Backtrader知識(shí)儲(chǔ)備
框架的概念還挺多:Cerebro,Data Feeds捧搞,Strategy,Indicators,Orders实牡,Broker陌僵,Analyzers轴合,Observers创坞,Sizers。逐個(gè)來(lái)看看大概的功能和角色受葛。對(duì)學(xué)習(xí)框架好處多多题涨。
- Cerebro :翻譯過(guò)來(lái)是大腦的意思∽芴玻可以說(shuō)是backtrader的基石纲堵,有點(diǎn)類似cpu的感覺(jué),處理收集所有數(shù)據(jù)闰渔、運(yùn)行策略席函,執(zhí)行回溯測(cè)試,操作交易冈涧,繪圖等等茂附。
- Data Feeds:交易數(shù)據(jù),這個(gè)沒(méi)什么好說(shuō)的督弓,都是各種金融平臺(tái)的交易數(shù)據(jù)营曼,開(kāi)盤價(jià),收盤價(jià)啥的愚隧。
- Strategy:策略蒂阱,根據(jù)定義的策略會(huì)處理或者說(shuō)遍歷數(shù)據(jù),來(lái)判定具體的買賣等動(dòng)作狂塘。
- Indicators:指標(biāo)录煤,用股市打比方,比如相對(duì)強(qiáng)弱指標(biāo)(RSI)荞胡、隨機(jī)指標(biāo)(KD)辐赞、趨向指標(biāo)(DMI)、平滑異同平均線(MACD)硝训、能量潮(OBV)等等這些都已經(jīng)實(shí)現(xiàn)好的响委,不用咱們自己實(shí)現(xiàn),拿來(lái)使用即可窖梁。當(dāng)然也支持自定義指標(biāo)赘风。
- Orders:下單員,可以理解具體交易訂單執(zhí)行單元纵刘,觸發(fā)了對(duì)應(yīng)的策略邀窃,發(fā)出訂單信號(hào),具體交給orders處理訂單操作。
- Broker:經(jīng)紀(jì)人瞬捕,可以理解為交易所鞍历,收取手續(xù)費(fèi),管理賬戶資金肪虎。
- Analyzers:看樣子輔助分析執(zhí)行的流程劣砍,協(xié)助改進(jìn)和修正問(wèn)題的角色(暫且這么理解)
- Observers:看樣子輔助分析執(zhí)行的流程,協(xié)助改進(jìn)和修正問(wèn)題的角色(暫且這么理解)
- Sizers:這個(gè)比較好理解扇救,不同的交易所刑枝,交易的單位不一樣,比如迅腔,1手是100股装畅,交易都是以100為單位。通過(guò)這個(gè)來(lái)設(shè)置交易的基本單位沧烈。
看了下官方給出的:Quickstart Guide掠兄。由于官網(wǎng)舉得例子都是國(guó)外的數(shù)據(jù)。要是想掌握這個(gè)必須把源頭先搞定锌雀,就是提供交易數(shù)據(jù)(Data Feeds )蚂夕,還好官方支持按照規(guī)范自己實(shí)現(xiàn)自己的數(shù)據(jù)。所以還是從這里開(kāi)始研究汤锨。
第一彈:Data Feeds(交易數(shù)據(jù))
背景
因?yàn)閿?shù)據(jù)的獲取双抽,我使用的是tushare。tushare返回的是pandas的dataframe格式闲礼。所以我就主攻pandas-datafeed這塊牍汹。
原理
參考官方文檔pandas-datafeed:
class PandasData(feed.DataBase):
'''
The ``dataname`` parameter inherited from ``feed.DataBase`` is the pandas
DataFrame
'''
params = (
# Possible values for datetime (must always be present)
# None : datetime is the "index" in the Pandas Dataframe
# -1 : autodetect position or case-wise equal name
# >= 0 : numeric index to the colum in the pandas dataframe
# string : column name (as index) in the pandas dataframe
('datetime', None),
# Possible values below:
# None : column not present
# -1 : autodetect position or case-wise equal name
# >= 0 : numeric index to the colum in the pandas dataframe
# string : column name (as index) in the pandas dataframe
('open', -1),
('high', -1),
('low', -1),
('close', -1),
('volume', -1),
('openinterest', -1),
)
PandasData類繼承feed.DataBase類,初始化數(shù)據(jù)需要7列數(shù)據(jù) 分別為:datetime柬泽、open慎菲、high、low锨并、close露该、volume、openinterest第煮,其中datetime是索引列解幼。經(jīng)過(guò)實(shí)踐送過(guò)去的數(shù)據(jù)按照這個(gè)順序排列,不包含header部分即可包警。
實(shí)踐(Data Feeds 使用pandas數(shù)據(jù))
使用的是601668 中國(guó)建筑的股票數(shù)據(jù)撵摆,csv文件我放到github上了『蓿可以自行去下載特铝,按照官方文檔的源碼改了下數(shù)據(jù)元,正常執(zhí)行。
# -*- coding: utf-8 -*-
"""
搞定自定義的數(shù)據(jù)送給backtrader
"""
#############################################################
#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
#############################################################
#############################################################
#global values
#############################################################
#############################################################
#global function
#############################################################
def G_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)
print(dataframe)
print('--------------------------------------------------')
print('-----------------------change time------------------------')
dataframe.trade_date = pd.to_datetime(dataframe.trade_date, format="%Y%m%d")
print(dataframe)
print('--------------------------------------------------')
print('-----------------------add openinterest-------------------')
dataframe['openinterest'] = '0'
print(dataframe)
print('--------------------------------------------------')
print('-----------------------make feedsdf-----------------------')
feedsdf = dataframe[['trade_date', 'open', 'high', 'low', 'close', 'vol', 'openinterest']]
print(feedsdf)
print('--------------------------------------------------')
print('-----------------------change columns---------------------')
feedsdf.columns =['datetime', 'open', 'high', 'low', 'close', 'volume', 'openinterest']
print(feedsdf)
print('--------------------------------------------------')
print('-----------------------change index-----------------------')
feedsdf.set_index(keys='datetime', inplace =True)
print(feedsdf)
print('--------------------------------------------------')
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
cerebro = bt.Cerebro(stdstats=False)
# Add a strategy
cerebro.addstrategy(bt.Strategy)
# Get a pandas dataframe
feedsdf = G_get_dataframe()
# Pass it to the backtrader datafeed and add it to the cerebro
data = bt.feeds.PandasData(dataname=feedsdf)
print(data)
cerebro.adddata(data)
# Run over everything
cerebro.run()
# Plot the result
cerebro.plot(style='bar')