使用Python对多个股票进行回测

1 投票
2 回答
4164 浏览
提问于 2025-04-18 03:31

我现在正在使用Pyalgotrade,这是一个流行的Python库,用来测试交易策略。我想写一个循环,可以一个接一个地测试几只股票。

假设我想把以下6只股票放入这个策略中,依次运行每只股票一次,并获取几个结果。我该如何写这个循环呢?

股票列表 = [AAPL, EBAY, NFLX, BBY, GOOG, WBAI]

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


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

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

    def onEnterCanceled(self, position):
        self.__position = None

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

    def onExitCanceled(self, position):
        # If the exit was canceled, re-submit it.
        self.__position.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.getAdjClose() > self.__sma[-1]:
                # Enter a buy market order for 10 shares. The order is good till canceled.
                self.__position = self.enterLong(self.__instrument, 10, True)
        # Check if we have to exit the position.
        elif bar.getAdjClose() < self.__sma[-1]:
            self.__position.exitMarket()



def run_strategy(smaPeriod):
    instruments = ["AAPL"]

        # Download the bars.
    feed = yahoofinance.build_feed(instruments, 2011, 2013, ".")

        # Evaluate the strategy with the feed's bars.
    myStrategy = MyStrategy(feed, "AAPL", smaPeriod)
    myStrategy.run()
    print "Final portfolio value: $%.2f" % myStrategy.getBroker().getEquity()

run_strategy(10)

2 个回答

0

我觉得 ScrenningTale 对于那些编程知识有限的人来说,会是一个更好、更简单的回测选择。

1

在编程中,有时候我们会遇到一些问题,像是代码运行不正常或者出现错误。这种情况下,我们可以去一些技术论坛,比如StackOverflow,寻求帮助。在这些论坛上,很多人会分享他们的经验和解决方案。

例如,有人可能会问:“我在运行我的代码时遇到了一个错误,应该怎么解决?”然后其他人就会根据他们的经验,给出一些建议,比如检查代码中的某些部分,或者尝试不同的方法来解决问题。

总之,技术论坛是一个很好的地方,可以让我们学习到很多实用的知识,帮助我们解决编程中遇到的各种问题。

def run_strategy(smaPeriod,inst):

        # Download the bars.
    feed = yahoofinance.build_feed([inst], 2011, 2013, ".")

        # Evaluate the strategy with the feed's bars.
    myStrategy = MyStrategy(feed, inst, smaPeriod)
    myStrategy.run()
    print "Final portfolio value: $%.2f" % myStrategy.getBroker().getEquity()
def main():
    instruments = ["AAPL","EBAY", "NFLX", "BBY"]
    for inst in instruments:
            run_strategy(10,inst)
if __name__ == '__main__':
        main()

撰写回答