四均线交易系统

策略说明

基于4均线系统进行判断交易
系统构成

(5和20周期均线), (3和10周期均线)构成的两组不同周期的均线组合
入场条件

当2组均线均成空头排列时且当前价低于上根BAR最低价入场
出场条件

1 小周期空头均线组合成多头排列
2 两组多头均线分别多头排列且低于上根BAR最高价出场
import numpy as np
import talib as ta
import pandas as pd
from collections import deque

class DataCenter():
keys = [u’openPrice’, u’highPrice’, u’lowPrice’, u’closePrice’, u’turnoverVol’]
def init(self, refresh_rate, pipe_length):
self.data = {key:deque([], maxlen=pipe_length) for key in (self.keys + [‘tradeTime’])}
self.refresh_rate = refresh_rate
self.pipe_length = pipe_length

def update_data(self, symbol):
    if len(self.data['openPrice']) < self.pipe_length:
        hist = history(symbol=symbol, attribute=self.keys, time_range=self.refresh_rate*self.pipe_length, freq='m', rtype='frame')[symbol]
    else:
        hist = history(symbol=symbol, attribute=self.keys, time_range=self.refresh_rate, freq='m', rtype='frame')[symbol]
    # hist.index = range(len(hist))
    current_data = {key:[] for key in (self.keys + ['tradeTime'])}

    for i in range(len(hist)/self.refresh_rate):
        current_bar = hist[self.refresh_rate*i:self.refresh_rate*(i+1)]
        current_data['closePrice'].append(current_bar.ix[len(current_bar)-1, 'closePrice'])
        current_data['openPrice'].append(current_bar.ix[0, 'openPrice'])
        current_data['highPrice'].append(current_bar['highPrice'].max())
        current_data['lowPrice'].append(current_bar['lowPrice'].min())
        current_data['turnoverVol'].append(current_bar['turnoverVol'].sum())
        current_data['tradeTime'].append(current_bar.index[len(current_bar)-1])
    for i in self.keys:
        for j in current_data[i]:
            self.data[i].append(j) 
    return self.data

import numpy as np
universe = [‘RBM0’] # 策略期货合约
start = ‘2016-01-01’ # 回测开始时间
end = ‘2016-02-07’ # 回测结束时间
refresh_rate = 5 # 调仓周期
freq = ‘m’ # 调仓频率:m-> 分钟;d-> 日

lefast = 5 # 多头入场短均线周期参数
leslow = 20 # 多头入场长均线周期参数
lxfast = 3 # 多头出场短周期均线参数
lxslow = 10 # 多头出场长均线周期参数
sefast = 5 # 空头入场短均线周期参数
seslow = 20 # 空头入场长均线周期参数
sxfast = 3 # 空头出场短均线周期参数
sxslow = 10 # 空头出场长均线周期参数

accounts = {
‘futures_account’: AccountConfig(account_type=’futures’, capital_base=1000000)
}

def initialize(context): # 初始化虚拟期货账户,一般用于设置计数器,回测辅助变量等。
global data_pool
data_pool = DataCenter(refresh_rate, seslow)
context.current_bar = 0
context.symbol = ‘RB1605’

def handle_data(context): # 回测调仓逻辑,每个调仓周期运行一次,可在此函数内实现信号生产,生成调仓指令。
futures_account = context.get_account(‘futures_account’)
symbol = context.symbol
long_position = futures_account.get_positions().get(symbol, dict()).get(‘long_amount’, 0)
if context.get_symbol(universe[0]) != symbol:
if long_position != 0:
print ‘主力更换, 平仓’
print context.get_symbol(universe[0])
futures_account.order(symbol, -long_position, ‘close’)
context.symbol = context.get_symbol(universe[0])
else:
data = data_pool.update_data(symbol)

    high_price = np.array(data['highPrice'], dtype=float)
    low_price = np.array(data['lowPrice'], dtype=float)
    open_price = np.array(data['openPrice'], dtype=float)
    close_price = np.array(data['closePrice'], dtype=float)


    malefast = ta.MA(close_price, lefast)
    maleslow = ta.MA(close_price, leslow)
    malxfast = ta.MA(close_price, lxfast)
    malxslow = ta.MA(close_price, lxslow)
    masefast = ta.MA(close_price, sefast)
    maseslow = ta.MA(close_price, seslow)
    masxfast = ta.MA(close_price, sxfast)
    masxslow = ta.MA(close_price, sxslow)


    if long_position == 0 and context.current_bar >= 100:
        if malefast[-1] > maleslow[-1] and malxfast[-1] > malxslow[-1] and high_price[-1] > high_price[-2]:# 当2组均线均成空头排列时且当前价低于上根BAR最低价入场
            ids = futures_account.order(symbol, 10, 'open')
            futures_account.get_order(ids)
    if long_position != 0:
        if malxfast[-1] < malxslow[-1]: # 小周期空头均线组合成多头排列
            futures_account.order(symbol, -long_position, 'close')
        elif masefast[-1] < maseslow[-1] and masxfast[-1] < masxslow[-1] and low[-1] < low[-2]: # 两组多头均线分别多头排列且低于上根BAR最高价出场
            futures_account.order(symbol, -long_position, 'close')   
    context.current_bar += 1
    # if isinstance(ids, quartz.trade.order.FuturesOrder):
    #     print futures_account.get_order(ids)
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值