#!/usr/bin/env python
# encoding: utf-8
import numpy as np
from gmsdk import *
from talib import SMA
import time
class MA(StrategyBase):
def __init__(self, *args, **kwargs):
super(MA, self).__init__(*args, **kwargs)
self.close_list = []
bars = self.get_last_n_bars('SHSE.600009', 60, 20, '2016-01-01 00:00:00')
last_closes = [bar.close for bar in bars] # 提取每分钟收盘价
last_closes.reverse() # 查询出的结果为倒序,需反转
self.close_list.extend(last_closes)
def on_bar(self, bar):
if bar.bar_type == 60:
position = self.get_positions() # 获取持仓量
if len(position) == 0: ##如果没有持仓,设self.holding = 0
self.holding = 0
if len(position) > 0:
if position[0].available_yesterday > 0: # 如果有昨仓,设self.holding = 1
self.volume = position[0].available_yesterday
self.holding = 1
if position[0].available_today > 0: # 如果有今仓,设self.holding = 2
self.holding = 2
self.close_list.append(bar.close)
if len(self.close_list) < 20:
self.MA10 = self.close_list[:]
self.MA20 = self.close_list[:]
if len(self.close_list) >= 20:
close = np.asarray(self.close_list)
self.MA10 = SMA(close, timeperiod=10) # 10周期均线
self.MA20 = SMA(close, timeperiod=20) # 20周期均线
if self.holding == 0:
if self.MA10[-1] > self.MA20[-1]: # 10周期均线>20周期均线开仓
self.open_long('SHSE', '600009', 0, 10000)
if self.holding == 1:
if self.MA10[-1] < self.MA20[-1]: # 10周期均线<20周期均线平仓
self.close_long('SHSE', '600009', 0, self.volume)
if self.holding == 2:
pass
if __name__ == '__main__':
ma = MA(
username='username', # 输入用户名
password='password', # 输入密码
strategy_id='strategy_2', # 输入策略ID
subscribe_symbols='SHSE.600009.bar.60', # 输入订阅代码
mode=4, # 选择模式
td_addr='localhost:8001'
)
ma.backtest_config(
start_time='2016-01-01 09:00:00', # 起始时间
end_time='2017-01-01 09:00:00', # 结束时间
initial_cash=1000000, # 初始金额
transaction_ratio=1, # 成交比率
commission_ratio=0.0000, # 手续费
slippage_ratio=0.000, # 滑点
price_type=1)
start = time.time()
ret = ma.run()
end = time.time()
print(end - start)