科技美学

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

If missing intraday data (EG: the day is the new year holiday in Chinese, but it is the trading day in the US), as a result, it will have a shifting data problem on Backtrader.

The solution is to drop US trading day data.

underlying, df_base = underlying_list[sector], None
for ucode, size in underlying.items():
    # 数据校验
    df0 = yf.download(ucode, date_start, date_end, auto_adjust=False)
    df0.replace(0, np.nan, inplace=True)
    df0.dropna(inplace=True)
    df0.drop_duplicates(keep=False, inplace=True)
    df0 = df0[['Open', 'High', 'Low', 'Close', 'Volume', 'Adj Close']]

    # 同步市场时间
    if '.HK' in ucode:
        df0.index = df0.index.tz_localize("Asia/Shanghai").tz_convert("UTC")
        df0.index = df0.index + pd.DateOffset(1)
    else:
        df0.index = df0.index.tz_localize("America/New_York").tz_convert("UTC")
    df0['Date'] = pd.to_datetime(df0.index.date)
    df0 = df0.set_index(df0['Date'])

    # 删除非基准数据
    if df_base is None:
        df_base = df0
    else:
        df0 = df0[df0['Date'].isin(df_base['Date'])]

    # 加载数据
    data0 = bt.feeds.PandasData(dataname=df0)
    cerebro.adddata(data0, name=ucode)

  

posted on 2022-11-09 16:10  chankuang  阅读(31)  评论(0编辑  收藏  举报