Skip to content

改进随机 Python Internet 学习笔记

原文: https://www.backtrader.com/blog/posts/2018-04-22-improving-code/improving-code/

互联网上不时会出现带有backtrader代码的样本。在我看来,中国人有几个特点。最新消息如下:

标题为:反向交易者-学习笔记 2,这显然(感谢谷歌)翻译为反向交易者——研究笔记 2。如果这些都是学习笔记,那么让我们试着在那里改进代码,在我个人看来,backtrader最为出色。

在研究笔记中的__init__策略方法中,我们发现以下几点

def __init__(self):
    ...
    self.ma1 = bt.indicators.SMA(self.datas[0],
                                   period=self.p.period
                                  )
    self.ma2 = bt.indicators.SMA(self.datas[1],
                                   period=self.p.period
                                  ) 

这里没什么好争论的(风格是非常私人的,我不会碰它)

在策略的next方法中,以下是买卖的逻辑决策。

...
# Not yet ... we MIGHT BUY if ...
if (self.ma1[0]-self.ma1[-1])/self.ma1[-1]>(self.ma2[0]-self.ma2[-1])/self.ma2[-1]:
... 

...
# Already in the market ... we might sell
if (self.ma1[0]-self.ma1[-1])/self.ma1[-1]<=(self.ma2[0]-self.ma2[-1])/self.ma2[-1]:
... 

这两个逻辑块实际上可以做得更好,这也将增加可读性、可维护性和调整(如果需要的话)

我们不需要在移动平均线(当前点0和上一点-1)的比较之后再加上一些分割,而是看看如何为我们预先计算。

让我们调整一下__init__

def __init__(self):
    ...

    # Let's create the moving averages as before
    ma1 = bt.ind.SMA(self.data0, period=self.p.period)
    ma2 = bt.ind.SMA(self.data1, period=self.p.period)

    # Use line delay notation (-x) to get a ref to the -1 point
    ma1_pct = ma1 / ma1(-1) - 1.0  # The ma1 percentage part
    ma2_pct = ma2 / ma2(-1) - 1.0  # The ma2 percentage part

    self.buy_sig = ma1_pct > ma2_pct  # buy signal
    self.sell_sig = ma1_pct <= ma2_pct  # sell signal 

现在我们可以将其转换为next方法,并执行以下操作:

def next(self):
    ...
    # Not yet ... we MIGHT BUY if ...
    if self.buy_sig:
    ...

    ...
    # Already in the market ... we might sell
    if self.sell_sig:
    ... 

请注意,我们甚至不必使用self.buy_sig[0],因为使用if self.buy_sig的布尔测试 make 已经被反向交易者机器转换为[0]的检查

Imho 是一种更简洁的方法,它使用标准算术和逻辑运算(并使用行延迟符号(-x))定义__init__中的逻辑,从而使代码变得更好。

在任何情况下,对于结束语,也可以尝试使用内置的PercentChange指示器(又名PctChange

参见:反向交易者文档-指标参考

顾名思义,它已经计算出了给定时间段内钢筋的百分比变化。__init__中的代码现在看起来像这样

def __init__(self):
    ...

    # Let's create the moving averages as before
    ma1 = bt.ind.SMA(self.data0, period=self.p.period)
    ma2 = bt.ind.SMA(self.data1, period=self.p.period)

    ma1_pct = bt.ind.PctChange(ma1, period=1)  # The ma1 percentage part
    ma2_pct = bt.ind.PctChange(ma2, period=1)  # The ma2 percentage part

    self.buy_sig = ma1_pct > ma2_pct  # buy signal
    self.sell_sig = ma1_pct <= ma2_pct  # sell signal 

在这种情况下,这没有多大区别,但如果计算更大、更复杂,它肯定会帮你省去很多麻烦。

快乐反向交易


我们一直在努力

apachecn/AiLearning

【布客】中文翻译组