复制链接
克隆策略
In [ ]:
ds.resample('2H', label="right").agg({
    "open":"first",
    "close":"last",
    "high":"max",
    "low":"min",
    "volume":"sum",
    "amount":"sum"
}).dropna()
In [ ]:
ds.close.resample("2H", label="right").last().dropna()
In [18]:
ds = DataSource("bar1m_CN_STOCK_A").read(["000001.SZA"], start_date='2022-05-01')
# ds.set_index("date", inplace=True)
ds
Out[18]:
instrument date open close low high amount volume
0 000001.SZA 2022-05-05 09:31:00 15.20 15.25 15.15 15.34 67931488.0 4459499
1 000001.SZA 2022-05-05 09:32:00 15.27 15.36 15.27 15.45 33069885.0 2151984
2 000001.SZA 2022-05-05 09:33:00 15.36 15.42 15.36 15.43 25269261.0 1641000
3 000001.SZA 2022-05-05 09:34:00 15.41 15.37 15.35 15.41 13344959.0 867100
4 000001.SZA 2022-05-05 09:35:00 15.36 15.31 15.30 15.36 9013854.0 588100
... ... ... ... ... ... ... ... ...
2875 000001.SZA 2022-05-20 14:56:00 14.98 15.00 14.98 15.00 7103885.0 473779
2876 000001.SZA 2022-05-20 14:57:00 14.99 14.99 14.98 15.00 16252523.0 1083621
2877 000001.SZA 2022-05-20 14:58:00 14.99 14.99 14.99 14.99 86989.0 5800
2878 000001.SZA 2022-05-20 14:59:00 14.99 14.99 14.99 14.99 0.0 0
2879 000001.SZA 2022-05-20 15:00:00 14.99 15.02 14.99 15.02 35327040.0 2352000

2880 rows × 8 columns

In [13]:
def aggregate_to_period(df, period, align_dt_minute=0):
    default_agg_rules = {
        "open": "first",
        "high": "max",
        "low": "min",
        "close": "last",
        "volume": "sum",
        "amount": "sum",
        "turnover": "sum"
    }

    if isinstance(period, int):
        period_int = period
        period = str(period_int) + 'm'

    agg_rules = {}
    for column in df.columns:
        agg_rules[column] = default_agg_rules.get(column, "last")

    dt_column = "datetime" if "datetime" in df.columns else "date"
    if "trading_day" not in df.columns:
        df['trading_day'] = df['date'].dt.date

    first_dt = df[dt_column].iloc[0]
    if align_dt_minute > 0 and first_dt.minute != 1 and first_dt.minute != 31:
        for index, dt in enumerate(df[dt_column]):
            if (dt.minute == 1 and align_dt_minute
                    == 1) or (dt.minute == 31 and align_dt_minute == 31):
                df = df[index:]
                break

    day_df_list = []
    for _, day_df in df.groupby("trading_day"):
        idx = list(range(
            0, (len(day_df) + period_int) // period_int)) * period_int
        idx.sort()
        day_df["idx"] = idx[:len(day_df)]
        day_df = day_df.groupby("idx").agg(agg_rules)
        day_df.set_index(dt_column, inplace=True)
        day_df.reset_index(inplace=True)
        day_df_list.append(day_df)
    # xperiod_df["period"] = period
    xperiod_df = pd.concat(day_df_list)

    return xperiod_df
In [12]:
def aggregate_df(df, period, align_dt_minute=0):
    if isinstance(period, int):
        period_int = period
        period = str(period_int) + 'T'
    if period_int <= 1:
        return df

    symbol_key = "symbol" if "symbol" in df.columns else "instrument"
    dt_column = "datetime" if "datetime" in df.columns else "date"
    if len(df[symbol_key].unique()) == 1:
        return aggregate_to_period(df,
                                   period_int,
                                   align_dt_minute=align_dt_minute)

    symbol_dfs = []
    for _, symbol_df in df.groupby(symbol_key):
        symbol_df = aggregate_to_period(
            symbol_df, period_int, align_dt_minute=align_dt_minute)
        symbol_dfs.append(symbol_df)

    ret_df = pd.concat(symbol_dfs)
    ret_df.sort_values(dt_column, inplace=True)
    ret_df.reset_index(inplace=True)
    return ret_df
In [19]:
aggregate_df(ds, 120)
Out[19]:
date instrument open close low high amount volume
0 2022-05-05 11:30:00 000001.SZA 15.20 15.28 15.15 15.45 731913450.0 47908506
1 2022-05-05 15:00:00 000001.SZA 15.27 15.32 15.26 15.37 476821691.0 31111114
0 2022-05-06 11:30:00 000001.SZA 15.02 15.06 14.91 15.20 733195820.0 48769542
1 2022-05-06 15:00:00 000001.SZA 15.06 14.96 14.93 15.17 517799774.0 34473640
0 2022-05-09 11:30:00 000001.SZA 14.94 14.60 14.55 14.94 653172102.0 44407513
1 2022-05-09 15:00:00 000001.SZA 14.60 14.55 14.46 14.65 543932145.0 37454622
0 2022-05-10 11:30:00 000001.SZA 14.50 14.30 14.11 14.50 798609791.0 55933731
1 2022-05-10 15:00:00 000001.SZA 14.30 14.59 14.30 14.60 627227136.0 43294771
0 2022-05-11 11:30:00 000001.SZA 14.54 14.73 14.44 14.74 715012666.0 49086406
1 2022-05-11 15:00:00 000001.SZA 14.73 14.63 14.60 14.84 525687760.0 35770956
0 2022-05-12 11:30:00 000001.SZA 14.48 14.45 14.34 14.56 636711141.0 44158895
1 2022-05-12 15:00:00 000001.SZA 14.45 14.38 14.33 14.53 350350466.0 24347528
0 2022-05-13 11:30:00 000001.SZA 14.50 14.56 14.49 14.66 693161530.0 47544284
1 2022-05-13 15:00:00 000001.SZA 14.57 14.61 14.51 14.61 292801402.0 20086907
0 2022-05-16 11:30:00 000001.SZA 14.66 14.41 14.38 14.73 600715623.0 41470066
1 2022-05-16 15:00:00 000001.SZA 14.41 14.41 14.35 14.44 364936675.0 25352716
0 2022-05-17 11:30:00 000001.SZA 14.51 14.67 14.32 14.72 874572613.0 60217406
1 2022-05-17 15:00:00 000001.SZA 14.67 14.71 14.60 14.72 482855793.0 32923233
0 2022-05-18 11:30:00 000001.SZA 14.85 14.74 14.67 14.89 783937933.0 53060054
1 2022-05-18 15:00:00 000001.SZA 14.73 14.75 14.72 14.83 366562504.0 24797779
0 2022-05-19 11:30:00 000001.SZA 14.55 14.63 14.50 14.70 535312821.0 36642815
1 2022-05-19 15:00:00 000001.SZA 14.63 14.62 14.55 14.69 327901309.0 22449357
0 2022-05-20 11:30:00 000001.SZA 14.70 14.94 14.67 14.99 891774669.0 59937059
1 2022-05-20 15:00:00 000001.SZA 14.94 15.02 14.92 15.04 523390042.0 34922719

    {"description":"实验创建于2022/5/20","graph":{"edges":[{"to_node_id":"-236:instruments","from_node_id":"-261:data"}],"nodes":[{"node_id":"-236","module_id":"BigQuantSpace.hftrade.hftrade-v2","parameters":[{"name":"start_date","value":"","type":"Literal","bound_global_parameter":null},{"name":"end_date","value":"","type":"Literal","bound_global_parameter":null},{"name":"initialize","value":"# 交易引擎:初始化函数,只执行一次\ndef bigquant_run(context):\n # 加载预测数据\n context.ins = context.instruments[0]\n \n","type":"Literal","bound_global_parameter":null},{"name":"before_trading_start","value":"# 交易引擎:每个单位时间开盘前调用一次。\ndef bigquant_run(context, data):\n # 盘前处理,订阅行情等\n context.subscribe(context.ins)\n# context.subscribe_bar(context.ins, \"1m\")\n context.subscribe_bar(context.ins, \"11m\")\n","type":"Literal","bound_global_parameter":null},{"name":"handle_tick","value":"# 交易引擎:tick数据处理函数,每个tick执行一次\ndef bigquant_run(context, tick):\n pass\n","type":"Literal","bound_global_parameter":null},{"name":"handle_data","value":"# 交易引擎:bar数据处理函数,每个时间单位执行一次\ndef bigquant_run(context, data):\n print(data.current_dt, data.history(context.ins, [\"close\",\"high\",\"low\",\"open\"] , 10, '11m'))\n","type":"Literal","bound_global_parameter":null},{"name":"handle_trade","value":"# 交易引擎:成交回报处理函数,每个成交发生时执行一次\ndef bigquant_run(context, trade):\n pass\n","type":"Literal","bound_global_parameter":null},{"name":"handle_order","value":"# 交易引擎:委托回报处理函数,每个委托变化时执行一次\ndef bigquant_run(context, order):\n pass\n","type":"Literal","bound_global_parameter":null},{"name":"after_trading","value":"# 交易引擎:盘后处理函数,每日盘后执行一次\ndef bigquant_run(context, data):\n pass\n","type":"Literal","bound_global_parameter":null},{"name":"capital_base","value":1000000,"type":"Literal","bound_global_parameter":null},{"name":"frequency","value":"minute","type":"Literal","bound_global_parameter":null},{"name":"price_type","value":"真实价格","type":"Literal","bound_global_parameter":null},{"name":"product_type","value":"股票","type":"Literal","bound_global_parameter":null},{"name":"before_start_days","value":"10","type":"Literal","bound_global_parameter":null},{"name":"order_price_field_buy","value":"open","type":"Literal","bound_global_parameter":null},{"name":"order_price_field_sell","value":"close","type":"Literal","bound_global_parameter":null},{"name":"benchmark","value":"000300.HIX","type":"Literal","bound_global_parameter":null},{"name":"plot_charts","value":"True","type":"Literal","bound_global_parameter":null},{"name":"disable_cache","value":"False","type":"Literal","bound_global_parameter":null},{"name":"replay_bdb","value":"False","type":"Literal","bound_global_parameter":null},{"name":"show_debug_info","value":"False","type":"Literal","bound_global_parameter":null},{"name":"backtest_only","value":"False","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"instruments","node_id":"-236"},{"name":"options_data","node_id":"-236"},{"name":"history_ds","node_id":"-236"},{"name":"benchmark_ds","node_id":"-236"}],"output_ports":[{"name":"raw_perf","node_id":"-236"}],"cacheable":false,"seq_num":1,"comment":"","comment_collapsed":true},{"node_id":"-261","module_id":"BigQuantSpace.instruments.instruments-v2","parameters":[{"name":"start_date","value":"2022-03-01","type":"Literal","bound_global_parameter":null},{"name":"end_date","value":"2022-03-05","type":"Literal","bound_global_parameter":null},{"name":"market","value":"CN_STOCK_A","type":"Literal","bound_global_parameter":null},{"name":"instrument_list","value":"000001.SZA","type":"Literal","bound_global_parameter":null},{"name":"max_count","value":0,"type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"rolling_conf","node_id":"-261"}],"output_ports":[{"name":"data","node_id":"-261"}],"cacheable":true,"seq_num":2,"comment":"","comment_collapsed":true}],"node_layout":"<node_postions><node_position Node='-236' Position='152,451.24853515625,200,200'/><node_position Node='-261' Position='187,339,200,200'/></node_postions>"},"nodes_readonly":false,"studio_version":"v2"}
    In [ ]:
    # 本代码由可视化策略环境自动生成 2022年5月20日 18:55
    # 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
    
    
    # 交易引擎:初始化函数,只执行一次
    def m1_initialize_bigquant_run(context):
        # 加载预测数据
        context.ins = context.instruments[0]
        
    
    # 交易引擎:每个单位时间开盘前调用一次。
    def m1_before_trading_start_bigquant_run(context, data):
        # 盘前处理,订阅行情等
        context.subscribe(context.ins)
    #     context.subscribe_bar(context.ins, "1m")
        context.subscribe_bar(context.ins, "11m")
    
    # 交易引擎:tick数据处理函数,每个tick执行一次
    def m1_handle_tick_bigquant_run(context, tick):
        pass
    
    # 交易引擎:bar数据处理函数,每个时间单位执行一次
    def m1_handle_data_bigquant_run(context, data):
        print(data.current_dt, data.history(context.ins, ["close","high","low","open"] , 10, '11m'))
    
    # 交易引擎:成交回报处理函数,每个成交发生时执行一次
    def m1_handle_trade_bigquant_run(context, trade):
        pass
    
    # 交易引擎:委托回报处理函数,每个委托变化时执行一次
    def m1_handle_order_bigquant_run(context, order):
        pass
    
    # 交易引擎:盘后处理函数,每日盘后执行一次
    def m1_after_trading_bigquant_run(context, data):
        pass
    
    
    m2 = M.instruments.v2(
        start_date='2022-03-01',
        end_date='2022-03-05',
        market='CN_STOCK_A',
        instrument_list='000001.SZA',
        max_count=0
    )
    
    m1 = M.hftrade.v2(
        instruments=m2.data,
        start_date='',
        end_date='',
        initialize=m1_initialize_bigquant_run,
        before_trading_start=m1_before_trading_start_bigquant_run,
        handle_tick=m1_handle_tick_bigquant_run,
        handle_data=m1_handle_data_bigquant_run,
        handle_trade=m1_handle_trade_bigquant_run,
        handle_order=m1_handle_order_bigquant_run,
        after_trading=m1_after_trading_bigquant_run,
        capital_base=1000000,
        frequency='minute',
        price_type='真实价格',
        product_type='股票',
        before_start_days='10',
        order_price_field_buy='open',
        order_price_field_sell='close',
        benchmark='000300.HIX',
        plot_charts=True,
        disable_cache=False,
        replay_bdb=False,
        show_debug_info=False,
        backtest_only=False
    )