python - 使用Python回测多只股票

标签 python trading

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

假设我想将以下 6 只股票放入该策略中,对每只股票进行一次 tun,得到多个结果。我该如何编写该循环?

股票 = [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)

最佳答案

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()

关于python - 使用Python回测多只股票,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23186816/

相关文章:

Python 警告 : Truncated incorrect DOUBLE value

python - 将文本文件数据传递给变量

trading - mql4:从站点获取数据

python - 如何将 OHLCV 数据重新采样为 5 分钟?

pine-script - 松树脚本: how to add and display text on a horizontal line/hline?

python - pickle 类定义

python - 从 XML 中删除 ns0

python - Scipy 优化曲线拟合无法正常工作

javascript - 使用 javascript 将参数发送到 java 应用程序

python - spyder中的RSI使用excel中的数据