機器學習篇章,本章不過時腳本小子,機器學習最核心的是機器,是模型。
學習,無非就是找些有的沒的因子扔進去,但說實話,機器學習,太過容易過擬合,容易無效化。回測好看的一筆,實盤垃圾的不行。
獲取訓練數據:
#獲取訓練數據#用20160101到20170101一年間的數據生成訓練集df = ContextInfo.get_market_data(['open','high','low','close','volume'],stock_code=[ContextInfo.stock],start_time='20160101',end_time='20200101',dividend_type='front')df = df.sort_index()days = df.index.valuesdays_close = df['close'].values
?獲取訓練因子:
#計算訓練因子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'].valuesclose = data['close'].valuesmax = data['high'].valuesmin = data['low'].valuesvolume = data['volume'].valuesclose_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 = 1else:label = 0y_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()
運用模型,判斷漲跌信號:
#運用模型,判斷漲跌信號try:prediction = ContextInfo.clf.predict(features)[0] # 機器學習判斷漲跌if prediction == 1:ContextInfo.holding = int(ContextInfo.money*0.95/(open_today))/100order_shares(ContextInfo.stock,ContextInfo.holding*100,'fix',open_today,ContextInfo,ContextInfo.accountid)ContextInfo.buyprice = open_todaybuy_condition = Trueprint(today)print('open long position to 0.95')except :print(('predict error occur,bar:', d))
?策略代碼:
#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.marketContextInfo.set_universe([ContextInfo.stock])ContextInfo.holding = 0ContextInfo.days = 0ContextInfo.money = ContextInfo.capitalContextInfo.accountid = "testS"def handlebar(ContextInfo):buy_condition = Falsesell_condition = Falsed = ContextInfo.barposif 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.valuesdays_close = df['close'].valuesprint('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'].valuesclose = data['close'].valuesmax = data['high'].valuesmin = data['low'].valuesvolume = data['volume'].valuesclose_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 = 1else:label = 0y_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 weekdayif 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'].valuesmax = data['high'].valuesmin = data['low'].valuesvolume = data['volume'].valuesclose_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))/100order_shares(ContextInfo.stock,ContextInfo.holding*100,'fix',open_today,ContextInfo,ContextInfo.accountid)ContextInfo.buyprice = open_todaybuy_condition = Trueprint(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 = 0sell_condition = Trueprint(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 = 0sell_condition = Trueprint(today)print('reach lose stop limit, close position')ContextInfo.days += 1ContextInfo.paint('do_buy', int(buy_condition), -1, 0)ContextInfo.paint('do_sell', int(sell_condition), -1, 0)