运行提示:get_history_data版本较老,推荐使用get_market_data_ex替代,配合download_history_data补充昨日以前的K线数据。
问题是:应该如何修改?还有里面是否还有其他需要修改的函数?例如get_sector?还有set_universe?
- #coding=gbk
- #导入常用库
- import numpy as np
- import math
- #初始化函数,用于初始化策略
- def init(C):
- MarketPosition={} #初始化持仓字典
- C.MarketPosition=MarketPosition #将持仓字典存储在全局变量C中
- index_universe=['399381.SZ','399382.SZ','399383.SZ','399384.SZ','399385.SZ','399386.SZ'] #行业指数列表
- index_stocks=[] #存储行业指数下的所有股票
- for index in index_universe: #遍历每个行业指数
- for stock in C.get_sector(index): #获取该行业下的所有股票
- index_stocks.append(stock) #将股票添加到列表中
- C.set_universe(index_universe+index_stocks) #设定股票池,包括行业指数和行业内的所有股票
- C.day=20 #设置回测周期
- C.ratio=0.8 #设定资金比例
- C.holding_amount=5 #设定持仓数量为5只股票
- C.accountid='testS' #设定账户ID
-
- def handlebar(C):
- buy_condition=False #买入初始值为False
- sell_condition=False #卖出初始值为False
- d=C.barpos #获取当前K线值
- lastdate=timetag_to_datetime(C.get_bar_timetag(d-1),'%Y%m%d') #获取上一根K线的日期
- date=timetag_to_datetime(C.get_bar_timetag(d),'%Y%m%d') #获取当前K线日期
- print(date)
- index_list=['399381.SZ','399382.SZ','399383.SZ','399384.SZ','399385.SZ','399386.SZ'] #设定行业指数列表
- return_index=[] #建立空列表,用于存储行业指数收益率
- weight=C.ratio/C.holding_amount #计算每只股票的权重
- size_dict={} #设立空字典,存储股票市值
- if (float(date[-4:-2])!=float(lastdate[-4:-2])): #根据与钱一日的月份数据是否相同判断是否新的一个月
- his=C.get_history_data(21,'1d','close') #获取过去21个交易日的收盘价数据
- for k in list(his.keys()): #遍历历史数据
- if len(his[k])==0: #如果某只股票没有历史数据
- del his[k] #删除该股票
- for index in index_list: #遍历行业指数列表
- ratio=0 #初始化收益率
- try:
- ratio=(his[index][-2]-his[index][0])/his[index][0] #计算过去20个交易日的收益率
- except KeyError: #如果索引错误
- print('key error:'+index) #打印错误信息
- except IndexError: #如果列表索引越界
- print('list index out of range:'+index) #打印错误信息
- return_index.append(ratio) #将收益率添加在列表中
- #获取指定数内收益表现最好的行业
- best_index=index_list[np.argmax(return_index)]
- #获取最佳行业指数下当天有交易的股票
- index_stock=C.get_sector(best_index)
- stock_available=[] #建立空集,用于存储当天有交易股票
- for stock in index_stock:
- if C.is_suspended_stock(stock)==False:
- stock_available.append(stock)
- for stock in stock_available:
- if stock in list(his.keys()):
- #目前历史流通股本取不到,暂用总股本
- if len(his[stock])>=2:
- stocksize=his[stock][-2]*float(C.get_financial_data(['CAPITALSTRUCTURE.total_capital'],[stock],lastdate,date).iloc[0,-1])
- size_dict[stock]=stocksize
- elif len(his[stock])==1:
- stocksize=his[stock][-1]*float(C.get_financial_data(['CAPITALSTRUCTURE.total_capital'],[stock],lastdate,date).iloc[0,-1])
- size_dict[stock]=stocksize
- else:
- return
- size_sorted=sorted(list(size_dict.items()),key=lambda item:item[1])
- pre_holding=[]
- for tuple in size_sorted[-C.holding_amount:]:
- pre_holding.append(tuple[0])
- print('买入备选',pre_holding)
- #函数下单
- if len(pre_holding)>0:
- sellshort_list=[]
- for stock in list(C.MarketPosition.keys()):
- if stock not in pre_holding and (stock in list(his.keys())):
- order_shares(stock,-C.MarketPosition[stock],'lastest',histock[-1],C,C.accountid)
- print('sell',stock)
- sell_condition=True
- sellshort_list.append(stock)
- if len(sellshort_list)>0:
- for stock in sellshort_list:
- del C.MarketPosition[stock]
- for stock in pre_holding:
- if stock not in list(C.MarketPosition.keys()):
- Lots=math.floor(C.ratio*(1.0/len(pre_holding))*C.capital/(his[stock][-1]*100))
- order_shares(stock,Lots*100,'lastest',his[stock][-1],C,C.accountid)
- print('buy',stock)
- buy_condition=True
- C.MarketPosition[stock]=Lots*100
- C.paint('do_buy',int(buy_condition),-1,0)
- C.paint('do_sell',int(sell_cindition),-1,0)
-
复制代码 |