Skip to content

扩展数据源

原文: https://www.backtrader.com/blog/posts/2015-08-07-extending-a-datafeed/extending-a-datafeed/

GitHub 中的问题实际上推动了文档部分的完成,或者帮助我了解 backtrader 是否具有我从一开始就设想的易用性和灵活性,以及一路上所做的决策。

在本例中为问题

问题最终似乎归结为:

  • 最终用户能否轻松地扩展现有机制,以线的形式添加额外信息,这些线沿着其他现有价格信息点传递,如openhigh等?

据我所知,这个问题的答案是:

海报似乎有以下要求(自第 6 期起):

  • 正在解析为 CSV 格式的数据源

  • 使用GenericCSVData加载信息

    此通用 csv 支持是针对问题而开发的

  • 一个额外的字段,显然包含 P/E 信息,需要沿着解析的 CSV 数据传递

让我们以 CSV 数据源开发和通用 CSV 数据源示例帖子为基础。

步骤:

  • 假设 P/E 信息是在解析的 CSV 数据中设置的

  • 使用GenericCSVData作为基类

  • 使用pe扩展现有行(开/高/低/关/卷/开利息)

  • 添加一个参数,让调用者确定 P/E 信息的列位置

结果是:

from backtrader.feeds import GenericCSVData

class GenericCSV_PE(GenericCSVData):

    # Add a 'pe' line to the inherited ones from the base class
    lines = ('pe',)

    # openinterest in GenericCSVData has index 7 ... add 1
    # add the parameter to the parameters inherited from the base class
    params = (('pe', 8),) 

工作完成了…

稍后以及在策略中使用此数据馈送时:

import backtrader as bt

....

class MyStrategy(bt.Strategy):

    ...

    def next(self):

        if self.data.close > 2000 and self.data.pe < 12:
            # TORA TORA TORA --- Get off this market
            self.sell(stake=1000000, price=0.01, exectype=Order.Limit)
    ... 

绘制额外的 P/E 线

显然,数据提要中的额外行没有自动绘图支持。

最好的选择是在这条线上做一个简单的平均,然后在一个单独的轴上绘制:

import backtrader as bt
import backtrader.indicators as btind

....

class MyStrategy(bt.Strategy):

    def __init__(self):

        # The indicator autoregisters and will plot even if no obvious
        # reference is kept to it in the class
        btind.SMA(self.data.pe, period=1, subplot=False)

    ...

    def next(self):

        if self.data.close > 2000 and self.data.pe < 12:
            # TORA TORA TORA --- Get off this market
            self.sell(stake=1000000, price=0.01, exectype=Order.Limit)
    ... 

我们一直在努力

apachecn/AiLearning

【布客】中文翻译组