量化平台量化策略如何编写?
发布时间:2023-12-1 14:02阅读:436
量化平台量化策略如何编写?
哈喽,大家好,刚接触量化平台的小伙伴们知道自己的策略思路,不知道如何下手编写,今天招财猫就给大家来看下简单的几个策略的编写,大家也好下手如何去写策略了!
比如说网格交易(期货交易)示例
#coding:gbk
#在期货的1min线下运行
'''
回测模型示例(非实盘交易策略)
本策略首先计算了过去300个价格数据的均值和标准差
并根据均值加减标准差得到网格的区间分界线,
并分别配以0.3和0.5的仓位权重
然后根据价格所在的区间来配置仓位(+/-40为上下界,无实际意义):
(-40,-3],(-3,-2],(-2,2],(2,3],(3,40](具体价格等于均值+数字倍标准差)
[0.25, 0.15, 0.0, 0.15, 0.25](资金比例)
'''
import numpy as np
import pandas as pd
import time
import datetime
def init(ContextInfo):
#设置图为标的
ContextInfo.tradefuture = ContextInfo.stockcode+"."+ContextInfo.market
ContextInfo.set_universe([ContextInfo.tradefuture])
print(ContextInfo.get_universe())
ContextInfo.timeseries = pd.DataFrame()
ContextInfo.band = np.zeros(5)
#print 'ContextInfo.band',ContextInfo.band
# 设置网格的仓位
ContextInfo.weight = [0.25, 0.15, 0.0, 0.15, 0.25]
# 获取多仓仓位
ContextInfo.position_long = 0
# 获取孔仓仓位
ContextInfo.position_short = 0
#剩余资金
ContextInfo.surpluscapital = ContextInfo.capital
#保证金比率
comdict = ContextInfo.get_commission()
ContextInfo.marginratio = comdict['margin_ratio']
#合约乘数
ContextInfo.multiplier = ContextInfo.get_contract_multiplier(ContextInfo.tradefuture)
#账号
ContextInfo.accountid='testF'
ContextInfo.now_timestamp = time.time()
def handlebar(ContextInfo):
index = ContextInfo.barpos
realtimetag = ContextInfo.get_bar_timetag(index)
lasttimetag = ContextInfo.get_bar_timetag(index - 1)
print(timetag_to_datetime(realtimetag, '%Y-%m-%d %H:%M:%S'))
if ContextInfo.period in ['1m','3m','5m','15m','30m'] and not ContextInfo.do_back_test:
if (datetime.datetime.fromtimestamp(ContextInfo.now_timestamp) - datetime.datetime.fromtimestamp(realtimetag / 1000)).days > 7:
return
starttime = timetag_to_datetime(realtimetag-86400000 * 10, '%Y%m%d%H%M%S')
endtime = timetag_to_datetime(realtimetag-86400000, '%Y%m%d%H%M%S')
#print 'starttime,endtime',starttime,endtime
Result=ContextInfo.get_market_data(['close'],stock_code=[ContextInfo.tradefuture],start_time=starttime,end_time=endtime,skip_paused=False,period=ContextInfo.period,dividend_type='front')
close_sort = Result['close'].sort_index(axis = 0,ascending = True)
#print close_sort,starttime,endtime
#过去300个价格数据的均值和标准差
Result_mean = close_sort.tail(300).mean()
Result_std = close_sort.tail(300).std()
ContextInfo.band = Result_mean + np.array([-40, -3, -2, 2, 3, 40]) * Result_std
#print 'ContextInfo.band',ContextInfo.band
if np.isnan(ContextInfo.band).any() or Result_std==0:
return
if index > 0:
lasttimetag = ContextInfo.get_bar_timetag(index - 1)
#前一根bar收盘价
close_lastbar = ContextInfo.get_market_data (['close'],stock_code=[ContextInfo.tradefuture],period=ContextInfo.period,dividend_type='front')
#当前开盘价
open_currentbar = ContextInfo.get_market_data (['open'],stock_code=[ContextInfo.tradefuture],period=ContextInfo.period,dividend_type='front')
#划分网格
#print close_lastbar,ContextInfo.band
grid = pd.cut([close_lastbar], ContextInfo.band, labels=[0, 1, 2, 3, 4])[0]
#print 'grid ',grid
if not ContextInfo.do_back_test:
ContextInfo.paint('grid',float(grid),-1,0)
# 若无仓位且价格突破则按照设置好的区间开仓
if ContextInfo.position_long == 0 and ContextInfo.position_short == 0 and grid != 2:
# 大于3为在中间网格的上方,做多
if grid >= 3 and ContextInfo.surpluscapital > 0 :
long_num = int(ContextInfo.weight[grid]*ContextInfo.surpluscapital/(ContextInfo.marginratio*close_lastbar*ContextInfo.multiplier))
ContextInfo.position_long = long_num
buy_open(ContextInfo.tradefuture,long_num,'fix',close_lastbar,ContextInfo,ContextInfo.accountid)
ContextInfo.surpluscapital -= long_num * ContextInfo.marginratio * close_lastbar * ContextInfo.multiplier
#print '开多'
elif grid <= 1 and ContextInfo.surpluscapital > 0 :
short_num = int(ContextInfo.weight[grid]*ContextInfo.surpluscapital/(ContextInfo.marginratio*close_lastbar*ContextInfo.multiplier))
ContextInfo.position_short = short_num
sell_open(ContextInfo.tradefuture,short_num,'fix',close_lastbar,ContextInfo,ContextInfo.accountid)
ContextInfo.surpluscapital -= short_num * ContextInfo.marginratio * close_lastbar * ContextInfo.multiplier
#print '开空'
# 持有多仓的处理
elif ContextInfo.position_long > 0 :
if grid >= 3 and ContextInfo.surpluscapital > 0 :
targetlong_num = int(ContextInfo.weight[grid] * (ContextInfo.surpluscapital + ContextInfo.multiplier * close_lastbar * ContextInfo.position_long*ContextInfo.marginratio)/ (ContextInfo.marginratio*close_lastbar * ContextInfo.multiplier))
if targetlong_num > ContextInfo.position_long :
trade_num = targetlong_num - ContextInfo.position_long
ContextInfo.position_long = targetlong_num
buy_open(ContextInfo.tradefuture,trade_num,'fix',close_lastbar,ContextInfo,ContextInfo.accountid)
ContextInfo.surpluscapital -= trade_num * close_lastbar * ContextInfo.marginratio * ContextInfo.multiplier
elif targetlong_num < ContextInfo.position_long:
trade_num = ContextInfo.position_long - targetlong_num
ContextInfo.position_long = targetlong_num
sell_close_tdayfirst(ContextInfo.tradefuture,trade_num,'fix',close_lastbar,ContextInfo,ContextInfo.accountid)
ContextInfo.surpluscapital += trade_num * close_lastbar * ContextInfo.marginratio * ContextInfo.multiplier
#print '调多仓到仓位'
# 等于2为在中间网格,平仓
elif grid == 2:
sell_close_tdayfirst(ContextInfo.tradefuture,ContextInfo.position_long,'fix',close_lastbar,ContextInfo,ContextInfo.accountid)
ContextInfo.surpluscapital += ContextInfo.position_long * close_lastbar * ContextInfo.marginratio * ContextInfo.multiplier
ContextInfo.position_long = 0
#print '平多'
# 小于1为在中间网格的下方,做空
elif grid <= 1:
sell_close_tdayfirst(ContextInfo.tradefuture,ContextInfo.position_long,'fix',close_lastbar,ContextInfo,ContextInfo.accountid)
ContextInfo.surpluscapital += ContextInfo.position_long * close_lastbar * ContextInfo.marginratio * ContextInfo.multiplier
ContextInfo.position_long = 0
#print '全平多仓'
if ContextInfo.surpluscapital > 0 :
short_num = int(ContextInfo.weight[grid]*ContextInfo.surpluscapital/(ContextInfo.multiplier * ContextInfo.marginratio * close_lastbar))
ContextInfo.position_short = short_num
sell_open(ContextInfo.tradefuture,short_num,'fix',close_lastbar,ContextInfo,ContextInfo.accountid)
ContextInfo.surpluscapital -= short_num * close_lastbar * ContextInfo.marginratio * ContextInfo.multiplier
#print '开空仓到仓位'
# 持有空仓的处理
elif ContextInfo.position_short> 0 :
# 小于1为在中间网格的下方,做空
if grid <= 1:
targetlshort_num = int(ContextInfo.weight[grid]*(ContextInfo.surpluscapital + ContextInfo.multiplier*close_lastbar*ContextInfo.position_short*ContextInfo.marginratio)/(ContextInfo.multiplier * ContextInfo.marginratio * close_lastbar))
if targetlshort_num > ContextInfo.position_short:
trade_num = targetlshort_num - ContextInfo.position_short
ContextInfo.position_short = targetlshort_num
sell_open(ContextInfo.tradefuture,trade_num,'fix',close_lastbar,ContextInfo,ContextInfo.accountid)
ContextInfo.surpluscapital -= trade_num * close_lastbar * ContextInfo.marginratio * ContextInfo.multiplier
#print '开空仓到仓位' ,targetlshort_num
elif targetlshort_num < ContextInfo.position_short:
trade_num = ContextInfo.position_short - targetlshort_num
ContextInfo.position_short = targetlshort_num
buy_close_tdayfirst(ContextInfo.tradefuture,trade_num,'fix',close_lastbar,ContextInfo,ContextInfo.accountid)
ContextInfo.surpluscapital += trade_num * close_lastbar * ContextInfo.marginratio * ContextInfo.multiplier
#print '平空仓到仓位' ,targetlshort_num
# 等于2为在中间网格,平仓
elif grid == 2:
buy_close_tdayfirst(ContextInfo.tradefuture,ContextInfo.position_short,'fix',close_lastbar,ContextInfo,ContextInfo.accountid)
ContextInfo.surpluscapital += ContextInfo.position_short * close_lastbar * ContextInfo.marginratio * ContextInfo.multiplier
ContextInfo.position_short = 0
#print '全平空仓'
# 大于3为在中间网格的上方,做多
elif grid >= 3:
buy_close_tdayfirst(ContextInfo.tradefuture,ContextInfo.position_short,'fix',close_lastbar,ContextInfo,ContextInfo.accountid)
ContextInfo.surpluscapital += ContextInfo.position_short * close_lastbar * ContextInfo.marginratio * ContextInfo.multiplier
ContextInfo.position_short = 0
#print '全平空仓'
if ContextInfo.surpluscapital > 0 :
trade_num = int(ContextInfo.weight[grid]*ContextInfo.surpluscapital / (ContextInfo.marginratio * close_lastbar * ContextInfo.multiplier))
ContextInfo.position_long = trade_num
buy_open(ContextInfo.tradefuture,trade_num,'fix',close_lastbar,ContextInfo,ContextInfo.accountid)
ContextInfo.surpluscapital -= trade_num * close_lastbar * ContextInfo.marginratio * ContextInfo.multiplier
#print ' 开多仓到仓位'
# 获取多仓仓位
#print 'ContextInfo.position_long',ContextInfo.position_long
# 获取空仓仓位
#print 'ContextInfo.position_short',ContextInfo.position_short
# 获取剩余资金
#print 'ContextInfo.surpluscapital',ContextInfo.surpluscapital
机器学习回测示例
#coding:gbk
#!/usr/bin/python
"""
回测模型示例(非实盘交易策略)
#单股机器学习模型,在主图下直接运行即可
#模型中以过去15个交易日数据生成特征变量以预测5个交易日后的涨跌,
#特征变量我们选取了平均收盘价,平均成交量,平均最高价,平均最低价,总收益,收盘价的标准差
#训练结束后,回测过程中在每个星期一预测本周五的涨跌,以此为据开仓
"""
import pandas as pd
import numpy as np
import time
from datetime import *
from sklearn import svm
import traceback
def init(ContextInfo):
ContextInfo.stock = ContextInfo.stockcode + '.' + ContextInfo.market
ContextInfo.set_universe([ContextInfo.stock])
ContextInfo.holding = 0
ContextInfo.days = 0
ContextInfo.money = ContextInfo.capital
ContextInfo.accountid = "testS"
def handlebar(ContextInfo):
buy_condition = False
sell_condition = False
d = ContextInfo.barpos
if ContextInfo.days == 0:
#用20160101到20170101一年间的数据生成训练集
df = ContextInfo.get_market_data(['open','high','low','close','volume'],stock_code=[ContextInfo.stock],start_time='20160101',end_time='20170101',dividend_type='front')
df = df.sort_index()
days = df.index.values
days_close = df['close'].values
print('start training SVM')
x_all = []
y_all = []
for i in range(14, len(days) - 5):
start_day = days[i - 14]
end_day = days[i]
data = ContextInfo.get_market_data(['open','high','low','close','volume'],stock_code=[ContextInfo.stock],end_time=end_day,count=15,skip_paused=False,dividend_type='front')
data = data.sort_index()
open = data['open'].values
close = data['close'].values
max = data['high'].values
min = data['low'].values
volume = data['volume'].values
close_mean = close[-1] / np.mean(close)
volume_mean = volume[-1] / np.mean(volume)
max_mean = max[-1] / np.mean(max)
min_mean = min[-1] / np.mean(min)
vol = volume[-1]
return_now = close[-1] / close[0]
std = np.std(np.array(close), axis = 0)
#features用于存放因子
features = [close_mean, volume_mean, max_mean, min_mean, vol, return_now, std] #计算出的6个因子作为特征
x_all.append(features)
for i in range(len(days_close) - 19):
if days_close[i+19] > days_close[i+14]:
label = 1
else:
label = 0
y_all.append(label)
x_train = x_all[:-1]
y_train = y_all[:-1]
ContextInfo.clf = svm.SVC(C=1.0, kernel='rbf', degree=3, gamma='auto', coef0=0.0, shrinking=True, probability=False,tol=0.001, cache_size=200, verbose=False, max_iter=-1, decision_function_shape='ovr', random_state=None)
try:
ContextInfo.clf.fit(x_train, y_train)
except:
e = traceback.format_exc()
print(('value error, bar:', e))
print('training finish!')
timetag = ContextInfo.get_bar_timetag(d)
timetag_start = ContextInfo.get_bar_timetag(d-15)
timetag_end = ContextInfo.get_bar_timetag(d-1) #过去15个交易日的起止时间
today = timetag_to_datetime(timetag, '%Y%m%d')
start_date = timetag_to_datetime(timetag_start, '%Y%m%d')
end_date = timetag_to_datetime(timetag_end, '%Y%m%d')
weekday = datetime.strptime(today, '%Y%m%d').isoweekday()
open_today = ContextInfo.get_market_data(['open'],stock_code=[ContextInfo.stock],skip_paused=False,dividend_type='front')
close_today = ContextInfo.get_market_data(['close'],stock_code=[ContextInfo.stock],skip_paused=False,dividend_type='front')
#print ContextInfo.holding
#print weekday
if ContextInfo.holding == 0 and weekday == 1: #每个星期一判断是否开仓
data = ContextInfo.get_market_data(['open','high','low','close','volume'],stock_code=[ContextInfo.stock],end_time=end_date,count=15,skip_paused=False, dividend_type='front')
data = data.sort_index()
close = data['close'].values
max = data['high'].values
min = data['low'].values
volume = data['volume'].values
close_mean = close[-1] / np.mean(close)
volume_mean = volume[-1] / np.mean(volume)
max_mean = max[-1] / np.mean(max)
min_mean = min[-1] / np.mean(min)
vol = volume[-1]
return_now = close[-1] / close[0]
std = np.std(np.array(close), axis = 0)
features = [close_mean, volume_mean, max_mean, min_mean, vol, return_now, std]
features = np.array(features).reshape(1, -1)
try:
prediction = ContextInfo.clf.predict(features)[0]
if prediction == 1:
ContextInfo.holding = int(ContextInfo.money*0.95/(open_today))/100
order_shares(ContextInfo.stock,ContextInfo.holding*100,'fix',open_today,ContextInfo,ContextInfo.accountid)
ContextInfo.buyprice = open_today
buy_condition = True
print(today)
print('open long position to 0.95')
except :
print(('predict error occur,bar:', d))
elif ContextInfo.holding > 0 and close_today/ContextInfo.buyprice >= 1.1: #每个交易日判断止盈止损
order_shares(ContextInfo.stock,-ContextInfo.holding*100,'fix',close_today,ContextInfo,ContextInfo.accountid)
ContextInfo.holding = 0
sell_condition = True
print(today)
print('reach profit stop limit, close position')
elif ContextInfo.holding > 0 and close_today/ContextInfo.buyprice < 0.98 and weekday == 5:
order_shares(ContextInfo.stock,-ContextInfo.holding*100,'fix',close_today,ContextInfo,ContextInfo.accountid)
ContextInfo.holding = 0
sell_condition = True
print(today)
print('reach lose stop limit, close position')
ContextInfo.days += 1
ContextInfo.paint('do_buy', int(buy_condition), -1, 0)
ContextInfo.paint('do_sell', int(sell_condition), -1, 0)
需要开通证券账户支持的量化平台开通,然后在量化平台上写策略,实现自己策略交易。
想要量化平台的可以沟通,门槛较低!
温馨提示:投资有风险,选择需谨慎。