Exemple #1
0
def run_strategy(isBenchmark, instruments, posMax, entrySma, exitSma,
                 rsiPeriod, overSoldThreshold):
    # Load the yahoo feed from the CSV file
    feed = yahoofeed.Feed()
    feed.sanitizeBars(True)
    for instrument, startYear in instruments.items():
        for year in range(startYear, assets.endYear):
            if os.path.isfile(assets.folder + instrument + "-" + str(year) +
                              ".csv"):
                feed.addBarsFromCSV(
                    instrument,
                    assets.folder + instrument + "-" + str(year) + ".csv")

    if isBenchmark:
        myStrategy = MyBenchmark(feed, instruments, posMax, exitSma)
    else:
        myStrategy = MyStrategy(feed, instruments, posMax, entrySma, exitSma,
                                rsiPeriod, overSoldThreshold)

    # Attach analyzers to the strategy.
    # Returns first in case others use it (DataSeries)
    returnsAnalyzer = returns.Returns()
    myStrategy.attachAnalyzer(returnsAnalyzer)
    returnsAnalyzer.getReturns().setMaxLen(1000000)

    sharpeAnalyzer = sharpe.SharpeRatio()
    myStrategy.attachAnalyzer(sharpeAnalyzer)

    drawDownAnalyzer = drawdown.DrawDown()
    myStrategy.attachAnalyzer(drawDownAnalyzer)

    tradesAnalyzer = trades.Trades()
    myStrategy.attachAnalyzer(tradesAnalyzer)

    volaAnalyzer = volatility.VolaAnalyzer(120)
    myStrategy.attachAnalyzer(volaAnalyzer)

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

    volaSeries = volaAnalyzer.getVolaSeries()
    plt.getOrCreateSubplot("Volatility").addDataSeries("Volatility",
                                                       volaSeries)

    capStart = myStrategy.getBroker().getEquity()
    myStrategy.info("CAPITAL INICIAL: $%.4f" % capStart)

    # Run the strategy
    myStrategy.run()

    # Show basic information
    allRet = returnsAnalyzer.getReturns()
    capEnd = myStrategy.getBroker().getEquity()

    myStrategy.info("CAPITAL FINAL: $%.4f" % capEnd)
    myStrategy.info(" ")
    myStrategy.info("Rentabilidad: %.4f%%" % (100 *
                                              (capEnd - capStart) / capStart))
    myStrategy.info("Rentabilidad Anualizada: %.4f%%" % (100 * (math.pow(
        (capEnd / capStart),
        (365.0 /
         ((myStrategy.endDateTime - myStrategy.startDateTime).days))) - 1)))
    myStrategy.info("Volatilidad Anualizada: %.4f%%" %
                    (100 * stats.stddev(allRet, 1) * math.sqrt(252)))
    myStrategy.info("Ratio de Sharpe Anualizado: %.4f" %
                    (100 * sharpeAnalyzer.getSharpeRatio(0.0036, True)))

    myStrategy.info("DrawDown Maximo: %.4f%%" %
                    (100 * drawDownAnalyzer.getMaxDrawDown()))
    myStrategy.info("DrawDown Mas Largo: %s dias" %
                    (drawDownAnalyzer.getLongestDrawDownDuration().days))
    myStrategy.info(" ")
    myStrategy.info("Rentabilidad Media: %.4f%%" % (100 * stats.mean(allRet)))
    posRet = []
    negRet = []
    allRet = returnsAnalyzer.getReturns()
    for ret in allRet:
        if ret > 0:
            posRet.append(ret)
        elif ret < 0:
            negRet.append(ret)
    myStrategy.info("Ganancia Media: %.4f%%" % (100 * stats.mean(posRet)))
    myStrategy.info("Perdida Media: %.4f%%" % (100 * stats.mean(negRet)))
    myStrategy.info(" ")
    myStrategy.info("Ganancia Media por Op: $%s" %
                    (stats.mean(tradesAnalyzer.getProfits())))
    myStrategy.info("Perdida Media por Op: $%s" %
                    (stats.mean(tradesAnalyzer.getLosses())))
    myStrategy.info("Comisiones Totales: $%s" %
                    (sum(tradesAnalyzer.getCommissionsForAllTrades())))
    myStrategy.info("Num Ops Igual: %s" % (tradesAnalyzer.getEvenCount()))
    myStrategy.info("Num Ops Gano: %s" % (tradesAnalyzer.getProfitableCount()))
    myStrategy.info("Num Ops Pierdo: %s" %
                    (tradesAnalyzer.getUnprofitableCount()))

    # Plot the strategy.
    plt.plot()
def run_strategy(index, startYear, endYear):

    # Load the yahoo feed from the CSV file
    feed = yahoofeed.Feed()
    feed.sanitizeBars(True)
    for year in range(startYear, endYear):
        feed.addBarsFromCSV(index,
                            "./data/" + index + "-" + str(year) + ".csv")

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

    # Attach analyzers to the strategy.
    # Returns first in case others use it (DataSeries)
    returnsAnalyzer = returns.Returns()
    myStrategy.attachAnalyzer(returnsAnalyzer)
    returnsAnalyzer.getReturns().setMaxLen(300000)

    sharpeAnalyzer = sharpe.SharpeRatio()
    myStrategy.attachAnalyzer(sharpeAnalyzer)

    drawDownAnalyzer = drawdown.DrawDown()
    myStrategy.attachAnalyzer(drawDownAnalyzer)

    tradesAnalyzer = trades.Trades()
    myStrategy.attachAnalyzer(tradesAnalyzer)

    volaAnalyzer = volatility.VolaAnalyzer(120)
    myStrategy.attachAnalyzer(volaAnalyzer)

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

    volaSeries = volaAnalyzer.getVolaSeries()
    plt.getOrCreateSubplot("Volatility").addDataSeries("Volatility",
                                                       volaSeries)

    # Run the strategy
    myStrategy.run()

    # Show basic information
    myStrategy.info("Valor final de la cartera: $%.2f" %
                    myStrategy.getBroker().getEquity())

    myStrategy.info("Ratio de Sharpe Anualizado: " +
                    str(sharpeAnalyzer.getSharpeRatio(0.0036, True)))

    myStrategy.info("DrawDown Maximo: " +
                    str(drawDownAnalyzer.getMaxDrawDown()))
    myStrategy.info("DrawDown Mas Largo: " +
                    str(drawDownAnalyzer.getLongestDrawDownDuration()))

    meanProfit = stats.mean(tradesAnalyzer.getProfits())
    myStrategy.info("Ganancia Media: " + str(meanProfit))
    meanLoss = stats.mean(tradesAnalyzer.getLosses())
    myStrategy.info("Perdida Media: " + str(meanLoss))
    myStrategy.info("Num Ops Igual: " + str(tradesAnalyzer.getEvenCount()))
    myStrategy.info("Num Ops Gano: " +
                    str(tradesAnalyzer.getProfitableCount()))
    myStrategy.info("Num Ops Pierdo: " +
                    str(tradesAnalyzer.getUnprofitableCount()))

    allRet = returnsAnalyzer.getReturns()
    #print len(allRet)
    myStrategy.info("Rent Media: " + str(stats.mean(allRet)))
    posRet = []
    negRet = []
    allRet = returnsAnalyzer.getReturns()
    for ret in allRet:
        if ret > 0:
            posRet.append(ret)
        elif ret < 0:
            negRet.append(ret)
    myStrategy.info("Ganancia Media: " + str(stats.mean(posRet)))
    myStrategy.info("Perdida Media: " + str(stats.mean(negRet)))

    myStrategy.info("Vola Media: " + str(stats.mean(volaSeries[-60:])))

    # Plot the strategy.
    plt.plot()
Exemple #3
0
# Attach analyzers to the strategy

returnsAnalyzer = returns.Returns()
myStrategy.attachAnalyzer(returnsAnalyzer)
returnsAnalyzer.getReturns().setMaxLen(1000000)

sharpeAnalyzer = sharpe.SharpeRatio()
myStrategy.attachAnalyzer(sharpeAnalyzer)

drawDownAnalyzer = drawdown.DrawDown()
myStrategy.attachAnalyzer(drawDownAnalyzer)

tradesAnalyzer = trades.Trades()
myStrategy.attachAnalyzer(tradesAnalyzer)

volaAnalyzer = volatility.VolaAnalyzer(120)
myStrategy.attachAnalyzer(volaAnalyzer)

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

capStart = myStrategy.getBroker().getEquity()
myStrategy.info("CAPITAL INICIAL: $%.4f" % capStart)

# Run the strategy
myStrategy.run()

# Show basic information
allRet = returnsAnalyzer.getReturns()
capEnd = myStrategy.getBroker().getEquity()