Python隐藏权力(1) – backtrader中文教程
Python中的隐藏的权力(1)
这只是满足真实用户的时候backtrader当一个人可以,如果实现在该平台中使用抽象和Python的力量使sense.
Without离开pythonic口号不谈,backtrader尝试给用户为最大程度地控制,而在同一时间通过简化使用投入动作hidden权力,Python的offers.
The在此一series.
Is的第一篇文章第一个例子它的阵列或者是什么
一个非常简单的例子:
import backtrader as bt class MyStrategy(bt.Strategy): def __init__(self): self.hi_lo_avg = (self.data.high + self.data.low) / 2.0 def next(self): if self.hi_lo_avg[0] > another_value: print("we have a winner!") ... ... cerebro.addstrategy(MyStrategy) cerebro.run()
一个是非常迅速弹出的问题是:
- 不能一个也使用
[]
在__init__
?被问.
The的问题,因为用户已经尝试和Python有停止与exception.
The答案运行:
- 没有。使用
[]
initialization.
With期间并不意味着接下来的问题是,那么:
- 那么在
self.hi_lo_avg
实际上是存储在__init__
如果它是不是数组?
答案是不能令人费解的程序员,但它可能是ALGO贸易商谁去为Python
- It是一个懒洋洋地评估对象,将计算和交付价值经由
[]
在cerebro.run
相位运算器,即:在next
的strategy.
Bottomline的方法:在next
方法数组索引操作符[]
将给出您访问的过去和当前时间moments.
The秘密的计算值是在sauce
Andoperator overriding是真正的酱油。让我们打破计算的high–low-average:
self.hi_lo_avg = (self.data.high + self.data.low) / 2.0
的组件:
他们在许多情况下,错误地采取纯arrays但事实并非如此。该原因是他们的对象:在
- 和
0
索引方案的-1
落实到位backtrader - 的缓冲器的大小的控制和链接到其他objects
And在这种情况下,最重要的方面:
- 重写操作员返回objects
这为什么下面的操作返回了lines对象。让我们开始:
temp = self.data.high - self.data.low
临时对象,然后通过2.0
分割,分配给成员变量:
self.hi_lo_avg = temp / 2.0
这agains返回另一个lines对象。由于运营商压倒一切不仅适用于直接之中lines对象执行的操作,而且,例如,像这样division.
Which算术运算意味着self.hi_lo_avg
具有到lines对象的引用。这个目的是在战略的next
的方法或作为输入到有用indicators或其他calculations.
Alogic operatorexample
The例如在上面使用一个算术运算符__init__
和后来的的[0]
和逻辑算子的,>
在next
.
因为运营商首要不限于arithmetic,让我们把另一个组合例如在适当位置,从而增加了混合物的指示器。第一次尝试是:
import backtrader as bt class MyStrategy(bt.Strategy): def __init__(self): self.hi_lo_avg = (self.data.high + self.data.low) / 2.0 self.sma = bt.indicators.SMA(period=30) def next(self): if self.hi_lo_avg[0] > self.sma[0]: print("we have a winner!") ... ... cerebro.addstrategy(MyStrategy) cerebro.run()
但是在这种情况下,仅仅是从another_value
改变self.sma[0]
。让我们来改进它:
import backtrader as bt class MyStrategy(bt.Strategy): def __init__(self): self.hi_lo_avg = (self.data.high + self.data.low) / 2.0 self.sma = bt.indicators.SMA(period=30) def next(self): if self.hi_lo_avg > self.sma: print("we have a winner!") ... ... cerebro.addstrategy(MyStrategy) cerebro.run()
一个好人。运营商压倒一切的不也是在工作next
和用户可以真正放下[0]
和直接比较objects.
If所有的人究竟是可能它实际上似乎是一个矫枉过正。但好消息是,有更多的。看到这个例子:
import backtrader as bt class MyStrategy(bt.Strategy): def __init__(self): hi_lo_avg = (self.data.high + self.data.low) / 2.0 sma = bt.indicators.SMA(period=30) self.signal = hi_lo_avg > sma def next(self): if self.signal: print("we have a winner!") ... ... cerebro.addstrategy(MyStrategy) cerebro.run()
我们已经做了两两件事:
- 创建lines对象命名
self.signal
哪个比较high–low-average对的值的Simple Moving Average作为该对象上面所解释的是在
next
,当它已经有用calculated - Remove
[0]
在next
检查时的使用,如果signal
是True
。这是可能的,因为运营商也已经重写了布尔operations
Conclusion
Hopefully这增加了一些光时,操作实际上发生了什么在执行__init__
怎么操作重写实际上happens.
评论被关闭。