回测收益回测年化收益基准收益AlphaBetaSharpe最大回撤 44.459%44.459%4.583%0.40620.44751.146626.855%
import pandas as pd import numpy as npfrom datetime import datetime, timedeltadef init(context): context.commission = 0 context.stocks = [] context.info = {} context.flag = -1 context.holdSize = 5 context.industry = ['I64', 'I65'] context.selectByIdt = True # 多空步长 context.inte = {'long':0.1,'short':-0.05} # context.tgtValue = [12,6,2,0,8,14,18,20] context.tgtValue = [10,8,4,2,0,6,12,16,18,20] context.c = 5 context.unitCash = 0 context.period = 130def getStkVar(stk) : #获取某只股票的波动率 his = history(180,'1d','close')[stk].values arr = np.array(his) sum1 = arr.sum() arr2 = arr*arr sum2 = arr2.sum() n = len(arr) mean = sum1/n var =sum2/n - mean**2 return var def doSelect (context, bar_dict): for stk in context.info.keys(): order_target_value(stk, 0) context.info = {} context.unitCash = context.portfolio.portfolio_value/(context.holdSize*20) stocks = [] for i in context.industry : stocks += industry(i) stocks = [stk for stk in stocks if stk in context.peBelow50] # stocks = index_components('000905.XSHG', date=None, country='cn') # stocks = index_components('000300.XSHG', date=None, country='cn') dic = {} for stk in stocks: dic[stk] = getStkVar(stk) s = pd.Series(dic) s.sort(ascending=False) context.stocks = s.index[:10] context.stocks = [stk for stk in context.stocks if not is_suspended(stk)] context.stocks = context.stocks[:context.holdSize] c = int(len(context.tgtValue)/2) prod = lambda x,i,n:x*(1+i*n) for stk in context.stocks: stk1 = {} stk1['initPrice'] = bar_dict[stk].close stk1['buy_price'] = [prod(stk1['initPrice'],context.inte['short'],n) for n in range(1,c+1)] stk1['sell_price'] = [prod(stk1['initPrice'],context.inte['long'],n) for n in range(1,c+1)] stk1['curValue'] = 0 context.info[stk]=stk1 def before_trading(context, bar_dict): context.flag +=1 if context.selectByIdt : fundamental_df = get_fundamentals( query().filter( fundamentals.eod_derivative_indicator.pe_ratio <50, fundamentals.eod_derivative_indicator.pe_ratio >0 ) ) context.peBelow50 = fundamental_df.columns.values# 你选择的证券的数据更新将会触发此段逻辑,例如日或分钟历史数据切片或者是实时数据切片更新def handle_bar(context, bar_dict): # 开始编写你的主要的算法逻辑 now = context.now if context.flag%context.period==0 and now.hour==9 and now.minute==31: doSelect(context, bar_dict) print (context.info) tgtValue = context.tgtValue for stk in context.info.keys(): info = context.info[stk] curPrice = bar_dict[stk].close i = context.c-1 while(i>=0): if curPrice>=info['sell_price'][i] and info['curValue']>tgtValue[i] : curValue = context.info[stk]['curValue'] order_value(stk, (tgtValue[i]-curValue)*context.unitCash) context.info[stk]['curValue'] = tgtValue[i] print ('卖出',curValue-tgtValue[i], '份', stk) break i -= 1 i = context.c-1 while(i>=0): if curPrice<=info['buy_price'][i] and info['curValue'] |
|
来自: 昵称36538943 > 《待分类》