def _get_data(self): from single_factor import OperationRevenueGrowth, EstimateNetRevenueGrowRateFY16M, FreeCashFlowPerShare, GrossIncomeRatio, ROC, EffectiveTaxRate, PS factor_list = [ OperationRevenueGrowth, EstimateNetRevenueGrowRateFY16M, FreeCashFlowPerShare, GrossIncomeRatio, ROC, EffectiveTaxRate, PS ] date_one_year = get_trading_date_from_now(self.date, -1, ql.Years) date_two_year = get_trading_date_from_now(self.date, -2, ql.Years) df = get_factor_from_wind_v2(self.code_list, factor_list, self.date) df_Revenue_growth_one_year = get_factor_from_wind_v2( self.code_list, [OperationRevenueGrowth], date_one_year) df_Revenue_growth_one_year.rename(columns={'营业收入增长率': '营业收入增长率_去年'}, inplace=True) df_FreeCashFlowPerShare_one_year = get_factor_from_wind_v2( self.code_list, [FreeCashFlowPerShare], date_one_year) df_FreeCashFlowPerShare_one_year.rename( columns={'每股企业自由现金流': '每股企业自由现金流_去年'}, inplace=True) df_FreeCashFlowPerShare_two_year = get_factor_from_wind_v2( self.code_list, [FreeCashFlowPerShare], date_two_year) df_FreeCashFlowPerShare_two_year.rename( columns={'每股企业自由现金流': '每股企业自由现金流_前年'}, inplace=True) df_temp = df['市销率'] * df['销售毛利率'] * 10.0 # 边际获利乘数即:销售毛利率*10 df = pd.concat([ df, df_Revenue_growth_one_year, df_FreeCashFlowPerShare_one_year, df_FreeCashFlowPerShare_two_year, df_temp ], axis=1) df.rename(columns={0: '高估/低估指数'}, inplace=True) df = df.dropna() return df
def init(context): global trading_date_list i = 0 print('回测开始日期:' + BACKTEST_START_DATE + ',结束日期:' + BACKTEST_END_DATE) while True: date_now = get_trading_date_from_now(BACKTEST_START_DATE, i, ql.Days) # 遍历每个交易日 print(('处理日期第%i个:' + date_now) % (i + 1)) dates_trading = [ get_trading_date_from_now( date_now.split('-')[0] + '-' + date_now.split('-')[1] + '-' + TRADING_DATE, 0, ql.Days) for TRADING_DATE in TRADING_DATES_LIST ] if date_now in dates_trading: trading_date_list.append(date_now) i += 1 if date_now == BACKTEST_END_DATE: break # 每天time_rule定时执行algo任务,time_rule处于09:00:00和15:00:00之间 print('时间列表整理完毕\n-----------------------------------------------\n') trading_date_list = [ d for d in trading_date_list if d.split('-')[1] in MONTHS ] # 按照选定的调仓月份进行筛选 schedule(schedule_func=algo, date_rule='daily', time_rule='10:00:00')
def __init__(self, backtest_start_date, backtest_end_date, N_list, M_list, industry_number=3): # N_list,M_list,S1_list,S2_list为计算各个行业指数的用到的参数 # industry_number为选择的行业数量 w.start() RSRS_start_date = get_trading_date_from_now( backtest_start_date, -max(N_list) - max(M_list) - 1, ql.Days) self.sw1_index_code = [t[0] for t in SW1_INDEX] data = w.wsd(self.sw1_index_code, "high", RSRS_start_date, backtest_end_date, "") self.RSRS_times = [t.strftime('%Y-%m-%d') for t in data.Times] self.RSRS_data_high = np.array(data.Data) # 格式为len(SW1_index) * 时间长度 data = w.wsd(self.sw1_index_code, "low", RSRS_start_date, backtest_end_date, "") self.RSRS_data_low = np.array(data.Data) # 格式为len(SW1_index) * 时间长度 # 时间序列的截取 self.backtest_start_date = backtest_start_date self.RSRS_cal_start_date = get_trading_date_from_now( backtest_start_date, -max(M_list) - 1, ql.Days) # 整理计算用的不同的时间序列 self.RSRS_raw_cal_times = self.RSRS_times[ self.RSRS_times.index(self.RSRS_cal_start_date):] self.RSRS_stand_cal_times = self.RSRS_times[ self.RSRS_times.index(self.backtest_start_date) - 1:] self.N_list = N_list # 计算RSRS指标采样的历史周期长短 self.M_list = M_list # 标准化序列的历史周期长短 self.date_list, self.signal_list = self._get_data() self.industry_number = industry_number
def __init__(self, backtest_start_date, backtest_end_date, index_code, N, M, S1=0.7, S2=-0.7): w.start() RSRS_start_date = get_trading_date_from_now(backtest_start_date, -N - M, ql.Days) data = w.wsd(index_code, "high,low,close", RSRS_start_date, backtest_end_date, "PriceAdj=T") self.RSRS_times = [t.strftime('%Y-%m-%d') for t in data.Times] self.RSRS_data_high = data.Data[0] self.RSRS_data_low = data.Data[1] self.RSRS_data = data.Data[2] self.backtest_start_date = backtest_start_date self.RSRS_cal_start_date = get_trading_date_from_now( backtest_start_date, -M, ql.Days) # 整理计算用的不同的时间序列 self.RSRS_raw_cal_times = self.RSRS_times[ self.RSRS_times.index(self.RSRS_cal_start_date):] self.RSRS_stand_cal_times = self.RSRS_times[ self.RSRS_times.index(self.backtest_start_date):] self.N = N # 计算RSRS指标采样的历史周期长短 self.M = M # 标准化序列的历史周期长短 self.S1 = S1 self.S2 = S2 super().__init__(backtest_start_date, backtest_end_date, index_code)
def algo(context): date_now = context.now.strftime('%Y-%m-%d') date_previous = get_trading_date_from_now(date_now, -1, ql.Days) # 前一个交易日,用于获取因子数据的日期 if date_now not in trading_date_list: # 非调仓日 pass # 预留非调仓日的微调空间 else: # 调仓日执行算法 print(date_now + '日回测程序执行中...') try: code_list = list_gm2wind( list( get_history_constituents( INDEX, start_date=date_previous, end_date=date_previous)[0]['constituents'].keys())) except IndexError: code_list = w.wset("sectorconstituent", "date=" + date_previous + ";windcode=" + INDEX).Data[1] I = trading_date_list.index(date_now) trading_dates = trading_date_list[I - HISTORY_LENGTH:I + 1] data_dfs = [] for i in range(len(trading_dates) - 1): date_start = get_trading_date_from_now( trading_dates[i], -1, ql.Days) # 计算因子值的日子,买入前一日的因子值 date_end = get_trading_date_from_now(trading_dates[i + 1], -1, ql.Days) # 计算收益率到期的日子-收盘 factors_df = get_factor_from_wind(code_list, FACTOR_LIST, date_start) # 获取因子 return_df = get_return_from_wind(code_list, date_start, date_end) factors_df_and_return_df = pd.concat( [factors_df, return_df], axis=1).dropna() # 去掉因子或者回报有空缺值的样本 factors_df_and_return_df = sort_data( factors_df_and_return_df) # 使用排序数据作为输入 data_dfs.append(factors_df_and_return_df) factors_return_df = pd.concat(data_dfs, axis=0) # 获取的最终训练数据拼接,return为目标 # 根据data_df训练模型 model = OrdinaryLinearRegression() model.fit(factors_return_df) # 根据factor_date_previous选取股票 factor_date_previous_df = get_factor_from_wind(code_list, FACTOR_LIST, date_previous).dropna() sorted_codes = model.predict( factor_date_previous_df) # 获取预测收益率从小到大排序的股票列表 sorted_codes = list_wind2jq(sorted_codes) # 根据股票列表下单 stock_codes = sorted_codes[-STOCK_NUMBER:] stock_now = {} for stock_code in stock_codes: # 平均持仓持股 stock_now[stock_code] = 1. / STOCK_NUMBER stock_dict[date_now] = stock_now
def __init__(self, backtest_start_date, backtest_end_date, index_code, N, M, S1=0.7, S2=-0.7): w.start() RSRS_start_date = get_trading_date_from_now(backtest_start_date, -N-M, ql.Days) data = w.wsd(index_code, "high,low,close", RSRS_start_date, backtest_end_date, "") self.RSRS_times = [t.strftime('%Y-%m-%d') for t in data.Times] self.RSRS_data_high = data.Data[0] self.RSRS_data_low = data.Data[1] self.RSRS_data = data.Data[2] self.backtest_start_date = backtest_start_date self.RSRS_cal_start_date = get_trading_date_from_now(backtest_start_date, -M, ql.Days) self.N = N # 计算RSRS指标采样的历史周期长短 self.M = M # 标准化序列的历史周期长短 self.S1 = S1 self.S2 = S2 self.date_list, _, self.signal_list = self._get_data()
def init(context): global date_trading # 调仓日期获取 i = 0 while True: print('处理日期:' + str(i)) date_now = get_trading_date_from_now(BACKTEST_START_DATE, i, ql.Days) # 遍历每个交易日 dates_trading = [get_trading_date_from_now(date_now.split('-')[0] + '-' + date_now.split('-')[1] + '-' + TRADING_DATE, 0, ql.Days) for TRADING_DATE in TRADING_DATES_LIST] if date_now in dates_trading: trading_date_list.append(date_now) i += 1 if date_now == BACKTEST_END_DATE: break # 每天time_rule定时执行algo任务,time_rule处于09:00:00和15:00:00之间 schedule(schedule_func=algo, date_rule='daily', time_rule='10:00:00')
def algo(context): global candidate_stock, selected_stock date_now = context.now.strftime('%Y-%m-%d') date_previous = get_trading_date_from_now(date_now, -1, ql.Days) # 前一个交易日,用于获取因子数据的日期 print(date_now + '日回测程序执行中...') if date_now not in trading_date_list: # 非调仓日 pass # 预留非调仓日的微调空间 else: # 调仓日执行算法 print(date_now + '日回测程序执行中...') # 根据指数获取股票候选池的代码 code_list = SelectedStockPoolFromListV1( INCLUDED_INDEX, EXCLUDED_INDEX, date_previous).get_stock_pool() strategy = STRATEGY(code_list, date_previous) candidate_stock = strategy.select_code() # 调仓日定期调节候选的股票池更新,非调仓日使用旧股票池 sw1_industry = get_SW1_industry(date_previous, candidate_stock) # 获取股票的申万一级行业信息字典 industry_wm_result = industry_wheel_movement[date_now] # 行业轮动内部自动替换为前一交易日 candidate_selected_stock = [ stock for stock in candidate_stock if sw1_industry[stock] is not None and industry_wm_result[sw1_industry[stock]] == 1 ] # 忽略无行业信息的股票并根据行业择时信号选择候选股票 if candidate_selected_stock == selected_stock: # 候选股状态与之前一样,不用任何操作 pass else: selected_stock = candidate_selected_stock # 更新已持股池的信息 if candidate_selected_stock == []: # 空仓信号 stock_dict[date_now] = {} else: candidate_selected_stock = list_wind2jq(candidate_selected_stock) stock_now = WEIGHTS(candidate_selected_stock, date_previous).get_weights() stock_dict[date_now] = stock_now
def __init__(self, backtest_start_date, backtest_end_date, index_code, L=50, N=3, Long=100, Threshold1=0.98, Threshold2=1.075): self.backtest_start_date = backtest_start_date # 策略参数设定 self.L = L self.N = N self.Long = Long self.Threshold1 = Threshold1 self.Threshold2 = Threshold2 # 基本数据获取 w.start() start_date = get_trading_date_from_now(backtest_start_date, -(max(L + N, Long) + 120), ql.Days) data = w.wsd(index_code, "close,amt", start_date, backtest_end_date, "") self.times = [t.strftime('%Y-%m-%d') for t in data.Times] # 日期序列 self.close = data.Data[0] # 价格序列 self.amt = data.Data[1] # 成交额序列 self._get_signal('2015-01-27') super().__init__(backtest_start_date, backtest_end_date, index_code)
def algo(context): date_now = context.now.strftime('%Y-%m-%d') date_previous = get_trading_date_from_now(date_now, -1, ql.Days) # 前一个交易日,用于获取因子数据的日期 if date_now not in trading_date_list: # 非调仓日 pass # 预留非调仓日的微调空间 else: # 调仓日执行算法 print(date_now + '日回测程序执行中...') try: code_list = list_gm2wind( list( get_history_constituents( INDEX, start_date=date_previous, end_date=date_previous)[0]['constituents'].keys())) except IndexError: code_list = w.wset("sectorconstituent", "date=" + date_previous + ";windcode=" + INDEX).Data[1] factor = FACTOR(date_previous, code_list, **FACTOR_COEFF) # 读取单因子的代码 df = factor.get_factor().dropna() quantiles = df.quantile(QUANTILE).values # 取对应的分位数值 stock_codes = list( df[(df[factor.factor_name] >= quantiles[0][0]) & (df[factor.factor_name] < quantiles[1][0])].index.values) stock_now = TRANSFER_FUNCTION(stock_codes, date_previous) # stock_now = {} # for stock_code in stock_codes: # stock_now[stock_code] = 1.0 / len(stock_codes) stock_dict[date_now] = stock_now
def __init__(self, backtest_start_date, backtest_end_date, index_code, llt_d, llt_cal_history=100, llt_threshold=0.0): ''' :param llt_d: 沪深300适合20,25 :param llt_cal_history: :param llt_threshold: ''' w.start() llt_start_date = get_trading_date_from_now(backtest_start_date, -llt_cal_history, ql.Days) data_std = w.wsd(index_code, "close", llt_start_date, backtest_end_date, "") # 指数收盘价数据 # 提取北上资金净流入数据 sh_data_base = w.wset("shhktransactionstatistics", "startdate=" + llt_start_date + ";enddate=" + backtest_end_date + ";cycle=day;currency=cny;field=date,sh_net_purchases") sh_data = sh_data_base.Data[1] sh_data_list = np.array([np.nan if i==None else i for i in sh_data]) sz_data = w.wset("szhktransactionstatistics", "startdate=" + llt_start_date + ";enddate=" + backtest_end_date + ";cycle=day;currency=cny;field=sz_net_purchases").Data[0] sz_data_list = np.array([np.nan if i==None else i for i in sz_data]) sum_list = sh_data_list + sz_data_list # 北上资金合计 sum_list = sum_list[::-1] # 数据倒序 # 整理北上资金净流入为pandas数据 df_sum_index = [t.strftime('%Y-%m-%d') for t in sh_data_base.Data[0]] df_sum_index.reverse() # w.wset和w.wss日期序列顺序是反的 此处做倒叙处理 df_sum = pd.DataFrame(data=sum_list, index=df_sum_index, columns=['total']) df_std_index = [t.strftime('%Y-%m-%d') for t in data_std.Times] df_std = pd.DataFrame(data=np.random.rand((len(df_std_index))), index=df_std_index, columns=['std']) target = pd.concat([df_std, df_sum], axis=1, ignore_index=True, sort=True) # 按照w.wss的index拼接df target = target.fillna(0) # 计算择时信号 self.llt_times = [t.strftime('%Y-%m-%d') for t in data_std.Times] self.llt_data = list(target[1].values) self.close_data = data_std.Data[0] self.llt_d = llt_d self.llt_threshold = llt_threshold self.llt_cal_history = llt_cal_history # LLT信号计算的历史长度 self.backtest_start_date = backtest_start_date super().__init__(backtest_start_date, backtest_end_date, index_code)
def algo(context): date_now = context.now.strftime('%Y-%m-%d') date_previous = get_trading_date_from_now(date_now, -1, ql.Days) # 前一个交易日,用于获取因子数据的日期 if date_now not in trading_date_list: # 非调仓日 pass # 预留非调仓日的微调空间 else: # 调仓日执行算法 print(date_now + '日回测程序执行中...') try: code_list = list_gm2wind( list( get_history_constituents( INDEX, start_date=date_previous, end_date=date_previous)[0]['constituents'].keys())) except IndexError: code_list = w.wset("sectorconstituent", "date=" + date_previous + ";windcode=" + INDEX).Data[1] strategy = STRATEGY(code_list, date_previous) select_code_list = list_wind2jq(strategy.select_code()) if len(select_code_list) > 0: # 有可选股票时选取合适的股票 stock_now = {} for code in select_code_list: stock_now[code] = 1.0 / len(select_code_list) stock_dict[date_now] = stock_now else: stock_dict[date_now] = {}
def algo(context): global position_now, position_target date_now = context.now.strftime('%Y-%m-%d') date_previous = get_trading_date_from_now(date_now, -1, ql.Days) # 前一个交易日,用于获取因子数据的日期 select_time_value = select_time_model[date_now] # 择时信号计算,择时内部自动替换为前一交易日 print(date_now + ('日回测程序执行中...,择时值:%.2f' % select_time_value)) if date_now not in trading_date_list: # 非调仓日 pass else: # 调仓日执行算法,更新position_target position_now = False # 虚拟上,调仓日需要提前清仓 stock_dict[date_now] = {} # 根据指数获取股票候选池的代码 code_list = SelectedStockPoolFromListV1( INCLUDED_INDEX, EXCLUDED_INDEX, date_previous).get_stock_pool() strategy = STRATEGY(code_list, date_previous, 0.9) select_code_list = list_wind2jq(strategy.select_code()) if len(select_code_list) > 0: # 有可选股票时记录下可选股票 stock_now = WEIGHTS(select_code_list, date_previous).get_weights() position_target = stock_now else: position_target = {} # 择时判定 if select_time_value >= 0 and not position_now and position_target != {}: # LLT择时信号为正,空仓且有目标持仓状态 stock_dict[date_now] = position_target position_now = True elif select_time_value < 0 and position_now and position_target != {}: # LLT择时信号为负且持仓状态: stock_dict[date_now] = {} position_now = False
def __init__(self, backtest_start_date, backtest_end_date, index_code, threshold=0.0, RPS_history=250, max_vol_diff_history=100): self.backtest_start_date = backtest_start_date # 策略参数设定 self.threshold = threshold self.RPS_history = RPS_history self.max_vol_diff_history = max_vol_diff_history # 提取数据 w.start() start_date = get_trading_date_from_now( backtest_start_date, -RPS_history - max_vol_diff_history - 30, ql.Days) data = w.wsd(index_code, "open, close, high, low", start_date, backtest_end_date, "") self.times = [t.strftime('%Y-%m-%d') for t in data.Times] # 日期序列 self.open = data.Data[0] self.close = data.Data[1] self.high = data.Data[2] self.low = data.Data[3] super().__init__(backtest_start_date, backtest_end_date, index_code)
def init(context): # 调仓日期获取 global trading_date_list BACKTEST_START_DATE_temp = get_trading_date_from_now( BACKTEST_START_DATE, -HISTORY_LENGTH - 1, ql.Months) trading_date_list = get_trading_date_list_by_day_monthly( BACKTEST_START_DATE_temp, BACKTEST_END_DATE, TRADING_DATES_LIST) # 每天time_rule定时执行algo任务,time_rule处于09:00:00和15:00:00之间 schedule(schedule_func=algo, date_rule='daily', time_rule='10:00:00')
def _get_data(self): from single_factor import ClosePrice, PE, DividendYield, NetTangibleAssetPerShare, NetLiquidAssetPerShare, TotalLiability, NetLiquidAsset, NetTangibleAsset, CurrentRatio, NetProfitGrowRateV2, PE_MAX factor_list = [ClosePrice, PE, DividendYield, NetTangibleAssetPerShare, NetLiquidAssetPerShare, TotalLiability, NetLiquidAsset, NetTangibleAsset, CurrentRatio, NetProfitGrowRateV2] # factor_list = [PE_MAX] # 待添加到上述列表,条件筛选不完整 df = get_factor_from_wind_v2(self.code_list, factor_list, self.date) date_temp_1 = get_trading_date_from_now(self.date, -3, ql.Days) # 取3天前国债收益率 yield_data = w.wss("TB" + str(self.N) + "Y.WI", "close", "tradeDate=" + str(date_temp_1) + ";priceAdj=U;cycle=D").Data[0][0] df = df.dropna() return df, yield_data
def __init__(self, backtest_start_date, backtest_end_date, index_code, llt_cal_history=100, llt_threshold=0.0, llt_d=39): w.start() llt_start_date = get_trading_date_from_now(backtest_start_date, -llt_cal_history, ql.Days) data = w.wsd(index_code, "close", llt_start_date, backtest_end_date, "") self.llt_times = [t.strftime('%Y-%m-%d') for t in data.Times] self.llt_data = data.Data[0] self.llt_d = llt_d self.llt_threshold = llt_threshold self.llt_cal_history = llt_cal_history # LLT信号计算的历史长度
def __getitem__(self, date_now): ''' :param date_now: 计算date_now前一天收盘后的择时指标 :return llt_value: 择时信号返回值,1为看多,-1为看空,0为不确定 ''' date_previous = get_trading_date_from_now(date_now, -1, ql.Days) index = self.date_list.index(date_previous) signal = self.signal_list[index] return signal
def 发布报告的模板1(): end_date = '2019-06-13' start_date = get_trading_date_from_now(end_date, -100, ql.Days) # RSRS模型 N = 18 M = 600 model = RSRS_standardization(start_date, end_date, '000300.SH', N=N, M=M) # 脉冲比模型 model = 脉冲比_银河(start_date, end_date, '000001.SH') # 单向波动差模型 model = 单向波动差_国信(start_date, end_date, '000300.SH')
def _get_data(self): from single_factor import NetProfitGrowRateV2, NetProfit, Revenue,PE factor_list = [NetProfitGrowRateV2, NetProfit,PE] df = get_factor_from_wind_v2(self.code_list, factor_list, self.date) date_temp = get_trading_date_from_now(self.date, -3, ql.Months) df_temp = get_factor_from_wind_v2(self.code_list, [NetProfitGrowRateV2, Revenue], date_temp) df_temp.rename(columns={'净利润增长率': '净利润增长率_3个月前'}, inplace=True) df_temp_1 = df['净利润增长率'] - df_temp['净利润增长率_3个月前'] df = pd.concat([df, df_temp, df_temp_1], axis=1) df.rename(columns={0: '差值'}, inplace=True) df = df.dropna() return df
def 发布报告的模板1(): end_date = '2019-06-28' start_date = get_trading_date_from_now(end_date, -100, ql.Days) # RSRS模型 N = 18 M = 600 model = RSRS_standardization(start_date, end_date, '000300.SH', N=N, M=M) # 脉冲比模型 model = 脉冲比_银河(start_date, end_date, '000001.SH') # 单向波动差模型 model = 单向波动差_国信(start_date, end_date, '000300.SH') # 北上资金LLT择时 model = 北上资金择时_LLT(start_date, end_date, '000300.SH', llt_d=20, llt_cal_history=30, llt_threshold=0.0)
def __init__(self, backtest_start_date, backtest_end_date, index_code, N, S1=1.0, S2=0.8): w.start() RSRS_start_date = get_trading_date_from_now(backtest_start_date, -N, ql.Days) data = w.wsd(index_code, "high,low,close", RSRS_start_date, backtest_end_date, "") self.RSRS_times = [t.strftime('%Y-%m-%d') for t in data.Times] self.RSRS_data_high = data.Data[0] self.RSRS_data_low = data.Data[1] self.RSRS_data = data.Data[2] self.backtest_start_date = backtest_start_date self.N = N # 计算RSRS指标采样的历史周期长短 self.S1 = S1 self.S2 = S2 super().__init__(backtest_start_date, backtest_end_date, index_code)
def _get_data(self): from single_factor import LCap, CurrentRatio, ROE, FreeCashFlowPerShare, OperationRevenueGrowth, NetProfitGrowRateV2 factor_list = [LCap, CurrentRatio, ROE, OperationRevenueGrowth, NetProfitGrowRateV2] df = get_factor_from_wind_v2(self.code_list, factor_list, self.date) # 五年自由现金流量 df_PE = [] for i in range(5): date_temp = get_trading_date_from_now(self.date, -i, ql.Years) df_temp = get_factor_from_wind_v2(self.code_list, [FreeCashFlowPerShare], date_temp) df_temp.rename(columns={'每股企业自由现金流指标': '每股企业自由现金流指标_' + str(i)}, inplace=True) df_PE.append(df_temp) df = pd.concat([df] + df_PE, axis=1) df = df.dropna() return df
def __getitem__(self, date_now): RSRS_value_result = {} date_previous = get_trading_date_from_now(date_now, -1, ql.Days) index = self.RSRS_stand_cal_times.index(date_previous) signal_date_now = self.signal_list[:, index] industry_selected_number = np.argsort(signal_date_now)[ -self.industry_number:] # ,按照RSRS标准化值从大到小排序,选取备选行业编号 for i in range(len(SW1_INDEX)): index = self.sw1_index_code[i] if i in industry_selected_number: RSRS_value_result[index] = 1 else: RSRS_value_result[index] = -1 return RSRS_value_result
def _get_data(self): from single_factor import PB, PE, DividendYield, PriceFreeCashFlowPerShare, LongTermLiabilityToWorkCapital factor_list = [PB, DividendYield, PriceFreeCashFlowPerShare, LongTermLiabilityToWorkCapital] df = get_factor_from_wind_v2(self.code_list, factor_list, self.date) # 五年PE值获取 df_PE = [] for i in range(5): date_temp = get_trading_date_from_now(self.date, -i, ql.Years) df_temp = get_factor_from_wind_v2(self.code_list, [PE], date_temp) df_temp.rename(columns={'市盈率PE': '市盈率_'+str(i)}, inplace=True) df_PE.append(df_temp) df = pd.concat([df]+df_PE, axis=1) df = df.dropna() return df
def algo(context): date_now = context.now.strftime('%Y-%m-%d') date_previous = get_trading_date_from_now(date_now, -1, ql.Days) # 前一个交易日,用于获取因子数据的日期 if date_now not in trading_date_list: # 非调仓日 pass # 预留非调仓日的微调空间 else: # 调仓日执行算法 print(date_now+'日回测程序执行中...') # 根据指数获取股票候选池的代码 select_code_list = list_wind2jq(INCLUDED_INDEX) if len(select_code_list) > 0: # 有可选股票时选取合适的股票 stock_now = WEIGHTS(select_code_list, date_previous).get_weights() stock_dict[date_now] = stock_now else: stock_dict[date_now] = {}
def __init__(self, backtest_start_date, backtest_end_date, index_code, threshold=1.5, hold_L=30, mean_L=5): self.backtest_start_date = backtest_start_date # 策略参数设定 self.threshold = threshold self.hold_L = hold_L self.mean_L = mean_L # 提取数据 w.start() start_date = get_trading_date_from_now(backtest_start_date, -mean_L-3, ql.Days) data = w.wsd(index_code, "amt, close", start_date, backtest_end_date, "") self.times = [t.strftime('%Y-%m-%d') for t in data.Times] # 日期序列 self.amt = data.Data[0] # 成交额数据 self.close = data.Data[1] # 价格序列 super().__init__(backtest_start_date, backtest_end_date, index_code)
def _get_data(self): from single_factor import DebetToAsset, CFPS, MarketValueToFreeCashFlow, NetProfitGrowRateV2, DividendYield, PE, InventoryTurnRatio factor_list = [DebetToAsset, CFPS, MarketValueToFreeCashFlow, NetProfitGrowRateV2, DividendYield, PE] factor_InvTurn_now = [InventoryTurnRatio] factor_InvTurn_one_year = [InventoryTurnRatio] date_one_year = get_trading_date_from_now(self.date, -1, ql.Years) df = get_factor_from_wind_v2(self.code_list, factor_list, self.date) # 存货增长率与营收增长率的比较判断数据,使用存货周转率判断 df_invturn_now = get_factor_from_wind_v2(self.code_list, factor_InvTurn_now, self.date) df_invturn_now.rename(columns={'存货周转率': '存货周转率_今年'}, inplace=True) df_invturn_one_year = get_factor_from_wind_v2(self.code_list, factor_InvTurn_one_year, date_one_year) df_invturn_one_year.rename(columns={'存货周转率': '存货周转率_去年'}, inplace=True) df = pd.concat([df, df_invturn_now, df_invturn_one_year], axis=1) df = df.dropna() return df
def __init__(self, backtest_start_date, backtest_end_date, index_code, llt_d, llt_cal_history=100, llt_threshold=0.0): ''' :param llt_d: 上证综指适合参数39 :param llt_cal_history: :param llt_threshold: ''' w.start() llt_start_date = get_trading_date_from_now(backtest_start_date, -llt_cal_history, ql.Days) data = w.wsd(index_code, "close", llt_start_date, backtest_end_date, "") self.llt_times = [t.strftime('%Y-%m-%d') for t in data.Times] self.llt_data = data.Data[0] self.llt_d = llt_d self.llt_threshold = llt_threshold self.llt_cal_history = llt_cal_history # LLT信号计算的历史长度 self.backtest_start_date = backtest_start_date super().__init__(backtest_start_date, backtest_end_date, index_code)
def algo(context): date_now = context.now.strftime('%Y-%m-%d') date_previous = get_trading_date_from_now(date_now, -1, ql.Days) # 前一个交易日,用于获取因子数据的日期 if date_now not in trading_date_list: # 非调仓日 pass # 预留非调仓日的微调空间 else: # 调仓日执行算法 print(date_now+'日回测程序执行中...') # 根据指数获取股票候选池的代码 if len(stock_pool) > 0: # 有可选股票时选取合适的股票 stock_now = 风险预算组合_模块求解基本版_带约束(stock_pool, date_previous, risk_budget=risk_budget, bounds=risk_bounds).get_weights() stock_now['161716.XSHE'] = 0.09 stock_now['167501.XSHE'] = 0.06 stock_now['511010.XSHG'] = stock_now['511010.XSHG'] - 0.15 print(stock_now) stock_dict[date_now] = stock_now else: stock_dict[date_now] = {}