目录
一、策略的基础概念二、ma20-5min策略实现1 - 新建类AstockTrading并添加构造方法2 - 方法说明3 - 完整源码一、策略的基础概念
MA概念:移动平均线,Moving Average,简称MA,MA是用统计分析的方法,将一定时期内的证券价格(指数)加以平均,并把不同时间的平均值连接起来,形成一根MA,用以观察证券价格变动趋势的一种技术指标MA查看:招商银行查看 -> 点击指标 -> 搜索ma -> 点击“移动平均线”5 minutes ma20:5分钟,MA20是指取最近100分钟的第5分钟、10分钟、15分钟……100分钟(20个价格)股票的收盘价的平均值
二、ma20-5min策略实现
1 - 新建类AstockTrading并添加构造方法
class AstockTrading(object):def __init__(self, stock_code):self.stock_code = stock_codeself._Dt = [] # 交易时间self._Open = [] # 开盘价self._High = [] # 最高价self._Low = [] # 最低价self._Close = [] # 收盘价self._Volume = []self._tick = None # 数据self._last_bar_start_minute = None # 最后一次更新bar的时间self._isNewBar = False # 是否有新bar# 当前订单,dict, 字典self._current_orders = {'order1': {'open_price': 1,'open_datetime': '-10-22 9:00','comment': {}}}# 历史订单self._history_orders = {}
2 - 方法说明
get_tick:获取当前的数据get_history_data_from_local_machine:加载历史数据bar_generator:生成bar_buy:买入_sell:卖出strategy:执行策略3 - 完整源码
以下代码还未进行回测,仅仅参考思路,需要可运行的请参考后续的文章
import requestsfrom time import sleepfrom datetime import datetime, timefrom dateutil import parser# __init__,构造,初始化,实例化class AstockTrading(object):def __init__(self, strategy_name):self._strategy_name = strategy_nameself._Dt = [] # 交易时间self._Open = [] # 开盘价self._High = [] # 最高价self._Low = [] # 最低价self._Close = [] # 最新价self._Volume = []self._tick = [] # 数据self._last_bar_start_minute = None # 最后一次更新bar的时间self._isNewBar = False # 是否有新barself._ma20 = None# 当前订单,dict, 字典self._current_orders = {}# 历史订单self._history_orders = {}self._order_number = 0def get_tick(self):headers = {'Referer': ""}page = requests.get("/list=sh600519", headers=headers)stock_info = page.textmt_info = stock_info.replace("\"", "").split("=")[1].split(",")# 最新价last = float(mt_info[1])trade_datetime = mt_info[30] + ' ' + mt_info[31]self._tick = (trade_datetime, last)def get_history_data_from_local_machine(self):# tushare 数据来源# self.Open = [1, 2, 3]# self.High = [2, 3, 4]pass# how save and import history data?# 策略def bar_generator(self):# assume we have history data already# 1、update bars,calculate 5 minutes ma20 , not daily data# 2、compare last and ma20 -> buy or sell or pass# assume we have history data,Open,High,Low,Close,Dt# 这里可以是5minutes、10minutes、15minutes、20minutes、30minutesif self._tick[0].minute % 5 == 0 and self._tick[0].minute != self._last_bar_start_minute:self._last_bar_start_minute = self._tick[0].minuteself._Open.insert(0, self._tick[1])self._High.insert(0, self._tick[1])self._Low.insert(0, self._tick[1])self._Close.insert(0, self._tick[1])self._Dt.insert(0, self._tick[0])self._isNewBar = Trueelse:# update current barself._High[0] = max(self._High[0], self._tick[1])self._Low[0] = max(self._Low[0], self._tick[1])self._Close[0] = self._tick[1]self._Dt[0] = self._tick[0]self._isNewBar = Falsedef _buy(self, price, volume):# create an orderself._order_number += 1key = "order" + str(self._order_number)self._current_orders[key] = {"open_datetime": self._Dt[0],"open_price": price,"volume": volume # 股数}passdef _sell(self, key, price):self._current_orders[key]['close_price'] = priceself._current_orders[key]['close_datetime'] = self._Dt[0]# move order from current orders to history ordersself._history_orders[key] = self._current_orders.pop(key)def strategy(self):# last < 0.95 *ma20 ,long position(仓位), last > ma20 *1.05, sellif self._isNewBar:sum_ = 0for item in self._Close[1:21]:sum_ = sum_ + itemself._ma20 = sum_ / 20if 0 == len(self._current_orders):if self._Close[0] < 0.95 * self._ma20:# 100000/44.28 = 2258 44.28是当前价格,10万指的你拥有的钱# 2258 -> 2200 sharesvolume = int(100000 / self._Close[0] / 100) * 100self._buy(self._Close[0] + 0.01, volume) # 这里的0.01是为了防止挂单,我们需要即可买入elif 1 == len(self._current_orders):if self._Close[0] > self._ma20 * 1.05:key = self._current_orders.keys()[0]self._sell(key, self._Close[0] - 0.01)else: # len() = 2raise ValueError("we have more then 1 current orders")# Close[0] in between 0.95*ma20 and 1.05*ma20,do nothingma = AstockTrading('600036') # 类实例化ma.get_history_data_from_local_machine()# 交易时间是9:30-11:30,13:00-15:00while time(9, 26) < datetime.now().time() < time(11, 32) \or time(13) < datetime.now().time() < time(15, 2):ma.get_tick()ma.bar_generator()ma.strategy()# trade_time = parser.parse(ma._tick[0]).time()# sleep(3)