Skip to content
All library documents

Preparing CSI 300 Constituents and Daily Bars for Research

Notebook vn.py

Summary

This data-preparation example builds a historical dataset for research on the CSI 300 and its constituent stocks. It retrieves the index membership history over a selected date range, converts provider-specific exchange symbols to the format used by the trading framework, and saves the dated constituent lists in a research lab. It then reloads the symbols and requests daily bars for each constituent and the index from a data service.

The workflow also assigns contract settings to constituent instruments, including long and short fee rates, contract size, and minimum price increment, so these assumptions can be used in later simulations. The document is procedural rather than analytical: it reports no strategy, data-quality checks, backtest results, or comparison of providers. Its usefulness depends on the chosen data service and the correctness of symbol mappings, historical membership records, timestamps, and instrument settings; those details should be checked before drawing research conclusions.

Key ideas

  • Historical index membership is retrieved by date and stored for later research.
  • Provider exchange suffixes are mapped to the trading framework's symbol convention.
  • Daily bars are collected for both constituent stocks and the index across the selected period.
  • Instrument fee rates, size, and price increments are configured for subsequent simulation.
  • The example does not describe validation of data quality or provide backtest evidence.

Tags

Full text
# 准备数据


# 准备数据

```python
# 加载模块
from datetime import datetime

from tqdm import tqdm
import rqdatac as rq

from vnpy.trader.database import DB_TZ
from vnpy.trader.datafeed import get_datafeed
from vnpy.trader.constant import Exchange, Interval
from vnpy.trader.object import HistoryRequest
from vnpy.alpha import AlphaLab, logger
```

```python
# 设置下载参数
task_name = "csi300"
index_symbol = "000300.SSE"
rq_index_symbol = "000300.XSHG"

start_date = "2007-01-01"
end_date = "2024-10-31"
```

```python
# 创建投研实验室
lab = AlphaLab(f"./lab/{task_name}")    # 指定数据文件夹
```

```python
# 初始化数据服务(这里配置使用的RQData)
datafeed = get_datafeed()
datafeed.init()
```

```python
# 下载指数成分股
data = rq.index_components(rq_index_symbol, start_date=start_date, end_date=end_date)

# 转换合约代码
index_components = {}
for dt, rq_symbols in data.items():
    vt_symbols: list = []

    for rq_symbol in rq_symbols:
        vt_symbol = rq_symbol.replace("XSHG", "SSE").replace("XSHE", "SZSE")
        vt_symbols.append(vt_symbol)

    index_components[dt.strftime("%Y-%m-%d")] = vt_symbols

# 保存到数据中心
lab.save_component_data(index_symbol, index_components)
```

```python
# 加载指数成分股代码
component_symbols = lab.load_component_symbols(index_symbol, start_date, end_date)
```

```python
# 转换时间格式
start = datetime.strptime(start_date, "%Y-%m-%d")
start = start.replace(tzinfo=DB_TZ)

end = datetime.strptime(end_date, "%Y-%m-%d")
end = end.replace(tzinfo=DB_TZ)

# 除了成分股,还要下载指数数据
task_symbols = component_symbols + [index_symbol]

# 遍历下载数据
for vt_symbol in tqdm(task_symbols):
    symbol, exchange_str = vt_symbol.split(".")

    req = HistoryRequest(symbol, Exchange(exchange_str), start, end, Interval.DAILY)
    bars = datafeed.query_bar_history(req)

    if bars:
        lab.save_bar_data(bars)
    else:
        logger.error(f"下载{vt_symbol}数据失败")

```

```python
# 添加回测参数配置
for vt_symbol in component_symbols:
    lab.add_contract_setting(
        vt_symbol,
        long_rate=5/10000,
        short_rate=10/10000,
        size=1,
        pricetick=0.0001,
    )
```

Shown in full with attribution under the source's licence. Licence: MIT

This summary was written by Stratmill's research agent from the original; it is not a copy of the source.