复制链接
克隆策略

    {"description":"实验创建于2022/4/11","graph":{"edges":[{"to_node_id":"-5976:instruments","from_node_id":"-5963:data"},{"to_node_id":"-5976:features","from_node_id":"-5971:data"},{"to_node_id":"-5983:features","from_node_id":"-5971:data"},{"to_node_id":"-5983:input_data","from_node_id":"-5976:data"}],"nodes":[{"node_id":"-5963","module_id":"BigQuantSpace.instruments.instruments-v2","parameters":[{"name":"start_date","value":"2018-01-01","type":"Literal","bound_global_parameter":null},{"name":"end_date","value":"2022-04-22","type":"Literal","bound_global_parameter":null},{"name":"market","value":"CN_STOCK_A","type":"Literal","bound_global_parameter":null},{"name":"instrument_list","value":"","type":"Literal","bound_global_parameter":null},{"name":"max_count","value":0,"type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"rolling_conf","node_id":"-5963"}],"output_ports":[{"name":"data","node_id":"-5963"}],"cacheable":true,"seq_num":1,"comment":"","comment_collapsed":true},{"node_id":"-5971","module_id":"BigQuantSpace.input_features.input_features-v1","parameters":[{"name":"features","value":"close_0\nopen_0\nprice_limit_status_0\nreturn_0\nmaxhigh100=ts_max(high_0, 100)\nflag=where(close_0>shift(maxhigh100,1),1,0)\n","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"features_ds","node_id":"-5971"}],"output_ports":[{"name":"data","node_id":"-5971"}],"cacheable":true,"seq_num":2,"comment":"","comment_collapsed":true},{"node_id":"-5976","module_id":"BigQuantSpace.general_feature_extractor.general_feature_extractor-v7","parameters":[{"name":"start_date","value":"","type":"Literal","bound_global_parameter":null},{"name":"end_date","value":"","type":"Literal","bound_global_parameter":null},{"name":"before_start_days","value":"0","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"instruments","node_id":"-5976"},{"name":"features","node_id":"-5976"}],"output_ports":[{"name":"data","node_id":"-5976"}],"cacheable":true,"seq_num":3,"comment":"","comment_collapsed":true},{"node_id":"-5983","module_id":"BigQuantSpace.derived_feature_extractor.derived_feature_extractor-v3","parameters":[{"name":"date_col","value":"date","type":"Literal","bound_global_parameter":null},{"name":"instrument_col","value":"instrument","type":"Literal","bound_global_parameter":null},{"name":"drop_na","value":"False","type":"Literal","bound_global_parameter":null},{"name":"remove_extra_columns","value":"False","type":"Literal","bound_global_parameter":null},{"name":"user_functions","value":"{}","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"input_data","node_id":"-5983"},{"name":"features","node_id":"-5983"}],"output_ports":[{"name":"data","node_id":"-5983"}],"cacheable":true,"seq_num":4,"comment":"","comment_collapsed":true}],"node_layout":"<node_postions><node_position Node='-5963' Position='161,86,200,200'/><node_position Node='-5971' Position='468,88,200,200'/><node_position Node='-5976' Position='264,190,200,200'/><node_position Node='-5983' Position='270,298,200,200'/></node_postions>"},"nodes_readonly":false,"studio_version":"v2"}
    In [48]:
    # 本代码由可视化策略环境自动生成 2022年4月24日 14:48
    # 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
    
    
    m1 = M.instruments.v2(
        start_date='2018-01-01',
        end_date='2022-04-22',
        market='CN_STOCK_A',
        instrument_list='',
        max_count=0
    )
    
    m2 = M.input_features.v1(
        features="""close_0
    open_0
    price_limit_status_0
    return_0
    maxhigh100=ts_max(high_0, 100)
    flag=where(close_0>shift(maxhigh100,1),1,0)
    """
    )
    
    m3 = M.general_feature_extractor.v7(
        instruments=m1.data,
        features=m2.data,
        start_date='',
        end_date='',
        before_start_days=0
    )
    
    m4 = M.derived_feature_extractor.v3(
        input_data=m3.data,
        features=m2.data,
        date_col='date',
        instrument_col='instrument',
        drop_na=False,
        remove_extra_columns=False,
        user_functions={}
    )
    
    In [36]:
    #计算下一个交易日的收益
    df_total = m4.data.read()
    
    #获取指数数据
    df_index_000905 = DataSource('bar1d_index_CN_STOCK_A').read(instruments=['000905.HIX'], start_date='2018-01-01')
    df_index_000905['returns'] = (df_index_000905.close / df_index_000905.close.shift(1) -1) + 1
    df_index_000905['中证500'] = df_index_000905['returns'].cumprod()
    df_index_000905['中证500'] = df_index_000905['中证500'] .fillna(1)
    
    #涨停和跌停数
    def cal_limit(x):
        x['涨停数'] = len(x[x.price_limit_status_0==3])
        x['跌停数'] = len(x[x.price_limit_status_0==1])
        x['上涨数'] = len(x[x.return_0>1])
        return x
    df_limit = df_total.groupby('date').apply(cal_limit)
    df_limit = df_limit.drop_duplicates(subset=['date'],keep='last').sort_values('date').reset_index()
    df_limit = pd.merge(left=df_limit,right=df_index_000905[['date','中证500']],left_on='date',right_on='date')
    
    #与指数合并
    options = {'chart': {'type': 'spline', 'height': 600},}
    T.plot(df_limit[['date','涨停数','跌停数','中证500']].set_index('date'),title='每日涨停跌停数',panes=[['涨停数', '跌停数', '60%'], ['中证500', '40%']],options=options)
    
    #上涨股票数
    T.plot(df_limit[['上涨数','date','中证500']].set_index('date'),title='每日上涨股票数',panes=[['上涨数', '60%'], ['中证500','40%']],options=options)
    #计算下一日收益率和前一日涨停状态
    def cal(x):
        x = x.sort_values('date')
        x['next_return'] = x.return_0.shift(-1)
        x['pre_limit_status_0'] = x.price_limit_status_0.shift(1)
        return x
    df_total = df_total.groupby('instrument').apply(cal)
    
    In [37]:
    import talib as ta
    #根据收益率计算指数净值
    df_yj = df_total.copy().reset_index(drop=True)
    df_yj = df_yj[df_yj.price_limit_status_0==3]
    #获取交易日为了填充空值
    df_trade = DataSource("trading_days").read(start_date="2018-01-01")
    df_trade = df_trade[df_trade.country_code=='CN']
    df_trade.sort_values('date')
    
    def cal_return(x):
        return x.next_return.mean()
    df_yj = df_yj.groupby('date').apply(cal_return)
    df_yj = pd.DataFrame(df_yj).rename(columns={0:'return'})
    df_yj = pd.merge(left=df_trade,right=df_yj,left_on='date',right_index=True,how='left')
    df_yj = df_yj.set_index('date')
    df_yj['return'] = df_yj['return'].fillna(1)
    df_yj['return'] = df_yj['return'].shift(1)
    df_yj['return'] = df_yj['return'].fillna(1)
    df_yj['净值'] = df_yj['return'].cumprod()
    
    N = 5
    df_yj["rsi"] = ta.RSI(df_yj['return'].values, timeperiod=N)
    #合并指数数据
    df_yj = pd.merge(left=df_yj,right=df_index_000905[['date','中证500']],left_on='date',right_on='date')
    df_yj = df_yj.set_index('date')
    T.plot(df_yj[['净值']],title='涨停溢价')
    options = {'chart': {'type': 'spline', 'height': 600},}
    T.plot(df_yj[['rsi','中证500']],panes=[['rsi', '60%'], ['中证500','40%']],options=options,title='涨停溢价RSI')
    
    In [38]:
    #昨日连扳指数
    df_lb = df_total.copy().reset_index(drop=True)
    df_lb = df_lb[(df_lb.price_limit_status_0==3)&(df_lb.pre_limit_status_0==3)]
    
    def cal_return(x):
        return x.next_return.mean()
    df_lb = df_lb.groupby('date').apply(cal_return)
    df_lb = pd.DataFrame(df_lb).rename(columns={0:'return'})
    df_lb['return'] = df_lb['return'].shift(1)
    df_lb['return'] = df_lb['return'].fillna(1)
    df_lb['净值'] = df_lb['return'].cumprod()
    T.plot(df_lb['净值'])
    
    In [50]:
    #计算每个行业的百日新高股票数
    df_industry = DataSource("industry_CN_STOCK_A").read(start_date="2018-01-01")
    df_basic_industry = DataSource("basic_info_IndustrySw").read()
    df_basic_industry = df_basic_industry[df_basic_industry.version==2021]
    #股票数据
    df_stock = m4.data.read()
    df_result = pd.merge(left=df_stock,right=df_industry[['instrument','date','industry_sw_level1']],on=['instrument','date'],how='left')
    df_result = df_result.dropna(subset=['industry_sw_level1'])
    df_result['industry_sw_level1'] = df_result['industry_sw_level1'].astype(int).astype(str)
    df_result = pd.merge(left=df_result,right=df_basic_industry[['code','name']],left_on='industry_sw_level1',right_on='code',how='left')
    
    #按照时间分类计算行业的数据
    def cal_industry(x):
        return x.groupby('name').apply(lambda x:len(x[x.flag==1]))
    df_result = df_result.groupby('date').apply(cal_industry)
    
    In [61]:
    #转换成宽表格式
    df_tmp = pd.DataFrame(df_result)
    df_tmp = df_tmp.reset_index()
    df_tmp = df_tmp.pivot(index='date',columns='name',values=0)
    df_tmp = df_tmp.fillna(method='bfill')
    
    #画出某个行业的百日新高数走势图
    T.plot(df_tmp[['医药生物']],title='百日新高数')
    
    #画图最近几日各板块百日新高数占比趋势
    df_day_pct_tmp = df_tmp.copy()
    df_day_pct_tmp['合计'] = df_tmp.sum(axis=1)
    df_day_pct_tmp.index = df_day_pct_tmp.index.strftime('%Y-%m-%d')
    #画出最近5日的情况
    for date in df_day_pct_tmp.index[-3:]:
        df_day_pct = df_day_pct_tmp[df_day_pct_tmp.index==date]
        total = df_day_pct.iloc[0]['合计']
    
        df_day_pct = df_day_pct.T
        #求出每个行业百日新高数占比
        df_day_pct['pct'] = df_day_pct.iloc[0:-1,0]/total
        df_day_pct=df_day_pct.iloc[0:-2]['pct']
        #只取有涨停的板块
        df_day_pct = df_day_pct[df_day_pct>0]
        df_day_pct = df_day_pct.sort_values(ascending=False)
        options={'title': {'text': "百日新高行业占比"+date},'chart': {'type': 'column'}}
        T.plot(df_day_pct,options=options)