在PyAlgoTrad中使用多个工具进行回溯测试

2024-06-16 17:41:43 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,我想用一个数组(“仪器”)将策略从1个推广到10个,以简化加载10个feed、创建10个sma的任务,然后每天检查一个(或多个)工具中是否发生信号交叉。在

我被困住了。另外,绘图仪是单独绘制图形,但我想把所有仪器的结果绘制在一个图形中。在

这是我的代码:

from pyalgotrade import strategy, plotter
from pyalgotrade.barfeed import yahoofeed
from pyalgotrade.technical import ma
from pyalgotrade.tools import yahoofinance

class MyStrategy(strategy.BacktestingStrategy):
    def __init__(self, feed, instruments, smaPeriod):
        strategy.BacktestingStrategy.__init__(self, feed, 1000)
        self.__position = None
        # We'll use adjusted close values instead of regular close values.
        self.setUseAdjustedValues(True)
        self.__sma = {}
        self.__instruments = instruments
        for instrument in instruments:
            self.__sma[instrument] = ma.SMA(feed[instrument].getPriceDataSeries(), smaPeriod)

    def onEnterOk(self, position):
        execInfo = position.getEntryOrder().getExecutionInfo()
        self.info("BUY at $%.2f" % (execInfo.getPrice()))

    def onEnterCanceled(self, position):
        execInfo = position.getEntryOrder().getExecutionInfo()

    def onExitOk(self, position):
        execInfo = position.getExitOrder().getExecutionInfo()
        self.info("SELL at $%.2f" % (execInfo.getPrice()))

    def onExitCanceled(self, position):
        # If the exit was canceled, re-submit it.
        self.__position[str(position.getEntryOrder().getInstrument())].exitMarket()

    def onBars(self, bars):
        # Wait for enough bars to be available to calculate a SMA.
        if self.__sma[-1] is None:
            return

        bar = bars[self.__instrument]
        # If a position was not opened, check if we should enter a long position.
        if self.__position is None:
            if bar.getPrice() > self.__sma[-1]:
            # Enter a buy market order for 25 shares. The order is good till canceled.
                self.__position = self.enterLong(self.__instrument, 25, True)
        # Check if we have to exit the position.
        elif bar.getPrice() < self.__sma[-1] and not self.__position.exitActive():
            self.__position.exitMarket()

def run_strategy(smaPeriod):

    # Load the yahoo feed from the CSV file
    instruments = [
        "AMZN",
        "ADBE",
        "C" ,
        "BA" ,
        "HOG" ,
        "MMM" ,
        "MS" ,
        "MSFT" ,
        "CVS" ,
        "AXP"
    ]
    #Download and Load yahoo feed from CSV files
    #Change year range 2000 to 2001 to your desired one
    feed = yahoofinance.build_feed(instruments, 2000,2001, ".")

    # Evaluate the strategy with the feed.
    myStrategy = MyStrategy(feed, instruments, smaPeriod)

    # Attach a plotter to the strategy
    plt = plotter.StrategyPlotter(myStrategy)


    # Run the strategy
    myStrategy.run()
    print "Final portfolio value: $%.2f" % myStrategy.getBroker().getEquity()

    # Plot the strategy.
    plt.plot()


run_strategy(10)

Tags: thetofromimportselfifdeffeed
1条回答
网友
1楼 · 发布于 2024-06-16 17:41:43

我刚刚开始处理pyalgotrade,但我认为您犯了一个相当简单的错误(正如gzc所指出的):类Bars的实例是来自不同仪器的条的集合,它们都具有相同的时间戳。因此,当调用onBars事件时,实际上必须遍历字典中的所有工具。在

相关问题 更多 >