利用短期均线 MAS 和长期均线 MAL 生成开平仓信号:
MAS 上穿 MAL,形成做多信号,买入开仓;
MAS 上穿 MAL,形成做空信号,卖出开仓;
止盈 [基于 Bar 线的止盈]:浮动盈利 / 保证金 > 5%, 计算 | 浮动盈利×保证金比例 / 保证金;
止损 [基于 Bar 线的止损]:浮动亏损 / 保证金 < 3%, 计算 | 浮动亏损×保证金比例 / 保证金。
************************************
双均线突破策略
************************************
import re
import talib
import pandas as pd
import numpy as np
import quartz_futures as qf
from quartz_futures.api import *
参数初始化
universe = [‘RB1610’] # 策略证券池
start = pd.datetime(2016, 6, 1) # 回测开始时间
end = pd.datetime(2016, 9, 1) # 回测结束时间
capital_base = 1e4 # 初试可用资金
refresh_rate = 1 # 调仓周期
freq = ‘d’ # 调仓频率:s -> 秒;m-> 分钟;d-> 日;
自动生成保证金比例: margin_rate
margin_ratio = DataAPI.FutuGet(ticker = universe, field = [‘ticker’,’tradeMarginRatio’], pandas = ‘1’)
margin_rate = dict(zip(margin_ratio.ticker.tolist(), [0.01*index for index in margin_ratio.tradeMarginRatio.tolist()]))
策略初始化函数,一般用于设置计数器,回测辅助变量等。
def initialize(futures_account):
pass
回测调仓逻辑,每个调仓周期运行一次,可在此函数内实现信号生产,生成调仓指令。
def handle_data(futures_account):
symbol, amount = universe[0], 1
history_data = get_symbol_history(symbol = symbol, time_range = 20)[symbol]
## 计算 MA_S 和 MS_L
MA_S = talib.MA(history_data['closePrice'].apply(float).values, timeperiod = 5)
MA_L = talib.MA(history_data['closePrice'].apply(float).values, timeperiod = 10)
current_long = futures_account.position.get(symbol, dict()).get('long_position', 0)
current_short = futures_account.position.get(symbol, dict()).get('short_position', 0)
if MA_S[-1] > MA_L[-1] and MA_S[-2] < MA_L[-2]:
if current_short > 0:
print futures_account.current_date, futures_account.current_time, '买入平仓'
order(symbol, current_short, 'close')
if current_long < amount:
print futures_account.current_date, futures_account.current_time, '买入开仓'
order(symbol, amount, 'open')
if MA_S[-1] < MA_L[-1] and MA_S[-2] > MA_L[-2]:
if current_long > 0:
print futures_account.current_date, futures_account.current_time,'卖出平仓'
order(symbol, -current_long, 'close')
if current_short < amount:
print futures_account.current_date, futures_account.current_time, '卖出开仓'
order(symbol, -amount, 'open')
profit = futures_account.position.get(symbol, dict()).get('profit', 0)
margin = futures_account.position.get(symbol, dict()).get('long_margin', 0) - futures_account.position.get(symbol, dict()).get('short_margin', 0)
if margin and profit/margin < -0.03:
if current_long > 0:
order(symbol, -current_long, 'close')
if current_short > 0:
order(symbol, current_short, 'close')
print futures_account.current_date, futures_account.current_time, '止损'
if margin and profit/margin > 0.05:
if current_long > 0:
order(symbol, -current_long, 'close')
if current_short > 0:
order(symbol, current_short, 'close')
print futures_account.current_date, futures_account.current_time, '止盈'