Backtrader中文笔记之Pandas DataFeed Example
Pandas DataFeed Example
Note
pandas
and its dependencies have to be installed
pandas
与它的依赖需要被安装
Supporting Pandas Dataframes seems to be of concern to lots of people, who rely on the already available parsing code for different data sources (including CSV) and other functionalities offered by Pandas.
支持Pandas数据模型似乎是很多人关心的问题,他们依赖于已经可用的针对不同数据源(包括CSV)的解析代码和Pandas提供的其他功能。
The important declarations for the Datafeed.
Datafeed的重要声明。
Note
These are ONLY declarations. Don't copy this code blindly. See the actual usage in the example below
这些只是声明。不要盲目地复制这个代码。请参见下面的示例中的实际用法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | 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 ), ) |
The above excerpt from the PandasData
class shows the keys:
上面的摘自PandasData类的代码显示了键:
-
The
dataname
parameter to the class during instantiation holds the Pandas Dataframe -
在实例化期间,类的dataname参数保存了panda Dataframe
This parameter is inherited from the base class
feed.DataBase
- 这个参数是从基类feed.DataBase继承的
-
The new parameters have the names of the regular fields in the
DataSeries
and follow these conventions -
新参数具有数据集中的常规字段的名称,并遵循这些约定
-
datetime
(default: None) -
None : datetime is the “index” in the Pandas Dataframe
- None : datetime is the “index” 在Pandas Dataframe里面
-
-1 : autodetect position or case-wise equal name
- -1:自动检测位置或大小写相等的名称
-
= 0 : numeric index to the colum in the pandas dataframe
- =0:数字索引来至pandas dataframe的列
-
string : column name (as index) in the pandas dataframe
- string :pandas数据帧中的列名(作为索引)
-
open
,high
,low
,high
,close
,volume
,openinterest
(default: -1 for all of them) -
None : column not present
- None :列不存在
-
-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
-
A small sample should be able to load the standar 2006 sample, having been parsed by Pandas
, rather than directly by backtrader
一个小样本应该能够加载standar2006样本,已经由Pandas解析,而不是直接由backtrader进行分析
Running the sample to use the exiting “headers” in the CSV data:
运行示例以使用CSV数据中现有的“标题”:
1 2 3 4 5 6 7 | $ . / panda - test.py - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Open High Low Close Volume OpenInterest Date 2006 - 01 - 02 3578.73 3605.95 3578.73 3604.33 0 0 2006 - 01 - 03 3604.08 3638.42 3601.84 3614.34 0 0 2006 - 01 - 04 3615.23 3652.46 3615.23 3652.46 0 0 |
The same but telling the script to skip the headers:
相同,但告诉脚本跳过标题:
1 2 3 4 5 6 7 | $ . / panda - test.py - - noheaders - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 1 2 3 4 5 6 0 2006 - 01 - 02 3578.73 3605.95 3578.73 3604.33 0 0 2006 - 01 - 03 3604.08 3638.42 3601.84 3614.34 0 0 2006 - 01 - 04 3615.23 3652.46 3615.23 3652.46 0 0 |
The 2nd run is using tells pandas.read_csv
:
第二次运行告诉pandas.read_csv
-
To skip the first input row (
skiprows
keyword argument set to 1) - 要跳过第一个输入行(skiprows关键字参数设置为1)
-
Not to look for a headers row (
header
keyword argument set to None) - 不查找标题行(标题关键字参数设置为None)
The backtrader
support for Pandas tries to automatically detect if column names have been used or else numeric indices and acts accordingly, trying to offer a best match.
The following chart is the tribute to success. The Pandas Dataframe has been correctly loaded (in both cases)
下表是对成功的案例。Pandas数据框架已正确加载(在两种情况下)
The sample code for the test.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 | from __future__ import (absolute_import, division, print_function, unicode_literals) import argparse import backtrader as bt import backtrader.feeds as btfeeds import pandas def runstrat(): args = parse_args() # Create a cerebro entity cerebro = bt.Cerebro(stdstats = False ) # Add a strategy cerebro.addstrategy(bt.Strategy) # Get a pandas dataframe datapath = ( '../../datas/2006-day-001.txt' ) # Simulate the header row isn't there if noheaders requested skiprows = 1 if args.noheaders else 0 header = None if args.noheaders else 0 dataframe = pandas.read_csv(datapath, skiprows = skiprows, header = header, parse_dates = True , index_col = 0 ) if not args.noprint: print ( '--------------------------------------------------' ) print (dataframe) print ( '--------------------------------------------------' ) # Pass it to the backtrader datafeed and add it to the cerebro data = bt.feeds.PandasData(dataname = dataframe) cerebro.adddata(data) # Run over everything cerebro.run() # Plot the result cerebro.plot(style = 'bar' ) def parse_args(): parser = argparse.ArgumentParser( description = 'Pandas test script' ) parser.add_argument( '--noheaders' , action = 'store_true' , default = False , required = False , help = 'Do not use header rows' ) parser.add_argument( '--noprint' , action = 'store_true' , default = False , help = 'Print the dataframe' ) return parser.parse_args() if __name__ = = '__main__' : runstrat() |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· Ollama——大语言模型本地部署的极速利器
· 使用C#创建一个MCP客户端
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现