Backtrader 文档学习-Platform Concepts

2023-12-14 04:20

本文主要是介绍Backtrader 文档学习-Platform Concepts,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Backtrader 文档学习-Platform Concepts

1.开始之前

导入backtrader ,以及backtrader 的指示器、数据反馈的模块 。

import backtrader as bt
import backtrader.indicators as btind
import backtrader.feeds as btfeeds

看看btind模块下有什么方法和属性:

obj_str = ''
for i in dir(btind):if i[:1] != '_' :obj_str += i + ','    
print(obj_str)

指示器中的指标函数很多,方法属性如下:

ADX,ADXR,AO,APO,ATR,AbsPriceOsc,AbsolutePriceOscillator,AccDeOsc,AccelerationDecelerationOscillator,Accum,AdaptiveMovingAverage,AdaptiveMovingAverageEnvelope,AdaptiveMovingAverageOsc,AdaptiveMovingAverageOscillator,All,AllN,And,Any,AnyN,ApplyN,ArithmeticMean,AroonDown,AroonIndicator,AroonOsc,AroonOscillator,AroonUp,AroonUpDown,AroonUpDownOsc,AroonUpDownOscillator,Average,AverageDirectionalMovementIndex,AverageDirectionalMovementIndexRating,AverageTrueRange,AverageWeighted,AwesomeOsc,AwesomeOscillator,BBands,BaseApplyN,BollingerBands,BollingerBandsPct,CCI,Cmp,CmpEx,CointN,CommodityChannelIndex,CrossDown,CrossOver,CrossUp,CumSum,CumulativeSum,DEMA,DEMAEnvelope,DEMAOsc,DEMAOscillator,DI,DM,DMA,DMAEnvelope,DMAOsc,DMAOscillator,DMI,DPO,DV2,DemarkPivotPoint,DetrendedPriceOscillator,DicksonMA,DicksonMAEnvelope,DicksonMAOsc,DicksonMAOscillator,DicksonMovingAverage,DicksonMovingAverageEnvelope,DicksonMovingAverageOsc,DicksonMovingAverageOscillator,DirectionalIndicator,DirectionalMovement,DirectionalMovementIndex,DivByZero,DivZeroByZero,DoubleExponentialMovingAverage,DoubleExponentialMovingAverageEnvelope,DoubleExponentialMovingAverageOsc,DoubleExponentialMovingAverageOscillator,DownDay,DownDayBool,DownMove,EC,ECEnvelope,ECOsc,ECOscillator,EMA,EMAEnvelope,EMAOsc,EMAOscillator,Envelope,EnvelopeMixIn,ErrorCorrecting,ErrorCorrectingEnvelope,ErrorCorrectingOsc,ErrorCorrectingOscillator,ExpSmoothing,ExpSmoothingDynamic,ExponentialMovingAverage,ExponentialMovingAverageEnvelope,ExponentialMovingAverageOsc,ExponentialMovingAverageOscillator,ExponentialSmoothing,ExponentialSmoothingDynamic,FibonacciPivotPoint,FindFirstIndex,FindFirstIndexHighest,FindFirstIndexLowest,FindLastIndex,FindLastIndexHighest,FindLastIndexLowest,HMA,HMAEnvelope,HMAOsc,HMAOscillator,HeikinAshi,Highest,HullMA,HullMAEnvelope,HullMAOsc,HullMAOscillator,HullMovingAverage,HullMovingAverageEnvelope,HullMovingAverageOsc,HullMovingAverageOscillator,Hurst,HurstExponent,Ichimoku,If,Indicator,KAMA,KAMAEnvelope,KAMAOsc,KAMAOscillator,KST,KnowSureThing,LAGF,LRSI,LaguerreFilter,LaguerreRSI,LineActions,List,Logic,Lowest,MACD,MACDHisto,MACDHistogram,MAXINT,Max,MaxN,Mean,MeanDev,MeanDeviation,MetaMovAvBase,Min,MinN,MinusDI,MinusDirectionalIndicator,ModifiedMovingAverage,ModifiedMovingAverageEnvelope,ModifiedMovingAverageOsc,ModifiedMovingAverageOscillator,Momentum,MomentumOsc,MomentumOscillator,MovAv,MovingAverage,MovingAverageAdaptive,MovingAverageAdaptiveEnvelope,MovingAverageAdaptiveOsc,MovingAverageAdaptiveOscillator,MovingAverageBase,MovingAverageDoubleExponential,MovingAverageDoubleExponentialEnvelope,MovingAverageDoubleExponentialOsc,MovingAverageDoubleExponentialOscillator,MovingAverageExponential,MovingAverageExponentialEnvelope,MovingAverageExponentialOsc,MovingAverageExponentialOscillator,MovingAverageSimple,MovingAverageSimpleEnvelope,MovingAverageSimpleOsc,MovingAverageSimpleOscillator,MovingAverageSmoothed,MovingAverageSmoothedEnvelope,MovingAverageSmoothedOsc,MovingAverageSmoothedOscillator,MovingAverageTripleExponential,MovingAverageTripleExponentialEnvelope,MovingAverageTripleExponentialOsc,MovingAverageTripleExponentialOscillator,MovingAverageWeighted,MovingAverageWeightedEnvelope,MovingAverageWeightedOsc,MovingAverageWeightedOscillator,MovingAverageWilder,MovingAverageWilderEnvelope,MovingAverageWilderOsc,MovingAverageWilderOscillator,MultiLogic,MultiLogicReduce,NZD,NonZeroDifference,OLS_BetaN,OLS_Slope_InterceptN,OLS_TransformationN,OperationN,Or,Oscillator,OscillatorMixIn,PGO,PPO,PPOShort,PSAR,ParabolicSAR,PctChange,PctRank,PercPriceOsc,PercPriceOscShort,PercentChange,PercentRank,PercentagePriceOscillator,PercentagePriceOscillatorShort,PeriodN,PivotPoint,PlusDI,PlusDirectionalIndicator,PrettyGoodOsc,PrettyGoodOscillator,PriceOsc,PriceOscillator,RMI,ROC,ROC100,RSI,RSI_Cutler,RSI_EMA,RSI_SMA,RSI_SMMA,RSI_Safe,RSI_Wilder,RateOfChange,RateOfChange100,Reduce,ReduceN,RelativeMomentumIndex,RelativeStrengthIndex,SMA,SMAEnvelope,SMAOsc,SMAOscillator,SMMA,SMMAEnvelope,SMMAOsc,SMMAOscillator,SimpleMovingAverage,SimpleMovingAverageEnvelope,SimpleMovingAverageOsc,SimpleMovingAverageOscillator,SmoothedMovingAverage,SmoothedMovingAverageEnvelope,SmoothedMovingAverageOsc,SmoothedMovingAverageOscillator,StandardDeviation,StdDev,Stochastic,StochasticFast,StochasticFull,StochasticSlow,Sum,SumN,TEMA,TEMAEnvelope,TEMAOsc,TEMAOscillator,TR,TRIX,TSI,TripleExponentialMovingAverage,TripleExponentialMovingAverageEnvelope,TripleExponentialMovingAverageOsc,TripleExponentialMovingAverageOscillator,Trix,TrixSignal,TrueHigh,TrueLow,TrueRange,TrueStrengthIndicator,UltimateOscillator,UpDay,UpDayBool,UpMove,Vortex,WMA,WMAEnvelope,WMAOsc,WMAOscillator,WeightedAverage,WeightedMovingAverage,WeightedMovingAverageEnvelope,WeightedMovingAverageOsc,WeightedMovingAverageOscillator,WilderMA,WilderMAEnvelope,WilderMAOsc,WilderMAOscillator,WilliamsAD,WilliamsR,ZLEMA,ZLEMAEnvelope,ZLEMAOsc,ZLEMAOscillator,ZLInd,ZLIndEnvelope,ZLIndOsc,ZLIndOscillator,ZLIndicator,ZLIndicatorEnvelope,ZLIndicatorOsc,ZLIndicatorOscillator,ZeroLagEma,ZeroLagEmaEnvelope,ZeroLagEmaOsc,ZeroLagEmaOscillator,ZeroLagExponentialMovingAverage,ZeroLagExponentialMovingAverageEnvelope,ZeroLagExponentialMovingAverageOsc,ZeroLagExponentialMovingAverageOscillator,ZeroLagIndicator,ZeroLagIndicatorEnvelope,ZeroLagIndicatorOsc,ZeroLagIndicatorOscillator,absolute_import,accdecoscillator,alias,aroon,atr,awesomeoscillator,basicops,bollinger,bt,cci,cmp,contrib,crossover,dema,deviation,directionalmove,division,dma,dpo,dv2,ema,envelope,functools,haD,haDelta,hadelta,heikinashi,hma,hurst,ichimoku,kama,kst,linename,lrsi,mabase,macd,map,math,module,momentum,movav,movname,newaliases,newcls,newclsdct,newclsdoc,newclsname,ols,operator,oscillator,percentchange,percentrank,pivotpoint,prettygoodoscillator,priceoscillator,print_function,psar,range,rmi,rsi,sma,smma,stochastic,suffix,sys,trix,tsi,ultimateoscillator,unicode_literals,williams,with_metaclass,wma,zlema,zlind,

也可以直接通过bt导入下面的模块feeds indicators

import backtrader as bt
thefeed = bt.feeds.OneOfTheFeeds(...)
theind = bt.indicators.SimpleMovingAverage(...)

2.数据读入-无处不在

所有的策略都基于数据,平台端用户不用考虑如何接收数据。

Data Feeds are automagically provided member variables to the strategy in the form of an array and shortcuts to the array positions

数据源是以数组的形式或者对数组位置快捷访问的方式提供给strategy(策略)作为成员变量使用的。
这句话需要好好理解。

数组的形式: self.datas[0].close
数组位置快捷访问:self.data0.close

class MyStrategy(bt.Strategy):params = dict(period=20)def __init__(self):sma = btind.SimpleMovingAverage(self.datas[0], period=self.params.period)print(sma)# Keep a reference to the "close" line in the data[0] dataseriesself.dataclose = self.datas[0].closeself.dataclosetest = self.data0.closeprint('-'* 20,'close','-' * 20 )print(self.dataclose[0])print(self.dataclosetest[0])        

执行结果
sma 的数据类型backtrader.indicators.sma.SimpleMovingAverage

<backtrader.indicators.sma.SimpleMovingAverage object at 0x7f616bd7c820>
-------------------- close --------------------
133.01
133.01

Data Feeds get added to the platform and they will show up inside the strategy in the sequential order in which they were added to the system.

SQL语句按日期排序,不论是正序还是逆序desc ,到BackTrader中,都是按时间倒序排列,[0]是最后的日期。

3.快捷访问数据

self.datas数组项可以通过自动成员变量直接访问:

self.data targets self.datas[0]
self.dataX targets self.datas[X]

下面好好测试一下BackTrader的数据访问,数据之间的关系。

#<class 'backtrader.linebuffer.LineBuffer'>
print(type(cerebro.datas[0].close))#<class 'backtrader.feeds.pandafeed.PandasData'>
print(type(cerebro.datas[0]))#<class 'list'>
print(type(cerebro.datas))# ('close', 'low', 'high', 'open', 'volume', 'openinterest', 'datetime')
print(cerebro.datas[0].getlinealiases())

结果如下:

<class 'backtrader.linebuffer.LineBuffer'>
<class 'backtrader.feeds.pandafeed.PandasData'>
<class 'list'>
('close', 'low', 'high', 'open', 'volume', 'openinterest', 'datetime')

在这里插入图片描述

说明:

  • 1、cerebro.datas数据集的类型是 <class ‘list’> ,对应载入cerebro的股票数据,可以是多个股票,就是股票的集合。
  • 2、cerebro.datas[0]是<class ‘backtrader.feeds.pandafeed.PandasData’>,其实与dataframe类似,包括以下列:(‘close’, ‘low’, ‘high’, ‘open’, ‘volume’, ‘openinterest’, ‘datetime’)的集合。
    -3、cerebro.datas[0].close就是dataframe的一列数据,BackTrader称之为Line <class ‘backtrader.linebuffer.LineBuffer’> 。
  • 4、cerebro.datas[0].close[0] 就是访问到数据的元素,实际数据值。
  • 5、cerebro.datas[0]都是按时间顺序逆序的,第一个元素index是0 ,下一个是-1 ,以此类推。
  • 6、时间序列必须用内置方法处理
print(cerebro.datas[0].datetime[0]) 
print(pd.to_datetime(cerebro.datas[0].datetime[0],unit='s'))
print(bt.num2date(cerebro.datas[0].datetime[0]))

结果如下:

737424.0
1970-01-09 12:50:24
2019-12-31 00:00:00

直接访问datetime列 ,是浮点数。
开始用pd.to_datetime 函数,转换的时间是1970年,迷惑很长时间。

重要:必须用自带的函数转换时间 bt.num2date()!!!

4.默认数据载入

class MyStrategy(bt.Strategy):params = dict(period=20)def __init__(self):sma = btind.SimpleMovingAverage(period=self.params.period)...

self.data has been completely removed from the invocation of SimpleMovingAverage. If this is done, the indicator (in this case the SimpleMovingAverage) receives the first data of the object in which is being created (the Strategy), which is self.data (aka self.data0 or self.datas[0])

默认使用的self是什么?
如果只有一个数据源,cerebro只载入一个股票数据,不用显式指定,系统会缺省使用self.datas[0],self.data=self.data0=self.datas[0] ,也就是第一个加入的数据源 。所以说self.data 就没有显式出现在调用SMA指示器 。
如果有多个载入数据,还是注明好,清晰可读。

5. 一切都是数据载入

class MyStrategy(bt.Strategy):#定义策略全局参数params = dict(period1=20, period2=25, period3=10, period4)def __init__(self):# 使用SMA指示器载入datas[0],使用参数1sma1 = btind.SimpleMovingAverage(self.datas[0], period=self.p.period1)# This 2nd Moving Average operates using sma1 as "data"# 使用第一个SMA指示器数据再次作为SMA的数据载入,使用参数2sma2 = btind.SimpleMovingAverage(sma1, period=self.p.period2)# New data created via arithmetic operation# 随意的计算  something = sma2 - sma1 + self.data.close# This 3rd Moving Average operates using something  as "data"# 随意计算的结果作为第三次SMA数据载入,使用参数3sma3 = btind.SimpleMovingAverage(something, period=self.p.period3)# Comparison operators work too ...# 比较后取大值 ,有点疑问 ?greater = sma3 > sma1# Pointless Moving Average of True/False values but valid# This 4th Moving Average operates using greater  as "data"# 比较后结果第四次载入SMA指示器,使用参数4sma3 = btind.SimpleMovingAverage(greater, period=self.p.period4)...

总而言之,所有的数据转换变化后,都可以作为数据载入,再次进行运算。

6. 参数

在backtrader中,所有的类都按照如下方法来使用参数:

1、声明一个带有缺省值的参数作为类的一个属性(元组或者字典结构)。
2、关键字类型参数(kwargs)会扫描匹配的参数,将值赋值给对应的参数,完成后从kwargs删除。
3、这些参数都可以在类实例中通过访问成员变量self.params(可以简写为self.p)来使用。
使用元组 tuple

class MyStrategy(bt.Strategy):params = (('period', 20),)def __init__(self):sma = btind.SimpleMovingAverage(self.data, period=self.p.period)

使用字典dict

class MyStrategy(bt.Strategy):params = dict(period=20)def __init__(self):sma = btind.SimpleMovingAverage(self.data, period=self.p.period)

7.Lines 关键的概念

从使用用户(通常是strategy)的角度来说,就是包括一个或多个line,这些line是一系列的数据,在图中可以形成一条线(line)。line是数组,不是pd.series ,没有index 。

class MyStrategy(bt.Strategy):params = dict(period=20)def __init__(self):self.movav = btind.SimpleMovingAverage(self.data, period=self.p.period)def next(self):if self.movav.lines.sma[0] > self.data.lines.close[0]:print(round(self.movav.lines.sma[0],2),self.data.lines.close[0],'Simple Moving Average is greater than the closing price')

执行结果:

83.34 74.4 Simple Moving Average is greater than the closing price
83.16 75.1 Simple Moving Average is greater than the closing price
83.01 76.6 Simple Moving Average is greater than the closing price
82.92 80.1 Simple Moving Average is greater than the closing price
82.82 79.64 Simple Moving Average is greater than the closing price
82.69 78.52 Simple Moving Average is greater than the closing price
82.36 76.1 Simple Moving Average is greater than the closing price
81.87 74.28 Simple Moving Average is greater than the closing price
... ... 

self.movav:这个是一个SimpleMovingAverage的指标(indicator),本身就包含一个具有lines属性的sma。这里特殊注意一下,计算SimpleMovingAverage使用的self.data,没有指定具体Line的话,缺省用的是close价进行计算。

简单的方法访问lines:

xxx.lines 可以简化为 xxx.l
xxx.lines.name可以简化为xxx.lines_name

一些复杂的对象也可以通过如下方法访问:

self.data_name 等于 self.data.lines.name

如果有多个变量的话,也可以self.data1_name 替代self.data1.lines.name

此外,Line的名字也可以通过如下方式访问:

self.data.close and self.movav.sma

class MyStrategy(bt.Strategy):params = dict(period=20)def __init__(self):self.movav = btind.SimpleMovingAverage(self.data, period=self.p.period)def next(self):# 数据集0 收盘价在110和120if (self.datas[0].close[0] > 110.0) & (self.datas[0].close[0] < 120.0):print(bt.num2date(self.datas[0].datetime[0]),'self.datas[0].close[0] > 110.0')# 数据集1 收盘价在110和120    if self.datas[1].close[0] > 9.0:print(bt.num2date(self.datas[1].datetime[0]),'self.datas[1].close[0] > 9.0')# 数据集SMA 收盘价在88和90if (self.movav.lines.sma[0] > 88) & (self.movav.sma[0] < 90) :print(round(self.movav.lines.sma[0],2),'self.movav.lines.sma[0] > 88')print(self.movav.getlinealiases())#print(cerebro.datas[0].getlinealiases())

结果如下:

2018-04-18 00:00:00 self.datas[1].close[0] > 9.0
2018-04-24 00:00:00 self.datas[1].close[0] > 9.0
2018-04-25 00:00:00 self.datas[1].close[0] > 9.0
2018-04-26 00:00:00 self.datas[1].close[0] > 9.0
2019-04-09 00:00:00 self.datas[0].close[0] > 110.0
88.78 self.movav.lines.sma[0] > 88
('sma',)
89.64 self.movav.lines.sma[0] > 88
('sma',)
2019-06-20 00:00:00 self.datas[0].close[0] > 110.0
2019-06-21 00:00:00 self.datas[0].close[0] > 110.0
2019-06-24 00:00:00 self.datas[0].close[0] > 110.0
2019-06-25 00:00:00 self.datas[0].close[0] > 110.0
2019-06-26 00:00:00 self.datas[0].close[0] > 110.0
2019-06-27 00:00:00 self.datas[0].close[0] > 110.0
2019-06-28 00:00:00 self.datas[0].close[0] > 110.0
2019-07-24 00:00:00 self.datas[0].close[0] > 110.0
2019-08-01 00:00:00 self.datas[0].close[0] > 110.0
2019-08-02 00:00:00 self.datas[0].close[0] > 110.0
2019-08-05 00:00:00 self.datas[0].close[0] > 110.0
2019-08-07 00:00:00 self.datas[0].close[0] > 110.0
2019-08-09 00:00:00 self.datas[0].close[0] > 110.0

需要好好说明一下:

  • 简写示例

if (self.movav.lines.sma[0] > 88) & (self.movav.sma[0] < 90) :

  • 多数据源

两种方式引用
self.movav.lines.sma[0] = self.movav.sma[0]

cerebro载入两个股票数据。
特别注意:调用datas ,有s
self.datas[0].close[0]
self.datas[0].close[0]
self.datas[0].close[0]

  • SMA指示器调用后,是数组,没有日期字段!!!
    开始也想增加打印日期,

print(bt.num2date(self.movav.datetime[0]) 无日期

只有一列

print(self.movav.getlinealiases())
('sma',)

未完待续!!!

这篇关于Backtrader 文档学习-Platform Concepts的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/491136

相关文章

重新对Java的类加载器的学习方式

《重新对Java的类加载器的学习方式》:本文主要介绍重新对Java的类加载器的学习方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1、介绍1.1、简介1.2、符号引用和直接引用1、符号引用2、直接引用3、符号转直接的过程2、加载流程3、类加载的分类3.1、显示

浅谈Redis Key 命名规范文档

《浅谈RedisKey命名规范文档》本文介绍了Redis键名命名规范,包括命名格式、具体规范、数据类型扩展命名、时间敏感型键名、规范总结以及实际应用示例,感兴趣的可以了解一下... 目录1. 命名格式格式模板:示例:2. 具体规范2.1 小写命名2.2 使用冒号分隔层级2.3 标识符命名3. 数据类型扩展命

Java学习手册之Filter和Listener使用方法

《Java学习手册之Filter和Listener使用方法》:本文主要介绍Java学习手册之Filter和Listener使用方法的相关资料,Filter是一种拦截器,可以在请求到达Servl... 目录一、Filter(过滤器)1. Filter 的工作原理2. Filter 的配置与使用二、Listen

使用Python从PPT文档中提取图片和图片信息(如坐标、宽度和高度等)

《使用Python从PPT文档中提取图片和图片信息(如坐标、宽度和高度等)》PPT是一种高效的信息展示工具,广泛应用于教育、商务和设计等多个领域,PPT文档中常常包含丰富的图片内容,这些图片不仅提升了... 目录一、引言二、环境与工具三、python 提取PPT背景图片3.1 提取幻灯片背景图片3.2 提取

Android实现在线预览office文档的示例详解

《Android实现在线预览office文档的示例详解》在移动端展示在线Office文档(如Word、Excel、PPT)是一项常见需求,这篇文章为大家重点介绍了两种方案的实现方法,希望对大家有一定的... 目录一、项目概述二、相关技术知识三、实现思路3.1 方案一:WebView + Office Onl

Python实现word文档内容智能提取以及合成

《Python实现word文档内容智能提取以及合成》这篇文章主要为大家详细介绍了如何使用Python实现从10个左右的docx文档中抽取内容,再调整语言风格后生成新的文档,感兴趣的小伙伴可以了解一下... 目录核心思路技术路径实现步骤阶段一:准备工作阶段二:内容提取 (python 脚本)阶段三:语言风格调

使用Java将DOCX文档解析为Markdown文档的代码实现

《使用Java将DOCX文档解析为Markdown文档的代码实现》在现代文档处理中,Markdown(MD)因其简洁的语法和良好的可读性,逐渐成为开发者、技术写作者和内容创作者的首选格式,然而,许多文... 目录引言1. 工具和库介绍2. 安装依赖库3. 使用Apache POI解析DOCX文档4. 将解析

如何解决idea的Module:‘:app‘platform‘android-32‘not found.问题

《如何解决idea的Module:‘:app‘platform‘android-32‘notfound.问题》:本文主要介绍如何解决idea的Module:‘:app‘platform‘andr... 目录idea的Module:‘:app‘pwww.chinasem.cnlatform‘android-32

Java利用docx4j+Freemarker生成word文档

《Java利用docx4j+Freemarker生成word文档》这篇文章主要为大家详细介绍了Java如何利用docx4j+Freemarker生成word文档,文中的示例代码讲解详细,感兴趣的小伙伴... 目录技术方案maven依赖创建模板文件实现代码技术方案Java 1.8 + docx4j + Fr

使用C#代码在PDF文档中添加、删除和替换图片

《使用C#代码在PDF文档中添加、删除和替换图片》在当今数字化文档处理场景中,动态操作PDF文档中的图像已成为企业级应用开发的核心需求之一,本文将介绍如何在.NET平台使用C#代码在PDF文档中添加、... 目录引言用C#添加图片到PDF文档用C#删除PDF文档中的图片用C#替换PDF文档中的图片引言在当