1、下面这个模型是系统自带的“py回测模型示例”修改而来的,可以正常回测,可以看到历史成交以及收益情况。
2、获取行情数据以后,print(high*2)能够输出,而且是一个数字;为什么能够打印出,但在开仓的时候,如果我把“if m5 >= m20:”改为“if high>=m20”的时候显示错误?
3、如何在开仓条件里引用输出的最高价,比如“最高价high>=m20"?
#coding:gbk
#!/usr/bin/python
import time, datetime
import numpy as np
s = ['600000.SH','600004.SH','000001.SZ','000002.SZ']
def init(ContextInfo):
ContextInfo.set_universe(s)
ContextInfo.benchmark=ContextInfo.stockcode+"."+ContextInfo.market
ContextInfo.tmp = {i:0 for i in s}
def handlebar(ContextInfo):
d = ContextInfo.barpos
realtime = ContextInfo.get_bar_timetag(d)
nowdate = timetag_to_datetime(realtime,'%Y-%m-%d')
ContextInfo.holdings=get_holdings('testS','STOCK')
last20s=ContextInfo.get_history_data(21,'1d','close')
count=0
buyNumber = 0
buyAmount = 0
sellNumber = 0
sellAmount = 0
for k ,closes in list(last20s.items()):
if len(closes)<21:
continue
pre=closes[-1]
m20=np.mean(closes[:20])
m5=np.mean(closes[-6:-1])
df = ContextInfo.get_market_data(['close', 'high','low','open','amount'], stock_code =ContextInfo.get_universe(), skip_paused = True, period = '1d', dividend_type ='front', count = -1)
close=df['close']
high=df['high']
low=df['low']
open=df['open']
amount=df['amount']
print(high*2)
if ContextInfo.tmp[k] == 0:
if m5 >= m20:
ContextInfo.tmp[k] = 0
else:
ContextInfo.tmp[k] = 1
else:
if m5 <= m20:
if k in ContextInfo.holdings:
sellNumber += 1
sellAmount += float(ContextInfo.holdings[k]) * pre
order_shares(k,-float(ContextInfo.holdings[k]),"FIX",pre,ContextInfo,"testS")
del ContextInfo.holdings[k]
print('卖出%s'%k)
else:
if k not in ContextInfo.holdings:
ContextInfo.holdings[k] = 500
buyNumber += 1
buyAmount += float(ContextInfo.holdings[k]) * pre
order_shares(k,float(ContextInfo.holdings[k]),"FIX",pre,ContextInfo,"testS")
print('买入%s'%k)
ContextInfo.paint("buy_num", buyNumber, -1, 0)
ContextInfo.paint("sell_num", sellNumber, -1, 0)
def get_holdings(accountid,datatype):
holdinglist={}
resultlist=get_trade_detail_data(accountid,datatype,"POSITION")
for obj in resultlist:
holdinglist[obj.m_strInstrumentID+"."+obj.m_strExchangeID]=obj.m_nVolume
return holdinglist
|