forked from qmhedging/poboquant
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSMA例子 SMA Example
87 lines (78 loc) · 3.01 KB
/
SMA例子 SMA Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# coding:utf-8
#!/usr/bin/env python
from PoboAPI import *
import datetime
import numpy as np
#用poboquant python实现,在poboquant上运行,如果有问题 可加群 726895887 咨询
#开始时间,用于初始化一些参数
def OnStart(context) :
print "I\'m starting..."
#登录交易账号,需在主页用户管理中设置账号,并把证券测试替换成您的账户名称
context.myacc = None
if context.accounts.has_key("回测期货") :
print "登录交易账号[回测期货]"
if context.accounts["回测期货"].Login() :
context.myacc = context.accounts["回测期货"]
def OnMarketQuotationInitial(context, marketid):
if marketid != 'SHFE':
return
#获取主力合约
g.code = GetMainContract('SHFE', 'rb',20)
print g.code
#订阅实时数据,用于驱动OnQuote事件
SubscribeQuote(g.code)
#订阅K线数据,用于驱动OnBar事件
SubscribeBar(g.code, BarType.Day)
def OnOrderChange(context, AccountName, order) :
Test = context.accounts["回测期货"].GetOrder(order.id)
print str(Test.volume)
#实时行情事件,当有新行情出现时调用该事件
def OnBar(context,code,bartype) :
#过滤掉不需要的行情通知
if code != g.code:
return
dyndata = GetQuote(g.code)
#创建均线
option = PBObj()
klinedata = GetHisData(g.code, BarType.Day, option)
i=0
klist = []#初始化k线数据数组
while i<len(klinedata):
klist.append(klinedata[i].close)#存入k线收盘价数据
i+=1
if len(klist)>0:
sma5 = CreateCalcObj()
sma10 = CreateCalcObj()
X = np.array(klist, dtype=np.double)
MA5=sma5.SMA(X, 5,0.3, -2) #计算sma
MA10=sma10.SMA(X, 10,0.3, -2)
print "ma5 and ma10 length are "+str(MA5[-2])+" "+str(MA10[-2])
if len(MA10)<2:
return
#ma5上穿ma10时买入螺纹主力10手
elif MA5[-1] >= MA10[-1] and MA5[-2]<MA10[-2]:
print "to buy...."
context.myacc.InsertOrder(g.code, BSType.BuyOpen, dyndata.now, 10)
bal=context.accounts["回测期货"].AccountBalance.AssetsBalance
print "账户金额 :"+str(bal)
#orders = context.accounts["回测期货"].GetOrder(order.id)
#print str(orders.volume)
#OnOrderChange(context, "回测期货", order)
print "发生交易:"
option = PBObj()
option.buysellflag = '0'
TradeDetails = context.accounts["回测期货"].GetTradeDetails(option)
print TradeDetails
for i in TradeDetails:
print i
#print i.bstype.OffsetFlag
print '----------------'
pos = context.accounts["回测期货"].GetPositions(option)
print "期货持仓: ",pos
for i in pos:
print i.bstype.contract
print '----------------'
#ma5下穿ma10时卖出平仓
elif MA5[-1] <= MA10[-1] and MA5[-2]>MA10[-2]:
print "to sell..."
context.myacc.InsertOrder(g.code, BSType.SellClose, dyndata.now, 10)