簡介
給策略增加指標(biāo)后,需要給你指標(biāo)設(shè)置參數(shù),比如SMA設(shè)置幾天合適呢,每個股票的周期又都不一樣??偛荒芤粋€一個的自己嘗試。Backtrader提供了一個參數(shù)優(yōu)化的方法,可以按照給出的范圍來運行,大家可以根據(jù)結(jié)果尋找最優(yōu)的均線天數(shù)。具體可以參看Backtrader官方文檔quickstart
目標(biāo):
- 通過給策略一個范圍值,根據(jù)運行結(jié)果,找出某適合一只股票的盤整周期。
原理
通過optstrategy方法,給策略設(shè)置范圍值,讓策略逐個執(zhí)行,對比結(jié)果。
實踐
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 29 12:18:17 2020
@author: horace pei
"""
#############################################################
#import
#############################################################
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import os,sys
import pandas as pd
import backtrader as bt
#############################################################
#global const values
#############################################################
#############################################################
#static function
#############################################################
#############################################################
#class
#############################################################
# Create a Stratey
class TestStrategy(bt.Strategy):
# 自定義均線的實踐間隔,默認是5天
params = (
('maperiod', 5),
('printlog', False),
)
def log(self, txt, dt=None, doprint=False):
''' Logging function for this strategy'''
if self.params.printlog or doprint:
dt = dt or self.datas[0].datetime.date(0)
print('%s, %s' % (dt.isoformat(), txt))
def __init__(self):
# Keep a reference to the "close" line in the data[0] dataseries
self.dataclose = self.datas[0].close
# To keep track of pending orders
self.order = None
# buy price
self.buyprice = None
# buy commission
self.buycomm = None
# 增加均線,簡單移動平均線(SMA)又稱“算術(shù)移動平均線”,是指對特定期間的收盤價進行簡單平均化
self.sma = bt.indicators.SimpleMovingAverage(
self.datas[0], period=self.params.maperiod)
#訂單狀態(tài)改變回調(diào)方法 be notified through notify_order(order) of any status change in an order
def notify_order(self, order):
if order.status in [order.Submitted, order.Accepted]:
# Buy/Sell order submitted/accepted to/by broker - Nothing to do
return
# Check if an order has been completed
# Attention: broker could reject order if not enough cash
if order.status in [order.Completed]:
if order.isbuy():
self.log(
'BUY EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %
(order.executed.price,
order.executed.value,
order.executed.comm))
self.buyprice = order.executed.price
self.buycomm = order.executed.comm
elif order.issell():
self.log('SELL EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %
(order.executed.price,
order.executed.value,
order.executed.comm))
self.bar_executed = len(self)
elif order.status in [order.Canceled, order.Margin, order.Rejected]:
self.log('Order Canceled/Margin/Rejected')
# Write down: no pending order
self.order = None
#交易狀態(tài)改變回調(diào)方法 be notified through notify_trade(trade) of any opening/updating/closing trade
def notify_trade(self, trade):
if not trade.isclosed:
return
# 每筆交易收益 毛利和凈利
self.log('OPERATION PROFIT, GROSS %.2f, NET %.2f' %
(trade.pnl, trade.pnlcomm))
def next(self):
# Simply log the closing price of the series from the reference
self.log('Close, %.2f' % self.dataclose[0])
# Check if an order is pending ... if yes, we cannot send a 2nd one
if self.order:
return
# Check if we are in the market(當(dāng)前賬戶持股情況,size,price等等)
if not self.position:
# Not yet ... we MIGHT BUY if ...
if self.dataclose[0] >= self.sma[0]:
#當(dāng)收盤價,大于等于均線的價格
# BUY, BUY, BUY!!! (with all possible default parameters)
self.log('BUY CREATE, %.2f' % self.dataclose[0])
# Keep track of the created order to avoid a 2nd order
self.order = self.buy()
else:
# Already in the market ... we might sell
if self.dataclose[0] < self.sma[0]:
#當(dāng)收盤價,小于均線價格
# SELL, SELL, SELL!!! (with all possible default parameters)
self.log('SELL CREATE, %.2f' % self.dataclose[0])
# Keep track of the created order to avoid a 2nd order
self.order = self.sell()
def stop(self):
self.log('(MA Period %2d) Ending Value %.2f' %
(self.params.maperiod, self.broker.getvalue()), doprint=True)
#############################################################
#global values
#############################################################
#############################################################
#global function
#############################################################
def get_dataframe():
# Get a pandas dataframe
datapath = './data/stockinfo.csv'
tmpdatapath = './data/stockinfo_tmp.csv'
print('-----------------------read csv---------------------------')
dataframe = pd.read_csv(datapath,
skiprows=0,
header=0,
parse_dates=True,
index_col=0)
dataframe.trade_date = pd.to_datetime(dataframe.trade_date, format="%Y%m%d")
dataframe['openinterest'] = '0'
feedsdf = dataframe[['trade_date', 'open', 'high', 'low', 'close', 'vol', 'openinterest']]
feedsdf.columns =['datetime', 'open', 'high', 'low', 'close', 'volume', 'openinterest']
feedsdf.set_index(keys='datetime', inplace =True)
feedsdf.iloc[::-1].to_csv(tmpdatapath)
feedsdf = pd.read_csv(tmpdatapath, skiprows=0, header=0, parse_dates=True, index_col=0)
if os.path.isfile(tmpdatapath):
os.remove(tmpdatapath)
print(tmpdatapath+" removed!")
return feedsdf
########################################################################
#main
########################################################################
if __name__ == '__main__':
# Create a cerebro entity(創(chuàng)建cerebro)
cerebro = bt.Cerebro()
# Add a strategy(加入自定義策略,可以設(shè)置自定義參數(shù),方便調(diào)節(jié))
cerebro.optstrategy(TestStrategy, maperiod=range(3,15))
# Get a pandas dataframe(獲取dataframe格式股票數(shù)據(jù))
feedsdf = get_dataframe()
# Pass it to the backtrader datafeed and add it to the cerebro(加入數(shù)據(jù))
data = bt.feeds.PandasData(dataname=feedsdf)
cerebro.adddata(data)
# Add a FixedSize sizer according to the stake(國內(nèi)1手是100股,最小的交易單位)
cerebro.addsizer(bt.sizers.FixedSize, stake=100)
# Set our desired cash start(給經(jīng)紀(jì)人,可以理解為交易所股票賬戶充錢)
cerebro.broker.setcash(10000.0)
# Set the commission - 0.1%(設(shè)置交易手續(xù)費,雙向收取)
cerebro.broker.setcommission(commission=0.001)
# Print out the starting conditions(輸出賬戶金額)
print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())
# Run over everything(執(zhí)行回測)
cerebro.run()
# Print out the final result(輸出賬戶金額)
print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())
分析和說明
通過: cerebro.optstrategy(TestStrategy, maperiod=range(3,15)),來設(shè)定3到15天的均線,看看均線時間那個收益最好。

image.png
通過看最后的收益,5天的均線應(yīng)收15.46。用5天的均線做判定是最合適的。
源碼
全代碼請到github上clone了。github地址:[qtbt](https://github.com/horacepei/qtbt.git)