Beispiel #1
0
def main():
    # Load the orders file.
    ordersFile = OrdersFile("orders.csv")
    print "First date", ordersFile.getFirstDate()
    print "Last date", ordersFile.getLastDate()
    print "Symbols", ordersFile.getInstruments()

    # Load the data from QSTK storage. QS environment variable has to be defined.
    if os.getenv("QS") is None:
        raise Exception("QS environment variable not defined")
    feed = yahoofeed.Feed()
    feed.setBarFilter(csvfeed.DateRangeFilter(ordersFile.getFirstDate(), ordersFile.getLastDate()))
    feed.setDailyBarTime(datetime.time(0, 0, 0))  # This is to match the dates loaded with the ones in the orders file.
    for symbol in ordersFile.getInstruments():
        feed.addBarsFromCSV(symbol, os.path.join(os.getenv("QS"), "QSData", "Yahoo", symbol + ".csv"))

    # Run the strategy.
    cash = 1000000
    useAdjustedClose = True
    myStrategy = MyStrategy(feed, cash, ordersFile, useAdjustedClose)

    # Attach returns and sharpe ratio analyzers.
    retAnalyzer = returns.Returns()
    myStrategy.attachAnalyzer(retAnalyzer)
    sharpeRatioAnalyzer = sharpe.SharpeRatio()
    myStrategy.attachAnalyzer(sharpeRatioAnalyzer)

    myStrategy.run()

    # Print the results.
    print "Final portfolio value: $%.2f" % myStrategy.getResult()
    print "Anual return: %.2f %%" % (retAnalyzer.getCumulativeReturns()[-1] * 100)
    print "Average daily return: %.2f %%" % (stats.mean(retAnalyzer.getReturns()) * 100)
    print "Std. dev. daily return: %.4f" % (stats.stddev(retAnalyzer.getReturns()))
    print "Sharpe ratio: %.2f" % (sharpeRatioAnalyzer.getSharpeRatio(0))
Beispiel #2
0
def main():
	# Load the orders file.
	ordersFile = OrdersFile("orders.csv")
	print "First date", ordersFile.getFirstDate()
	print "Last date", ordersFile.getLastDate()
	print "Symbols", ordersFile.getInstruments()

	# Load the data from QSTK storage. QS environment variable has to be defined.
	if os.getenv("QS") == None:
		raise Exception("QS environment variable not defined")
	feed = yahoofeed.Feed()
	feed.setBarFilter(csvfeed.DateRangeFilter(ordersFile.getFirstDate(), ordersFile.getLastDate()))
	feed.setDailyBarTime(datetime.time(0, 0, 0)) # This is to match the dates loaded with the ones in the orders file.
	for symbol in ordersFile.getInstruments():
		feed.addBarsFromCSV(symbol, os.path.join(os.getenv("QS"), "QSData", "Yahoo", symbol + ".csv"))

	# Run the strategy.
	cash = 1000000
	useAdjustedClose = True
	myStrategy = MyStrategy(feed, cash, ordersFile, useAdjustedClose)

	# Attach returns and sharpe ratio analyzers.
	retAnalyzer = returns.Returns()
	myStrategy.attachAnalyzer(retAnalyzer)
	sharpeRatioAnalyzer = sharpe.SharpeRatio()
	myStrategy.attachAnalyzer(sharpeRatioAnalyzer)

	myStrategy.run()

	# Print the results.
	print "Final portfolio value: $%.2f" % myStrategy.getResult()
	print "Anual return: %.2f %%" % (retAnalyzer.getCumulativeReturns()[-1] * 100)
	print "Average daily return: %.2f %%" % (stats.mean(retAnalyzer.getReturns()) * 100)
	print "Std. dev. daily return: %.4f" % (stats.stddev(retAnalyzer.getReturns()))
	print "Sharpe ratio: %.2f" % (sharpeRatioAnalyzer.getSharpeRatio(0, 252))
Beispiel #3
0
def main(tick, year, cash, smaPeriod, order):
    print 'Welcome, ' + os.environ['USER'] + '!'
    print 'Backtesting ' + tick + ' in ' + str(year)

    # Download daily bars
    filename = tick + '-' + str(year) + '.csv'
    yahoofinance.download_daily_bars(tick, year, filename)

    # Load CSV file
    feed = yahoofeed.Feed()
    feed.addBarsFromCSV(tick, filename)

    # Evaluate Strategy
    strategySMA = StrategySMA(feed, tick, smaPeriod, order, cash)

    # Attach a returns analyzers to the strategy.
    retAnalyzer = returns.Returns()
    strategySMA.attachAnalyzer(retAnalyzer)
    sharpeRatioAnalyzer = sharpe.SharpeRatio()
    strategySMA.attachAnalyzer(sharpeRatioAnalyzer)

    # Attach the plotter to the strategy.
    plt = plotter.StrategyPlotter(strategySMA)
    # Include the SMA in the instrument's subplot to get it displayed along with the closing prices.
    plt.getInstrumentSubplot(tick).addDataSeries("SMA", strategySMA.getSMA())

    # Set portfolio cash
    strategySMA.getBroker().setCash(cash)
    initial = strategySMA.getBroker().getEquity()

    # Run the strategy
    strategySMA.run()

    # Print the results
    print '*' * 60
    print 'Initial portfolio value: $%.2f' % initial

    final = strategySMA.getBroker().getEquity()
    print 'Final portfolio value: $%.2f' % final

    net = final - initial
    if net > 0:
        print 'Net gain: $%.2f' % net
    else:
        print 'Net loss: $%.2f' % net

    percentage = (final - initial) / initial * 100
    if percentage > 0:
        print 'Percentage gain: +%.2f%%' % percentage
    else:
        print 'Percentage loss: %.2f%%' % percentage

    #print 'Final portfolio value: $%.2f' % strategySMA.getResult()
    print 'Annual return: %.2f%%' % (retAnalyzer.getCumulativeReturns()[-1] * 100)
    print 'Average daily return: %.2f%%' % (stats.mean(retAnalyzer.getReturns()) * 100)
    print 'Std. dev. daily return: %.4f' % (stats.stddev(retAnalyzer.getReturns()))
    print 'Sharpe ratio: %.2f' % (sharpeRatioAnalyzer.getSharpeRatio(0))

    # Plot the strategy
    plt.plot()
Beispiel #4
0
    def getSharpeRatio(self, riskFreeRate, tradingPeriods, annualized=True):
        """
		Returns the Sharpe ratio for the strategy execution.
		If the volatility is 0, 0 is returned.

		:param riskFreeRate: The risk free rate per annum.
		:type riskFreeRate: int/float.
		:param tradingPeriods: The number of trading periods per annum.
		:type tradingPeriods: int/float.
		:param annualized: True if the sharpe ratio should be annualized.
		:type annualized: boolean.

		.. note::
			* If using daily bars, tradingPeriods should be set to 252.
			* If using hourly bars (with 6.5 trading hours a day) then tradingPeriods should be set to 252 * 6.5 = 1638.
		"""
        ret = 0.0

        # From http://en.wikipedia.org/wiki/Sharpe_ratio: if Rf is a constant risk-free return throughout the period,
        # then stddev(R - Rf) = stddev(R).
        volatility = stats.stddev(self.__netReturns, 1)

        if volatility != 0:
            excessReturns = [dailyRet - (riskFreeRate / float(tradingPeriods)) for dailyRet in self.__netReturns]
            avgExcessReturns = stats.mean(excessReturns)
            ret = avgExcessReturns / volatility
            if annualized:
                ret = ret * math.sqrt(tradingPeriods)
        return ret
Beispiel #5
0
def main():
	import dateutil.parser
	startPeriod = dateutil.parser.parse('2005-06-30T08:00:00.000Z')
	endPeriod = dateutil.parser.parse('2014-12-31T08:00:00.000Z')
	# Load the orders file.
	#ordersFile = OrdersFile("MasterOrders_Both_Abhi-26.csv", filterAction='sell', rank=500)
	#ordersFile = OrdersFile("MasterOrders_Both_SP-500.csv", filterAction='both', rank=500)
	ordersFile = OrdersFile("orders.csv", filterAction='both', rank=20)
	#ordersFile = OrdersFile("Problem-Orders.csv", filterAction='both', rank=20)
	#startPeriod = yearFromTimeSinceEpoch(ordersFile.getFirstDate())
	#endPeriod = yearFromTimeSinceEpoch(ordersFile.getLastDate())
	print "First Year", startPeriod
	print "Last Year", endPeriod
	print "Instruments", ordersFile.getInstruments()
	#instrument = ordersFile.getInstruments()[0]

	k = 0
	feed = None
	for instrument in ordersFile.getInstruments():
		if k == 0:
			feed = xiquantPlatform.redis_build_feed_EOD_RAW(instrument, startPeriod, endPeriod)
		else:
			feed = xiquantPlatform.add_feeds_EODRAW_CSV(feed, instrument, startPeriod, endPeriod)
		k += 1

	# Add the SPY bars to support the simulation of whether we should have
	# entered certain trades or not -- based on the SPY opening higher/lower
	# than 20 SMA value for bullish/bearish trades.
	feed = xiquantPlatform.add_feeds_EODRAW_CSV(feed, 'SPY', startPeriod, endPeriod)

	barsDictForCurrAdj = {}
	for instrument in ordersFile.getInstruments():
		barsDictForCurrAdj[instrument] = feed.getBarSeries(instrument)
	barsDictForCurrAdj['SPY'] = feed.getBarSeries('SPY')
	feedAdjustedToEndDate = xiquantPlatform.adjustBars(barsDictForCurrAdj, startPeriod, endPeriod, keyFlag=False)

	cash = 100000
	useAdjustedClose = True
	#myStrategy = MyStrategy(feedAdjustedToEndDate, endPeriod, cash, ordersFile, useAdjustedClose)
	myStrategy = MyStrategy(feedAdjustedToEndDate, endPeriod, cash, ordersFile, useAdjustedClose)
	# Attach returns and sharpe ratio analyzers.
	retAnalyzer = returns.Returns()
	myStrategy.attachAnalyzer(retAnalyzer)
	sharpeRatioAnalyzer = sharpe.SharpeRatio()
	myStrategy.attachAnalyzer(sharpeRatioAnalyzer)

	myStrategy.run()
	filteredOrders = ordersFile.getOrders()
	for key in sorted(filteredOrders.iterkeys()):
		print key, filteredOrders[key]

	# Print the results.
	print "Final Portfolio Value: $%.2f" % myStrategy.getResult()
	print "Total Return: %.2f %%" % (retAnalyzer.getCumulativeReturns()[-1] * 100)
	print "Average Daily Return: %.2f %%" % (stats.mean(retAnalyzer.getReturns()) * 100)
	print "Std. Dev. Daily Return: %.4f" % (stats.stddev(retAnalyzer.getReturns()))
	print "Sharpe Ratio: %.2f" % (sharpeRatioAnalyzer.getSharpeRatio(0))
	print "Strategy Results:\n" 
	print myStrategy.getStrategiesOutput()
	print myStrategy.getResults()
Beispiel #6
0
    def getLosingStdDev(self, ddof=1):
        """Returns the profit's standard deviation for the losing trades, or None if there are no losing trades.

		:param ddof: Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements.
		:type ddof: int.
		"""
        return stats.stddev(self.__losingTrades, ddof)
Beispiel #7
0
	def getLosingStdDev(self, ddof=1):
		"""Returns the profit's standard deviation for the losing trades, or None if there are no losing trades.

		:param ddof: Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements.
		:type ddof: int.
		"""
		return stats.stddev(self.__losingTrades, ddof)
Beispiel #8
0
def main():
    # Load the orders file.
    ordersFile = OrdersFile("./OrderFiles/orders.csv")
    print "First date", ordersFile.getFirstDate()
    print "Last date", ordersFile.getLastDate()
    print "Symbols", ordersFile.getInstruments()


    qsPath = "/Users/LunaFire/Anaconda/lib/python2.7/site-packages/QSTK"

    feed = yahoofeed.Feed()
    feed.setBarFilter(csvfeed.DateRangeFilter(ordersFile.getFirstDate(), ordersFile.getLastDate()))
    feed.setDailyBarTime(datetime.time(0, 0, 0))  # This is to match the dates loaded with the ones in the orders file.
    for symbol in ordersFile.getInstruments():
        feed.addBarsFromCSV(symbol, os.path.join(qsPath, "QSData", "Yahoo", symbol + ".csv"))

    # Run the strategy.
    cash = 1000000
    useAdjustedClose = True
    myStrategy = MyStrategy(feed, cash, ordersFile, useAdjustedClose)

    # Attach returns and sharpe ratio analyzers.
    retAnalyzer = returns.Returns()
    myStrategy.attachAnalyzer(retAnalyzer)
    sharpeRatioAnalyzer = sharpe.SharpeRatio()
    myStrategy.attachAnalyzer(sharpeRatioAnalyzer)

    myStrategy.run()

    # Print the results.
    print "Final portfolio value: $%.2f" % myStrategy.getResult()
    print "Anual return: %.2f %%" % (retAnalyzer.getCumulativeReturns()[-1] * 100)
    print "Average daily return: %.2f %%" % (stats.mean(retAnalyzer.getReturns()) * 100)
    print "Std. dev. daily return: %.4f" % (stats.stddev(retAnalyzer.getReturns()))
    print "Sharpe ratio: %.2f" % (sharpeRatioAnalyzer.getSharpeRatio(0))
Beispiel #9
0
def volatility(returns, tradingPeriods):
    ret = 0.0

    # From http://en.wikipedia.org/wiki/Sharpe_ratio: if Rf is a constant risk-free return throughout the period,
    # then stddev(R - Rf) = stddev(R).
    volatility = stats.stddev(returns, 1)
    ret = volatility * math.sqrt(tradingPeriods)
    return ret
Beispiel #10
0
def main(printinfo):
    firstyear = 2007
    lastyear = 2013
    num_instr = 3
    posinstruments = daq.find_instruments_by_year(firstyear)
    instruments = sample(posinstruments, num_instr)
    instruments = ['JCI', 'AAPL', 'YUM', 'ABC']
    feed = daq.build_stock_feed(instruments, [firstyear, lastyear])
    this_Strategy = sgs.SLTRIXCrossover(feed,
                                        instruments,
                                        100000,
                                        12,
                                        27,
                                        .43,
                                        .43,
                                        printinfo=printinfo)
    # this_Strategy = sgs.EMACrossover(feed, instruments, 100000, 28, .5, ('FixedPerTrade', 10))
    retAnalyzer = returns.Returns()
    this_Strategy.attachAnalyzer(retAnalyzer)
    # this_Strategy.getBroker().setCommission(
    # backtesting.TradePercentage(.01))  # 1.% commission per trade
    this_Strategy.getBroker().setCommission(
        backtesting.FixedPerTrade(10))  # $10 commission per trade

    # Attach plotters
    # Attach the plotter to the strategy.
    plt = plotter.StrategyPlotter(this_Strategy)
    # Include the SMA in the instrument's subplot to get it displayed along
    # with the closing prices.

    # for pltinstr in instruments:
    #     plt.getInstrumentSubplot(pltinstr).addDataSeries(
    #         "Short TRIX", this_Strategy.getshorttrix(pltinstr))
    #     plt.getInstrumentSubplot(pltinstr).addDataSeries(
    #         "Long TRIX", this_Strategy.getlongtrix(pltinstr))

    # for pltinstr in instruments:
    #     plt.getInstrumentSubplot(pltinstr).addDataSeries(
    #         "EMA", this_Strategy.getEMA(pltinstr))

    # # Plot the simple returns on each bar.
    # plt.getOrCreateSubplot("returns").addDataSeries(
    #     "Simple returns", retAnalyzer.getReturns())
    # Run the strategy
    this_Strategy.run()

    # Print the results.
    print "Final portfolio value: $%.2f" % this_Strategy.getResult()
    print "Annual return: %.2f %%" % (
        (retAnalyzer.getCumulativeReturns()[-1] * 100) /
        float(lastyear - firstyear))
    print "Average daily return: %.2f %%" % (
        stats.mean(retAnalyzer.getReturns()) * 100)
    print "Std. dev. daily return: %.4f" % (stats.stddev(
        retAnalyzer.getReturns()))
    plt.plot()
    return this_Strategy.getResult()
Beispiel #11
0
 def getBeta(self, riskRate):
     ret = 0.0
     # tushare获取的涨跌幅数据已*100 故在此/100
     volatility = stats.stddev(np.array(riskRate) / 100, 1)
     if volatility != 0 and not np.isnan(volatility):
         ret = cov(np.array(self.__returns),
                   np.array(riskRate) / 100) / pow(volatility, 2)
     self.__beta = ret
     return ret
Beispiel #12
0
def algo_test(target_name,
              target_csv,
              model_name,
              model_csv,
              model_prediction_std=0.0):
    # Load the bar feed from the CSV file
    feed = csvfeed.GenericBarFeed(pyalgotrade.bar.Frequency.DAY)
    feed.addBarsFromCSV(target_name, target_csv)
    feed.addBarsFromCSV(model_name, model_csv)

    # Evaluate the strategy with the feed's bars.
    myStrategy = MyStrategy(feed, target_name, model_prediction_std)
    # myStrategy = MyBasicStrategy(feed, target_name)

    # Attach analyzers.
    retAnalyzer = returns.Returns()
    myStrategy.attachAnalyzer(retAnalyzer)
    sharpeRatioAnalyzer = sharpe.SharpeRatio()
    myStrategy.attachAnalyzer(sharpeRatioAnalyzer)
    drawDownAnalyzer = drawdown.DrawDown()
    myStrategy.attachAnalyzer(drawDownAnalyzer)
    sortinoRatioAnalyzer = sortino.SortinoRatio()
    myStrategy.attachAnalyzer(sortinoRatioAnalyzer)

    # Run the strategy
    myStrategy.run()

    # Print the results.
    print("Final portfolio value: $%.2f" % myStrategy.getResult())
    print("Total return: %.2f %%" %
          (retAnalyzer.getCumulativeReturns()[-1] * 100))
    print("Average daily return: %.2f %%" %
          (stats.mean(retAnalyzer.getReturns()) * 100))
    print("Std. dev. daily return: %.4f" %
          (stats.stddev(retAnalyzer.getReturns())))
    print("Sharpe ratio: %.2f" % (sharpeRatioAnalyzer.getSharpeRatio(0)))
    print("Sortino ratio: %.2f" % (sortinoRatioAnalyzer.getSortinoRatio(0)))

    returnsPerDay = stats.mean(retAnalyzer.getReturns())

    # print("shares list : ")
    # print(myStrategy.getShares())
    output = {
        'sharpe': sharpeRatioAnalyzer.getSharpeRatio(0),
        'sortino': sortinoRatioAnalyzer.getSortinoRatio(0),
        'returnAnalyzer': retAnalyzer,
        'annualReturns': returnsPerDay * 252
    }

    return output
Beispiel #13
0
def sharpe_ratio(returns, riskFreeRate, tradingPeriods, annualized=True):
    ret = 0.0

    # From http://en.wikipedia.org/wiki/Sharpe_ratio: if Rf is a constant risk-free return throughout the period,
    # then stddev(R - Rf) = stddev(R).
    volatility = stats.stddev(returns, 1)

    if volatility != 0:
        excessReturns = [dailyRet - (riskFreeRate / float(tradingPeriods)) for dailyRet in returns]
        avgExcessReturns = stats.mean(excessReturns)
        ret = avgExcessReturns / volatility
        if annualized:
            ret = ret * math.sqrt(tradingPeriods)
    return ret
Beispiel #14
0
def sharpe_ratio(returns, riskFreeRate, tradingPeriods, annualized=True):
    ret = 0.0

    # From http://en.wikipedia.org/wiki/Sharpe_ratio: if Rf is a constant risk-free return throughout the period,
    # then stddev(R - Rf) = stddev(R).
    volatility = stats.stddev(returns, 1)

    if volatility != 0:
        rfPerReturn = riskFreeRate / float(tradingPeriods)
        avgExcessReturns = stats.mean(returns) - rfPerReturn
        ret = avgExcessReturns / volatility

        if annualized:
            ret = ret * math.sqrt(tradingPeriods)
    return ret
Beispiel #15
0
 def __onReturns(self, dateTime, returnsAnalyzerBase):
     netReturn = returnsAnalyzerBase.getNetReturn()
     # Calculate daily returns.
     if dateTime.date() == self.__currentDate:
         self.__retBuffer.append(netReturn)
     else:
         if self.__retBuffer:
             self.__retBuffer.append(netReturn)
             netReturn = self.__retBuffer[0]
             for aReturn in self.__retBuffer[1:]:
                 netReturn = (1 + netReturn) * (1 + aReturn) - 1
             self.__retBuffer = []
         self.__currentDate = dateTime.date()
         self.__returns.append(netReturn)
         if len(self.__returns) == self.__sessions:
             self.__volaSeries.appendWithDateTime(dateTime.date(), stats.stddev(self.__returns, 1) * math.sqrt(252) * 100)
def main(printinfo):
    firstyear = 2007
    lastyear = 2013
    num_instr = 3
    posinstruments = daq.find_instruments_by_year(firstyear)
    instruments = sample(posinstruments, num_instr)
    instruments = ['JCI', 'AAPL', 'YUM', 'ABC']
    feed = daq.build_stock_feed(instruments, [firstyear, lastyear])
    this_Strategy = sgs.SLTRIXCrossover(
        feed, instruments, 100000, 12, 27, .43, .43, printinfo=printinfo)
    # this_Strategy = sgs.EMACrossover(feed, instruments, 100000, 28, .5, ('FixedPerTrade', 10))
    retAnalyzer = returns.Returns()
    this_Strategy.attachAnalyzer(retAnalyzer)
    # this_Strategy.getBroker().setCommission(
    # backtesting.TradePercentage(.01))  # 1.% commission per trade
    this_Strategy.getBroker().setCommission(
        backtesting.FixedPerTrade(10))  # $10 commission per trade

    # Attach plotters
    # Attach the plotter to the strategy.
    plt = plotter.StrategyPlotter(this_Strategy)
    # Include the SMA in the instrument's subplot to get it displayed along
    # with the closing prices.

    # for pltinstr in instruments:
    #     plt.getInstrumentSubplot(pltinstr).addDataSeries(
    #         "Short TRIX", this_Strategy.getshorttrix(pltinstr))
    #     plt.getInstrumentSubplot(pltinstr).addDataSeries(
    #         "Long TRIX", this_Strategy.getlongtrix(pltinstr))

    # for pltinstr in instruments:
    #     plt.getInstrumentSubplot(pltinstr).addDataSeries(
    #         "EMA", this_Strategy.getEMA(pltinstr))

    # # Plot the simple returns on each bar.
    # plt.getOrCreateSubplot("returns").addDataSeries(
    #     "Simple returns", retAnalyzer.getReturns())
    # Run the strategy
    this_Strategy.run()

    # Print the results.
    print "Final portfolio value: $%.2f" % this_Strategy.getResult()
    print "Annual return: %.2f %%" % ((retAnalyzer.getCumulativeReturns()[-1] * 100)/float(lastyear - firstyear))
    print "Average daily return: %.2f %%" % (stats.mean(retAnalyzer.getReturns()) * 100)
    print "Std. dev. daily return: %.4f" % (stats.stddev(retAnalyzer.getReturns()))
    plt.plot()
    return this_Strategy.getResult()
Beispiel #17
0
def sharpe_ratio_2(returns, riskFreeRate, firstDateTime, lastDateTime, annualized=True):
    ret = 0.0

    # From http://en.wikipedia.org/wiki/Sharpe_ratio:
    # if Rf is a constant risk-free return throughout the period, then stddev(R - Rf) = stddev(R).
    volatility = stats.stddev(returns, 1)

    if volatility != 0:
        # We use 365 instead of 252 becuase we wan't the diff from 1/1/xxxx to 12/31/xxxx to be 1 year.
        yearsTraded = days_traded(firstDateTime, lastDateTime) / 365.0

        riskFreeRateForPeriod = riskFreeRate * yearsTraded
        rfPerReturn = riskFreeRateForPeriod / float(len(returns))

        avgExcessReturns = stats.mean(returns) - rfPerReturn
        ret = avgExcessReturns / volatility
        if annualized:
            ret = ret * math.sqrt(len(returns) / yearsTraded)
    return ret
Beispiel #18
0
def sharpe_ratio_2(returns, riskFreeRate, firstDateTime, lastDateTime, annualized=True):
    ret = 0.0

    # From http://en.wikipedia.org/wiki/Sharpe_ratio:
    # if Rf is a constant risk-free return throughout the period, then stddev(R - Rf) = stddev(R).
    volatility = stats.stddev(returns, 1)

    if volatility != 0:
        # We use 365 instead of 252 becuase we wan't the diff from 1/1/xxxx to 12/31/xxxx to be 1 year.
        yearsTraded = days_traded(firstDateTime, lastDateTime) / 365.0

        riskFreeRateForPeriod = riskFreeRate * yearsTraded
        rfPerReturn = riskFreeRateForPeriod / float(len(returns))

        avgExcessReturns = stats.mean(returns) - rfPerReturn
        ret = avgExcessReturns / volatility
        if annualized:
            ret = ret * math.sqrt(len(returns) / yearsTraded)
    return ret
Beispiel #19
0
myStrategy.attachAnalyzer(retAnalyzer)
sharpeRatioAnalyzer = sharpe.SharpeRatio()
myStrategy.attachAnalyzer(sharpeRatioAnalyzer)
drawDownAnalyzer = drawdown.DrawDown()
myStrategy.attachAnalyzer(drawDownAnalyzer)

# Run the strategy
myStrategy.run()

# Print the results.
print("")
print("最终资产价值 Final portfolio value: $%.2f" % myStrategy.getResult())
print("年收益 Anual return: %.2f %%" %
      (retAnalyzer.getCumulativeReturns()[-1] * 100))
print("平均日收益率 Average daily return: %.2f %%" %
      (stats.mean(retAnalyzer.getReturns()) * 100))
print("日收益率方差 Std. dev. daily return: %.4f" %
      (stats.stddev(retAnalyzer.getReturns())))
print("夏普指数 Sharpe ratio: %.2f" % (sharpeRatioAnalyzer.getSharpeRatio(0)))
print("最大回撤率 Max. drawdown: %.2f %%" %
      (drawDownAnalyzer.getMaxDrawDown() * 100))
print("最长回撤时间 Longest drawdown duration: %s" %
      (drawDownAnalyzer.getLongestDrawDownDuration()))

print('')
fss = 'tmp\dret010.csv'
xs1 = ret2csv(fss)

mpl.use('seaborn-whitegrid')
xs1.plot()
Beispiel #20
0
    def onBars(self, bars):
        pass

priceCurrency = "USD"
# Load the bar feed from the CSV file
feed = quandlfeed.Feed()
feed.addBarsFromCSV("ibm/USD", "WIKI-IBM-2011-quandl.csv")
feed.addBarsFromCSV("aes/USD", "WIKI-AES-2011-quandl.csv")
feed.addBarsFromCSV("aig/USD", "WIKI-AIG-2011-quandl.csv")
feed.addBarsFromCSV("orcl/USD", "WIKI-ORCL-2011-quandl.csv")

# Evaluate the strategy with the feed's bars.
myStrategy = MyStrategy(feed)

# Attach returns and sharpe ratio analyzers.
retAnalyzer = returns.Returns(priceCurrency)
myStrategy.attachAnalyzer(retAnalyzer)
sharpeRatioAnalyzer = sharpe.SharpeRatio(priceCurrency)
myStrategy.attachAnalyzer(sharpeRatioAnalyzer)

# Run the strategy
myStrategy.run()

# Print the results.
print("Final portfolio value: $%.2f" % myStrategy.getResult())
print("Anual return: %.2f %%" % (retAnalyzer.getCumulativeReturns()[-1] * 100))
print("Average daily return: %.2f %%" % (stats.mean(retAnalyzer.getReturns()) * 100))
print("Std. dev. daily return: %.4f" % (stats.stddev(retAnalyzer.getReturns())))
print("Sharpe ratio: %.2f" % (sharpeRatioAnalyzer.getSharpeRatio(0)))
    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" %
                    (sharpeAnalyzer.getSharpeRatio(0.0036, True)))

    myStrategy.info("DrawDown Maximo: %.4f%%" %
                    (100 * drawDownAnalyzer.getMaxDrawDown()))
    myStrategy.info("DrawDown Mas Largo: %s dias" %
                    (drawDownAnalyzer.getLongestDrawDownDuration().days))

    # Plot the strategy.
    plt.plot()
Beispiel #22
0
    def protfolio(self, myStrategy):
        retAnalyzer = returns.Returns()
        sharpeRatioAnalyzer = sharpe.SharpeRatio()
        drawDownAnalyzer = drawdown.DrawDown()
        tradesAnalyzer = trades.Trades()

        myStrategy.attachAnalyzer(retAnalyzer)
        myStrategy.attachAnalyzer(sharpeRatioAnalyzer)
        myStrategy.attachAnalyzer(drawDownAnalyzer)

        myStrategy.attachAnalyzer(tradesAnalyzer)

        myStrategy.run()
        dfjson = myStrategy.EchoDF()
        if self._Debug:
            print dfjson
            print "--------------"

        finalProt = myStrategy.getResult()

        brjObject = brj()

        #交易过程

        brjObject.db(dfjson.to_json(orient="split"))
        ## ...
        brjObject.formats("markPoint")
        brjObject.name("df")
        brjObject.buildData()

        brjObject.db(dfjson.to_json(orient="split"))
        ## ...
        brjObject.formats("table")
        brjObject.name("交易细则")
        brjObject.buildData()

        base = {}
        #总资产
        base["Final portfolio value: "] = "$%.2f" % finalProt
        #累计收益率
        base["Anual return: "] = "%.2f %%" % (
            retAnalyzer.getCumulativeReturns()[-1] * 100)
        #    平均收益率
        base["Average daily return:"] = " %.2f %%" % (
            stats.mean(retAnalyzer.getReturns()) * 100)
        #方差收益率
        base["Std. dev. daily return:"] = " %.4f" % (stats.stddev(
            retAnalyzer.getReturns()))
        #夏普比率
        base["Sharpe ratio: "] = "%.2f" % (
            sharpeRatioAnalyzer.getSharpeRatio(0))
        #最大回撤
        base["DrawDown :"] = " %.2f" % (drawDownAnalyzer.getMaxDrawDown())
        dfbase = pd.DataFrame(base, index=["val"])
        if self._Debug:
            print dfbase.T
            print "--------------"

        baseJson = dfbase.T.reset_index().to_json(orient="split")

        brjObject.db(baseJson)
        brjObject.formats("table")
        brjObject.name("base")
        brjObject.buildData()

        AllTrades = {}
        #总交易笔数
        AllTrades["Total trades:"] = " %d" % (tradesAnalyzer.getCount())
        if tradesAnalyzer.getCount() > 0:
            profits = tradesAnalyzer.getAll()
            AllTrades["Avg. profit:"] = " $%2.f" % (profits.mean())
            AllTrades["Profits std. dev.:"] = " $%2.f" % (profits.std())
            AllTrades["Max. profit: "] = "$%2.f" % (profits.max())
            AllTrades["Min. profit:"] = " $%2.f" % (profits.min())
            returns_trade = tradesAnalyzer.getAllReturns()
            AllTrades["Avg. return:"] = " %2.f %%" % (returns_trade.mean() *
                                                      100)
            AllTrades["Returns std. dev.: "] = "%2.f %%" % (
                returns_trade.std() * 100)
            AllTrades["Max. return: "] = "%2.f %%" % (returns_trade.max() *
                                                      100)
            AllTrades["Min. return: "] = "%2.f %%" % (returns_trade.min() *
                                                      100)

        df = pd.DataFrame(AllTrades, index=["val"])
        if self._Debug:
            print df.T
            print "--------------"

        baseJson = df.T.reset_index().to_json(orient="split")

        brjObject.db(baseJson)
        brjObject.formats("table")
        brjObject.name("AllTrades")
        brjObject.buildData()

        #盈利笔数
        proTrades = {}
        proTrades["Profitable trades: "] = "%d" % (
            tradesAnalyzer.getProfitableCount())
        if tradesAnalyzer.getProfitableCount() > 0:
            profits = tradesAnalyzer.getProfits()
            proTrades["Avg. profit: "] = "$%2.f" % (profits.mean())
            proTrades["Profits std. dev.: "] = "$%2.f" % (profits.std())
            proTrades["Max. profit:"] = " $%2.f" % (profits.max())
            proTrades["Min. profit:"] = " $%2.f" % (profits.min())
            returns_trade = tradesAnalyzer.getPositiveReturns()
            proTrades["Avg. return: "] = "%2.f %%" % (returns_trade.mean() *
                                                      100)
            proTrades["Returns std. dev.:"] = " %2.f %%" % (
                returns_trade.std() * 100)
            proTrades["Max. return: "] = "%2.f %%" % (returns_trade.max() *
                                                      100)
            proTrades["Min. return: "] = "%2.f %%" % (returns_trade.min() *
                                                      100)

        df = pd.DataFrame(proTrades, index=["val"])
        if self._Debug:
            print df.T
            print "--------------"

        baseJson = df.T.reset_index().to_json(orient="split")

        brjObject.db(baseJson)
        brjObject.formats("table")
        brjObject.name("proTrades")
        brjObject.buildData()
        #亏损笔数
        unproTrades = {}
        unproTrades["Unprofitable trades:"] = " %d" % (
            tradesAnalyzer.getUnprofitableCount())
        if tradesAnalyzer.getUnprofitableCount() > 0:
            losses = tradesAnalyzer.getLosses()
            unproTrades["Avg. loss:"] = " $%2.f" % (losses.mean())
            unproTrades["Losses std. dev.:"] = " $%2.f" % (losses.std())
            unproTrades["Max. loss: "] = "$%2.f" % (losses.min())
            unproTrades["Min. loss: "] = "$%2.f" % (losses.max())
            returns_trade = tradesAnalyzer.getNegativeReturns()
            unproTrades["Avg. return: "] = "%2.f %%" % (returns_trade.mean() *
                                                        100)
            unproTrades["Returns std. dev.: "] = "%2.f %%" % (
                returns_trade.std() * 100)
            unproTrades["Max. return: "] = "%2.f %%" % (returns_trade.max() *
                                                        100)
            unproTrades["Min. return: "] = "%2.f %%" % (returns_trade.min() *
                                                        100)

        df = pd.DataFrame(unproTrades, index=["val"])
        if self._Debug:
            print df.T
            print "--------------"

        baseJson = df.T.reset_index().to_json(orient="split")

        brjObject.db(baseJson)
        brjObject.formats("table")
        brjObject.name("unproTrades")
        brjObject.buildData()

        brjJson = brjObject.getResult()
        if self._Debug == False:
            print brjJson
Beispiel #23
0
			
	def onEnterOk(self, position):
		execInfo = position.getEntryOrder().getExecutionInfo()
		print("BUY at $%.2f 数量:%d 手续费:%.2f" % (execInfo.getPrice(), execInfo.getQuantity(), execInfo.getCommission()))
		
	def onBars(self, bars):
		pass
			
		
if __name__ == "__main__":
	feed = quandlfeed.Feed()
	feed.addBarsFromCSV("ibm", "WIKI-IBM-2011-quandl.csv")
	feed.addBarsFromCSV("aes", "WIKI-AES-2011-quandl.csv")
	feed.addBarsFromCSV("aig", "WIKI-AIG-2011-quandl.csv")
	feed.addBarsFromCSV("orcl", "WIKI-ORCL-2011-quandl.csv")
	
	myStrategy = MyStrategy(feed)

	retAnalyzer = returns.Returns()
	myStrategy.attachAnalyzer(retAnalyzer)
	sharpeAnalyzer = sharpe.SharpeRatio()
	myStrategy.attachAnalyzer(sharpeAnalyzer)
	
	myStrategy.run()
	
	print("最终收益:%.2f" % myStrategy.getResult())
	print("年化收益率:%.2f%%" % (retAnalyzer.getCumulativeReturns()[-1]*100))
	print("平均每日收益率:%.2f %%" % (stats.mean(retAnalyzer.getReturns())*100))
	print("每日收益标准差:%.4f" % (stats.stddev(retAnalyzer.getReturns())))
	print("夏普比率:%.2f" % sharpeAnalyzer.getSharpeRatio(0))
 
Beispiel #24
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()
Beispiel #25
0
	def __testStdDevImpl(self, values, ddof):
		self.__assertEqFloat(stats.stddev(values, ddof), stats.py_stddev(values, ddof))
Beispiel #26
0
def main(plot):
    instrument = "FB"
    #smaPeriod = 163
    smaPeriod = 30

    # Download the bars.
    feed = yahoofinance.build_feed([instrument], 2015, 2016, "../../data/")

    strat = SMACrossOver(feed, instrument, smaPeriod)

    retAnalyzer = returns.Returns()
    strat.attachAnalyzer(retAnalyzer)

    sharpeRatioAnalyzer = sharpe.SharpeRatio()
    strat.attachAnalyzer(sharpeRatioAnalyzer)

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

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


    if plot:
        plt = plotter.StrategyPlotter(strat, True, True, True)
        plt.getInstrumentSubplot(instrument).addDataSeries("sma", strat.getSMA())
        # Plot the simple returns on each bar.
        plt.getOrCreateSubplot("returns").addDataSeries("Simple returns", retAnalyzer.getReturns())
        #plt.getOrCreateSubplot("Slope").addDataSeries("slope", strat.getSlope())
        plt.getOrCreateSubplot("BuySlope").addDataSeries("BuySlope", strat.getBuySlope())

    strat.run()
    print "Final portfolio value: $%.2f" % strat.getResult()
    print "Cumulative returns: %.2f %%" % (retAnalyzer.getCumulativeReturns()[-1] * 100)
    print "Average daily return: %.2f %%" % (pystats.mean(retAnalyzer.getReturns()) * 100)
    print "Std. dev. daily return: %.4f" % (pystats.stddev(retAnalyzer.getReturns()))
    print "Sharpe ratio: %.2f" % (sharpeRatioAnalyzer.getSharpeRatio(0.05))
    print "Max. drawdown: %.2f %%" % (drawDownAnalyzer.getMaxDrawDown() * 100)
    print "Longest drawdown duration: %s" % (drawDownAnalyzer.getLongestDrawDownDuration())

    print
    print "Total trades: %d" % (tradesAnalyzer.getCount())
    if tradesAnalyzer.getCount() > 0:
        profits = tradesAnalyzer.getAll()
        print "Avg. profit: $%2.f" % (profits.mean())
        print "Profits std. dev.: $%2.f" % (profits.std())
        print "Max. profit: $%2.f" % (profits.max())
        print "Min. profit: $%2.f" % (profits.min())
        rets = tradesAnalyzer.getAllReturns()
        print "Avg. return: %2.f %%" % (rets.mean() * 100)
        print "Returns std. dev.: %2.f %%" % (rets.std() * 100)
        print "Max. return: %2.f %%" % (rets.max() * 100)
        print "Min. return: %2.f %%" % (rets.min() * 100)

    print
    print "Profitable trades: %d" % (tradesAnalyzer.getProfitableCount())
    if tradesAnalyzer.getProfitableCount() > 0:
        profits = tradesAnalyzer.getProfits()
        print "Avg. profit: $%2.f" % (profits.mean())
        print "Profits std. dev.: $%2.f" % (profits.std())
        print "Max. profit: $%2.f" % (profits.max())
        print "Min. profit: $%2.f" % (profits.min())
        rets = tradesAnalyzer.getPositiveReturns()
        print "Avg. return: %2.f %%" % (rets.mean() * 100)
        print "Returns std. dev.: %2.f %%" % (rets.std() * 100)
        print "Max. return: %2.f %%" % (rets.max() * 100)
        print "Min. return: %2.f %%" % (rets.min() * 100)

    print
    print "Unprofitable trades: %d" % (tradesAnalyzer.getUnprofitableCount())
    if tradesAnalyzer.getUnprofitableCount() > 0:
        losses = tradesAnalyzer.getLosses()
        print "Avg. loss: $%2.f" % (losses.mean())
        print "Losses std. dev.: $%2.f" % (losses.std())
        print "Max. loss: $%2.f" % (losses.min())
        print "Min. loss: $%2.f" % (losses.max())
        rets = tradesAnalyzer.getNegativeReturns()
        print "Avg. return: %2.f %%" % (rets.mean() * 100)
        print "Returns std. dev.: %2.f %%" % (rets.std() * 100)
        print "Max. return: %2.f %%" % (rets.max() * 100)
        print "Min. return: %2.f %%" % (rets.min() * 100)

    if plot:
        plt.plot()
Beispiel #27
0
def main(tick, year, cash, smaPeriod, order):
    print 'Welcome, ' + os.environ['USER'] + '!'
    print 'Backtesting ' + tick + ' in ' + str(year)

    # Download daily bars
    filename = tick + '-' + str(year) + '.csv'
    yahoofinance.download_daily_bars(tick, year, filename)

    # Load CSV file
    feed = yahoofeed.Feed()
    feed.addBarsFromCSV(tick, filename)

    # Evaluate Strategy
    strategySMA = StrategySMA(feed, tick, smaPeriod, order, cash)

    # Attach a returns analyzers to the strategy.
    retAnalyzer = returns.Returns()
    strategySMA.attachAnalyzer(retAnalyzer)
    sharpeRatioAnalyzer = sharpe.SharpeRatio()
    strategySMA.attachAnalyzer(sharpeRatioAnalyzer)

    # Attach the plotter to the strategy.
    plt = plotter.StrategyPlotter(strategySMA)
    # Include the SMA in the instrument's subplot to get it displayed along with the closing prices.
    plt.getInstrumentSubplot(tick).addDataSeries("SMA", strategySMA.getSMA())

    # Set portfolio cash
    strategySMA.getBroker().setCash(cash)
    initial = strategySMA.getBroker().getEquity()

    # Run the strategy
    strategySMA.run()

    # Print the results
    print '*' * 60
    print 'Initial portfolio value: $%.2f' % initial

    final = strategySMA.getBroker().getEquity()
    print 'Final portfolio value: $%.2f' % final

    net = final - initial
    if net > 0:
        print 'Net gain: $%.2f' % net
    else:
        print 'Net loss: $%.2f' % net

    percentage = (final - initial) / initial * 100
    if percentage > 0:
        print 'Percentage gain: +%.2f%%' % percentage
    else:
        print 'Percentage loss: %.2f%%' % percentage

    #print 'Final portfolio value: $%.2f' % strategySMA.getResult()
    print 'Annual return: %.2f%%' % (retAnalyzer.getCumulativeReturns()[-1] *
                                     100)
    print 'Average daily return: %.2f%%' % (
        stats.mean(retAnalyzer.getReturns()) * 100)
    print 'Std. dev. daily return: %.4f' % (stats.stddev(
        retAnalyzer.getReturns()))
    print 'Sharpe ratio: %.2f' % (sharpeRatioAnalyzer.getSharpeRatio(0))

    # Plot the strategy
    plt.plot()
Beispiel #28
0
    if hasattr(myStrategy, '_smaShort'):
        subPlot = plt.getOrCreateSubplot("SMA")
        subPlot.addDataSeries("SMALong", myStrategy._smaLong[instrument])
        subPlot.addDataSeries("SMAShort", myStrategy._smaShort[instrument])
        subPlot = plt.getOrCreateSubplot("MACD")
        subPlot.addDataSeries("MACDPrice", myStrategy._macdPrice[instrument])
        subPlot.addDataSeries("MACDVolume", myStrategy._macdVol[instrument])

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

    # Plot the strategy.
    plt.plot()
Beispiel #29
0
	def onBars(self, bars):
		pass

# Load the yahoo feed from CSV files.
feed = yahoofeed.Feed()
feed.addBarsFromCSV("aeti", "aeti-2011-yahoofinance.csv")
feed.addBarsFromCSV("egan", "egan-2011-yahoofinance.csv")
feed.addBarsFromCSV("glng", "glng-2011-yahoofinance.csv")
feed.addBarsFromCSV("simo", "simo-2011-yahoofinance.csv")

# Evaluate the strategy with the feed's bars.
myStrategy = MyStrategy(feed)

# Attach returns and sharpe ratio analyzers.
retAnalyzer = returns.Returns()
myStrategy.attachAnalyzer(retAnalyzer)
sharpeRatioAnalyzer = sharpe.SharpeRatio()
myStrategy.attachAnalyzer(sharpeRatioAnalyzer)

# Run the strategy
myStrategy.run()

# Print the results.
print "Final portfolio value: $%.2f" % myStrategy.getResult()
print "Anual return: %.2f %%" % (retAnalyzer.getCumulativeReturns()[-1] * 100)
print "Average daily return: %.2f %%" % (stats.mean(retAnalyzer.getReturns()) * 100)
print "Std. dev. daily return: %.4f" % (stats.stddev(retAnalyzer.getReturns()))
print "Sharpe ratio: %.2f" % (sharpeRatioAnalyzer.getSharpeRatio(0, 252))

Beispiel #30
0
def main(plot):
    # Download the bars.
    feed = build_feed(instFeed, start, endYear)
    # Define Strategy
    myStrategy = MyStrategy(feed, starting_cash)
    # Attach returns and sharpe ratio analyzers.
    returnsAnalyzer = returns.Returns()
    myStrategy.attachAnalyzer(returnsAnalyzer)
    sharpeRatioAnalyzer = sharpe.SharpeRatio()
    myStrategy.attachAnalyzer(sharpeRatioAnalyzer)
    tradesAnalyzer = trades.Trades()
    myStrategy.attachAnalyzer(tradesAnalyzer)
    drawDownAnalyzer = drawdown.DrawDown()
    myStrategy.attachAnalyzer(drawDownAnalyzer)
    
    if plot:
        symbol = "C"
        etf = sym_dictionary[symbol]
        spreadDS = dataseries.SequenceDataSeries(pltSpread[symbol])
        returnDS = dataseries.SequenceDataSeries(marketValue[symbol])
        MACD_ROC = dataseries.SequenceDataSeries(MFI_MACD[symbol][3])
        middleBandDS = dataseries.SequenceDataSeries(bollingerBands[symbol][1])
        upperBandDS = dataseries.SequenceDataSeries(bollingerBands[symbol][2])
        lowerBandDS = dataseries.SequenceDataSeries(bollingerBands[symbol][0])
        umiddleBandDS = dataseries.SequenceDataSeries(bollingerBands[symbol][3])
        lmiddleBandDS = dataseries.SequenceDataSeries(bollingerBands[symbol][4])
        MFI_MACD_ds = dataseries.SequenceDataSeries(MFI_MACD[symbol][0])
        MFI_MACDtrigger_ds = dataseries.SequenceDataSeries(MFI_MACD[symbol][1])
        MFI_MACDoscillator_ds = dataseries.SequenceDataSeries(MFI_MACD[symbol][2])
        plt = plotter.StrategyPlotter(myStrategy, False, False, False)
        plt.getOrCreateSubplot("spread").addDataSeries(symbol + ":" + etf, spreadDS)
        plt.getOrCreateSubplot("spread").addDataSeries("Middle", middleBandDS)
        plt.getOrCreateSubplot("spread").addDataSeries("Upper", upperBandDS)
        plt.getOrCreateSubplot("spread").addDataSeries("Lower", lowerBandDS)
        plt.getOrCreateSubplot("spread").addDataSeries("Mid-L", lmiddleBandDS)
        plt.getOrCreateSubplot("spread").addDataSeries("Mid-U", umiddleBandDS)
        plt.getOrCreateSubplot("returns").addDataSeries(symbol + "-Return", returnDS)
        plt.getOrCreateSubplot("returns").addDataSeries("Cum. return", returnsAnalyzer.getCumulativeReturns())
        #plt.getOrCreateSubplot("MFI").addDataSeries("MFI-MACD", MFI_MACD_ds)
        #plt.getOrCreateSubplot("MFI").addDataSeries("Trigger", MFI_MACDtrigger_ds)
        plt.getOrCreateSubplot("MACD").addDataSeries("Oscillator", MFI_MACDoscillator_ds)
        #plt.getOrCreateSubplot("MACD").addDataSeries("ROC", MACD_ROC)
        plt.getOrCreateSubplot("MACD").addDataSeries("0", [0])
        
    # Run the strategy
    print "Running Strategy..."
    myStrategy.clearOrders(orders_file)
    myStrategy.run()
    
    print "Final portfolio value: $%.2f" % myStrategy.getResult()
    print "Anual return: %.2f %%" % (returnsAnalyzer.getCumulativeReturns()[-1] * 100)
    print "Average daily return: %.2f %%" % (stats.mean(returnsAnalyzer.getReturns()) * 100)
    print "Std. dev. daily return: %.4f" % (stats.stddev(returnsAnalyzer.getReturns()))
    print "Sharpe ratio: %.2f" % (sharpeRatioAnalyzer.getSharpeRatio(0, 252))
    print
    print "Total trades: %d" % (tradesAnalyzer.getCount())
    if tradesAnalyzer.getCount() > 0:
        profits = tradesAnalyzer.getAll()
        print "Avg. profit: $%2.f" % (profits.mean())
        print "Profits std. dev.: $%2.f" % (profits.std())
        print "Max. profit: $%2.f" % (profits.max())
        print "Min. profit: $%2.f" % (profits.min())
        returnz = tradesAnalyzer.getAllReturns()
        print "Avg. return: %2.f %%" % (returnz.mean() * 100)
        print "Returns std. dev.: %2.f %%" % (returnz.std() * 100)
        print "Max. return: %2.f %%" % (returnz.max() * 100)
        print "Min. return: %2.f %%" % (returnz.min() * 100)
    print
    print "Profitable trades: %d" % (tradesAnalyzer.getProfitableCount())
    if tradesAnalyzer.getProfitableCount() > 0:
        profits = tradesAnalyzer.getProfits()
        print "Avg. profit: $%2.f" % (profits.mean())
        print "Profits std. dev.: $%2.f" % (profits.std())
        print "Max. profit: $%2.f" % (profits.max())
        print "Min. profit: $%2.f" % (profits.min())
        returnz = tradesAnalyzer.getPositiveReturns()
        print "Avg. return: %2.f %%" % (returnz.mean() * 100)
        print "Returns std. dev.: %2.f %%" % (returnz.std() * 100)
        print "Max. return: %2.f %%" % (returnz.max() * 100)
        print "Min. return: %2.f %%" % (returnz.min() * 100)
    print
    print "Unprofitable trades: %d" % (tradesAnalyzer.getUnprofitableCount())
    if tradesAnalyzer.getUnprofitableCount() > 0:
        losses = tradesAnalyzer.getLosses()
        print "Avg. loss: $%2.f" % (losses.mean())
        print "Losses std. dev.: $%2.f" % (losses.std())
        print "Max. loss: $%2.f" % (losses.min())
        print "Min. loss: $%2.f" % (losses.max())
        returnz = tradesAnalyzer.getNegativeReturns()
        print "Avg. return: %2.f %%" % (returnz.mean() * 100)
        print "Returns std. dev.: %2.f %%" % (returnz.std() * 100)
        print "Max. return: %2.f %%" % (returnz.max() * 100)
        print "Min. return: %2.f %%" % (returnz.min() * 100)
    print
    for symbol in instruments:
        print str(symbol)+ ": " + str(round(marketValue[symbol][-1], 4) * 100) + "%"
    print bbandPeriod   
    if plot:
            plt.plot(datetime.strptime('01/01/' + str(startYear), '%m/%d/%Y'))