文档
测试

二八轮动策略

POST

说明 / 示例

```py #encoding:gbk ''' 本策略事先设定好交易的股票篮子,使用动量指标进行择时判断 当有超买和超卖发生时,进行开仓和平仓 ''' import pandas as pd import numpy as np import datetime def init(ContextInfo): #hs300成分股中sh和sz市场各自流通市值最大的前3只股票 ContextInfo.trade_code_list=['000300.SH','000905.SH'] ContextInfo.set_universe(ContextInfo.trade_code_list) ContextInfo.accID = '620000276629' def handlebar(ContextInfo): d = ContextInfo.barpos #当前K线索引号 time= timetag_to_datetime(ContextInfo.get_bar_timetag(d),'%Y%m%d %H:%M:%S') totalvalue = get_totalvalue(ContextInfo.accID,'STOCK') data = ContextInfo.get_history_data(period,'1d', 'close',1) #print (data['510300.SH']) #datanow = ContextInfo.get_history_data(1,'1d', 'close',1) hs300 = data['000300.SH'][0] zz500 = data['000905.SH'][0] cp300 = data['000300.SH'][-1] cp500 = data['000905.SH'][-1] ret300 = (cp300 - hs300) / cp300 ret500 = (cp500 - zz500) / cp500 hold300 = get_holding(ContextInfo.accID,'STOCK','510300') hold500 = get_holding(ContextInfo.accID,'STOCK','159922') #获取持仓 #hold300 = ContextInfo.get_market_data('quoter',['510300.SH'],start_time ='20200305', end_time ='20200306',skip_paused = True,period='1d',dividend_type = 'front',count = 1) #print(type(hold300)) if ret300<=0 and hold300>0: order_target_value('510300',0,ContextInfo,ContextInfo.accID) print("卖出300") elif ret500<=0 and hold500>0: order_target_value('159922',0,ContextInfo,ContextInfo.accID) print("卖出500") elif ret300>ret500 and ret300>0 and hold300==0 and hold500==0: order_target_value('510300',totalvalue,ContextInfo,ContextInfo.accID) print("买入300",time) elif ret500>ret300 and ret500>0 and hold300==0 and hold500==0: order_target_value('159922',totalvalue,ContextInfo,ContextInfo.accID) print("买入500",time) #调用模块:获取账户资金 def get_totalvalue(accountid,datatype): #(账号,商品类型) result=0 #设初值为0 resultlist=get_trade_detail_data(accountid,datatype,"ACCOUNT")#(账号,商品类型,账户类型) #print(resultlist) for obj in resultlist: result=obj.m_dAvailable #账户可用资金余额 #print(obj,result) return result #调用模块:获取对应股票持仓 def get_holding(accountid,datatype,stockcode): result = 0 resultlist=get_trade_detail_data(accountid,datatype,"POSITION")#(账号,商品类型,仓位) for obj in resultlist: if obj.m_strInstrumentID == stockcode: result = obj.m_nVolume #print(obj.m_strInstrumentID, obj.m_nVolume) return result def get_holding_code(accountid,datatype): result=[] resultlist = get_trade_detail_data(accountid,datatype,"POSITION")#(账号,商品类型,仓位) for obj in resultlist: result.append(obj.m_strInstrumentID) return result ```