コード例 #1
0
ファイル: report.py プロジェクト: nightrose79/try
def reporting(myStrtegy, plot):

    print "Final portfolio value: $%.2f" % myStrategy.getResult()
    print "Cumulative returns: %.2f %%" % (
        retAnalyzer.getCumulativeReturns()[-1] * 100)
    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())
        returns = tradesAnalyzer.getAllReturns()
        print "Avg. return: %2.f %%" % (returns.mean() * 100)
        print "Returns std. dev.: %2.f %%" % (returns.std() * 100)
        print "Max. return: %2.f %%" % (returns.max() * 100)
        print "Min. return: %2.f %%" % (returns.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())
        returns = tradesAnalyzer.getPositiveReturns()
        print "Avg. return: %2.f %%" % (returns.mean() * 100)
        print "Returns std. dev.: %2.f %%" % (returns.std() * 100)
        print "Max. return: %2.f %%" % (returns.max() * 100)
        print "Min. return: %2.f %%" % (returns.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())
        returns = tradesAnalyzer.getNegativeReturns()
        print "Avg. return: %2.f %%" % (returns.mean() * 100)
        print "Returns std. dev.: %2.f %%" % (returns.std() * 100)
        print "Max. return: %2.f %%" % (returns.max() * 100)
        print "Min. return: %2.f %%" % (returns.min() * 100)

    if plot:
        plt.plot()
コード例 #2
0
 def detail(self):
     """"""        
     print "-------------------------------------------------------------------------"
     print "Final portfolio value: $%.2f" % self.strat.getResult()
     print "Cumulative returns: %.2f %%" % (self.returnsAnalyzer.getCumulativeReturns()[-1] * 100)
     print "Sharpe ratio: %.2f" % (self.sharpeRatioAnalyzer.getSharpeRatio(0.05))
     print "Max. drawdown: %.2f %%" % (self.drawdownAnalyzer.getMaxDrawDown() * 100)
     print "Longest drawdown duration: (%s)" % (self.drawdownAnalyzer.getLongestDrawDownDuration())
     
     print
     print "Total trades: %d" % (self.tradesAnalyzer.getCount())
     if self.tradesAnalyzer.getCount() > 0:
         profits = self.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())
         returns = self.tradesAnalyzer.getAllReturns()
         print "Avg. return: %2.f %%" % (returns.mean() * 100)
         print "Returns std. dev.: %2.f %%" % (returns.std() * 100)
         print "Max. return: %2.f %%" % (returns.max() * 100)
         print "Min. return: %2.f %%" % (returns.min() * 100)
     
     print
     print "Profitable trades: %d" % (self.tradesAnalyzer.getProfitableCount())
     if self.tradesAnalyzer.getProfitableCount() > 0:
         profits = self.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())
         returns = self.tradesAnalyzer.getPositiveReturns()
         print "Avg. return: %2.f %%" % (returns.mean() * 100)
         print "Returns std. dev.: %2.f %%" % (returns.std() * 100)
         print "Max. return: %2.f %%" % (returns.max() * 100)
         print "Min. return: %2.f %%" % (returns.min() * 100)
     
     print
     print "Unprofitable trades: %d" % (self.tradesAnalyzer.getUnprofitableCount())
     if self.tradesAnalyzer.getUnprofitableCount() > 0:
         losses = self.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())
         returns = self.tradesAnalyzer.getNegativeReturns()
         print "Avg. return: %2.f %%" % (returns.mean() * 100)
         print "Returns std. dev.: %2.f %%" % (returns.std() * 100)
         print "Max. return: %2.f %%" % (returns.max() * 100)
         print "Min. return: %2.f %%" % (returns.min() * 100)    
     print "-------------------------------------------------------------------------"
コード例 #3
0
ファイル: testdata.py プロジェクト: zwdnet/MyQuant
def analyzer(testResult):
	# 回测信息
	print("年化收益率: %.2f %%" % (testResult[0].getCumulativeReturns()[-1] * 100))
	print("夏普比率: %.2f" % (testResult[1].getSharpeRatio(0.05)))
	print("最大回撤: %.2f %%" % (testResult[2].getMaxDrawDown() * 100))
	print("最大回撤期间: %s" % (testResult[2].getLongestDrawDownDuration()))
	
	# 交易信息
	td = testResult[3]
	print("-----------------------")
	print("总交易次数:%d" % (td.getCount()))
	if td.getCount() > 0:
		profits = td.getAll()
		print("平均收益:%.2f" % (profits.mean()))
		print("收益标准差:%.2f" % (profits.std()))
		print("最大收益:%.2f" % (profits.max()))
		print("最小收益:%.2f" % (profits.min()))
		returns = td.getAllReturns()
		print("平均收益率:%.2f%%" % (returns.mean() * 100))
		print("收益率标准差:%.2f%%" % (returns.std() * 100))
		print("最大收益率:%.2f%%" % (returns.max() * 100))
		print("最小收益率:%.2f%%" % (returns.min() * 100))
	
	print("-----------------------")	
	print("盈利的交易次数: %d" % (td.getProfitableCount()))
	if td.getProfitableCount() > 0:
		profits = td.getProfits()
		print("平均收益:%.2f" % (profits.mean()))
		print("收益标准差:%.2f" % (profits.std()))
		print("最大收益:%.2f" % (profits.max()))
		print("最小收益:%.2f" % (profits.min()))
		returns = td.getPositiveReturns()
		print("平均收益率:%.2f%%" % (returns.mean() * 100))
		print("收益率标准差:%.2f%%" % (returns.std() * 100))
		print("最大收益率:%.2f%%" % (returns.max() * 100))
		print("最小收益率:%.2f%%" % (returns.min() * 100))
		
	print("-----------------------")
	print("未盈利的交易次数: %d" % (td.getUnprofitableCount()))
	if td.getUnprofitableCount() > 0:
		losses = td.getLosses()
		print("平均收益:%.2f" % (losses.mean()))
		print("收益标准差:%.2f" % (losses.std()))
		print("最大收益:%.2f" % (losses.max()))
		print("最小收益:%.2f" % (losses.min()))
		returns = td.getNegativeReturns()
		print("平均收益率:%.2f%%" % (returns.mean() * 100))
		print("收益率标准差:%.2f%%" % (returns.std() * 100))
		print("最大收益率:%.2f%%" % (returns.max() * 100))
		print("最小收益率:%.2f%%" % (returns.min() * 100))
コード例 #4
0
ファイル: analyzer.py プロジェクト: fuckfuckfuckfuck/bin
def report_profit_return(get_count, get_profit, get_returns, ree):
    tmp = get_count()
    if 0 < tmp:
        profits = get_profit()
        # ree.append((profits.mean(),profits.std(),profits.max(),profits.min()))
        ree["profits_mean"] = profits.mean()
        ree["profits_std"] = profits.std()
        ree["profits_max"] = profits.max()
        ree["profits_min"] = profits.min()
        returns = get_returns()
        # ree.append((returns.mean() * 100, returns.std() * 100, returns.max() * 100, returns.min() * 100))
        ree["returns_mean"] = returns.mean() * 100
        ree["returns_std"] = returns.std() * 100
        ree["returns_max"] = returns.max() * 100
        ree["returns_min"] = returns.min() * 100
    else:
        ree["profits_mean"] = NULLVALUE
        ree["profits_std"] = NULLVALUE
        ree["profits_max"] = NULLVALUE
        ree["profits_min"] = NULLVALUE
        ree["returns_mean"] = NULLVALUE
        ree["returns_std"] = NULLVALUE
        ree["returns_max"] = NULLVALUE
        ree["returns_min"] = NULLVALUE
コード例 #5
0
ファイル: untitled1.py プロジェクト: nightrose79/try
def Function_form(    bBandsPeriod,smaPeriod_short,smaPeriod_long, slopePeriod,plot=False):
    from pyalgotrade.stratanalyzer import returns
    from pyalgotrade.stratanalyzer import sharpe
    from pyalgotrade.stratanalyzer import drawdown
    from pyalgotrade.stratanalyzer import trades

    from pyalgotrade import strategy
    from pyalgotrade.strategy import position
    from pyalgotrade import plotter
    from pyalgotrade.tools import yahoofinance
    from pyalgotrade.barfeed import yahoofeed
    from pyalgotrade.technical import bollinger
    from pyalgotrade.stratanalyzer import sharpe
    import BBands_mod
    #import report
    import matplotlib.pyplot as plt 

    # Load the yahoo feed from the CSV file
    feed = yahoofeed.Feed()
    feed.addBarsFromCSV("orcl", "data_daily.csv")

    #def main(plot):
    instrument = "orcl"


    # Evaluate the strategy with the feed's bars.
    myStrategy = BBands_mod.BBands(feed, instrument, bBandsPeriod,smaPeriod_short,smaPeriod_long,slopePeriod)

    if plot:
        plt = plotter.StrategyPlotter(myStrategy, True, True, True)
        plt.getInstrumentSubplot(instrument).addDataSeries("upper", myStrategy.getBollingerBands().getUpperBand())
        plt.getInstrumentSubplot(instrument).addDataSeries("middle", myStrategy.getBollingerBands().getMiddleBand())
        plt.getInstrumentSubplot(instrument).addDataSeries("lower", myStrategy.getBollingerBands().getLowerBand())

    # Attach different analyzers to a strategy before executing it.
    retAnalyzer = returns.Returns()
    myStrategy.attachAnalyzer(retAnalyzer)
    sharpeRatioAnalyzer = sharpe.SharpeRatio()
    myStrategy.attachAnalyzer(sharpeRatioAnalyzer)
    drawDownAnalyzer = drawdown.DrawDown()
    myStrategy.attachAnalyzer(drawDownAnalyzer)
    tradesAnalyzer = trades.Trades()
    myStrategy.attachAnalyzer(tradesAnalyzer)

    # Run the strategy.
    myStrategy.run()

    print "Final portfolio value: $%.2f" % myStrategy.getResult()
    print "Cumulative returns: %.2f %%" % (retAnalyzer.getCumulativeReturns()[-1] * 100)
    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())
        returns = tradesAnalyzer.getAllReturns()
        print "Avg. return: %2.f %%" % (returns.mean() * 100)
        print "Returns std. dev.: %2.f %%" % (returns.std() * 100)
        print "Max. return: %2.f %%" % (returns.max() * 100)
        print "Min. return: %2.f %%" % (returns.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())
        returns = tradesAnalyzer.getPositiveReturns()
        print "Avg. return: %2.f %%" % (returns.mean() * 100)
        print "Returns std. dev.: %2.f %%" % (returns.std() * 100)
        print "Max. return: %2.f %%" % (returns.max() * 100)
        print "Min. return: %2.f %%" % (returns.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())
        returns = tradesAnalyzer.getNegativeReturns()
        print "Avg. return: %2.f %%" % (returns.mean() * 100)
        print "Returns std. dev.: %2.f %%" % (returns.std() * 100)
        print "Max. return: %2.f %%" % (returns.max() * 100)
        print "Min. return: %2.f %%" % (returns.min() * 100)

    if plot:
        plt.plot()
    return (myStrategy.getResult(),retAnalyzer.getCumulativeReturns()[-1] * 100,
            sharpeRatioAnalyzer.getSharpeRatio(0.05), drawDownAnalyzer.getMaxDrawDown() * 100)
コード例 #6
0
def main():
    filedir = "testresults"
    iteration = 0
    resultsdict = {}

    for instrument in instrumentListGetter():
        if len(instrument.split()) > 1:
            instrument, instrumentSource = instrument.split()
            print "instrument: %s, source: %s" % (instrument, instrumentSource)
        else:
            instrumentSource = ""

        #feed = yahoofeed.Feed()
        #feed.addBarsFromCSV("hm",  DATAPATH + "/hm_table.csv")

        # Load the feed from the CSV files.

        #for params in parameters_generator():
        faileddataforinstrument = False
        for params in teststrategy.parameters_generator():

            # Do not move to outer loop or severe performance problems arise # take the data we have and use
            yiter = 0
            if "quandl" in instrumentSource:  # https://www.quandl.com/data/
                '''/home/carl/Projects/algotrader/algotrader/lib64/python2.7/site-packages/pyalgotrade/barfeed/csvfeed.py:171 needs try hack '''
                try:
                    feed = GenericBarFeed(frequency=bar.Frequency.DAY)
                    feed.setDateTimeFormat("%Y-%m-%d")
                    feed.setColumnName("datetime", "Date")
                    feed.setColumnName("adj_close", "Adjusted Close")
                    #feed.addBarsFromCSV(instrument, DATAPATH)
                    feed.addBarsFromCSV(instrument,
                                        DATAPATH + "/" + instrument + ".csv")
                except:
                    print sys.exc_info()
                    faileddataforinstrument = True

            else:
                for year in range(YEARSOFDATA, 0, -1):
                    startyear = localtime().tm_year - (YEARSOFDATA - yiter)
                    try:
                        feed = build_feed([instrument],
                                          startyear,
                                          2016,
                                          DATAPATH,
                                          frequency=86400,
                                          timezone=None,
                                          skipErrors=False)
                    except:
                        print "\n\nFailed downloading %s for year %d yiter %d \n\n" % (
                            instrument, startyear, yiter)
                        yiter += 1
                        if year == (YEARSOFDATA - 1):
                            faileddataforinstrument = True

            if faileddataforinstrument:
                break

            strat = teststrategy.TestStrat(feed, instrument, *params)
            iteration += 1

            paramnames = teststrategy.parameters_generator(paramnames=True)
            paramsarray = zip(paramnames, [str(p) for p in params])
            paramsstring = str([
                ":".join(t) for t in zip(paramnames, [str(p) for p in params])
            ])

            print "\n\nIteration %d / %d; Instrument %s ; Params %s" % (
                iteration, iterations, instrument, paramsstring)

            #retAnalyzer = returns.Returns()
            #strat.attachAnalyzer(retAnalyzer)
            sharpeRatioAnalyzer = sharpe.SharpeRatio()
            strat.attachAnalyzer(sharpeRatioAnalyzer)
            #drawDownAnalyzer = drawdown.DrawDown()
            #strat.attachAnalyzer(drawDownAnalyzer)
            tradesAnalyzer = trades.Trades()
            strat.attachAnalyzer(tradesAnalyzer)

            # with instrument
            #csvdict["Params"] = [":".join(t) for t in  zip(("instrument", "entrySMA", "exitDays", "rsiPeriod", "overBoughtThreshold", "overSoldThreshold"), [str(p) for p in params] )]
            # without instrument

            print paramsstring
            strat.run()
            tradetotal = 0

            tradetotal = sum(
                [t * 100.00 for t in tradesAnalyzer.getAllReturns()])
            nr_of_trades = tradesAnalyzer.getCount()
            try:
                profitable_tradeprcnt = "%.2f" % (
                    (float(tradesAnalyzer.getProfitableCount()) /
                     float(tradesAnalyzer.getCount())) * 100)
                trade_avg_result_prcnt = "%.2f" % (
                    tradetotal / float(tradesAnalyzer.getCount()))
            except ZeroDivisionError:
                profitable_tradeprcnt = "0.0"
                trade_avg_result_prcnt = "0.0"

            sharpe_ratio = "%.2f" % (sharpeRatioAnalyzer.getSharpeRatio(0.05))

            #print "Cumulative returns: %.2f %%" % (retAnalyzer.getCumulativeReturns()[-1] * 100)

            print "Trade stats"
            print "Nr of trades:\t\t\t%d" % (nr_of_trades)
            print "Trade avg:\t\t\t%s%%" % (trade_avg_result_prcnt)
            print "Profitable trades:\t\t%s%%" % (profitable_tradeprcnt)
            print "Sharpe ratio:\t\t\t", sharpe_ratio
            print
            returns = tradesAnalyzer.getAllReturns()

            if tradesAnalyzer.getProfitableCount() > 0:
                trade_max = "%.2f" % (returns.max() * 100)
                trade_min = "%.2f" % (returns.min() * 100)
                trade_stddev = "%.2f" % (returns.std() * 100)
            else:
                trade_max = "%.2f" % 0
                trade_min = "%.2f" % 0
                trade_stddev = "%.2f" % 0

            print "Returns std. dev.: %s %%\t\t\t" % trade_stddev
            print "Max. return: %s %%\t\t\t" % trade_max
            print "Min. return: %s %%\t\t\t" % trade_min
            #print "Trade total:	    %.2f" % ( tradetotal )
            #print "Max. drawdown: %.2f %%" % (drawDownAnalyzer.getMaxDrawDown() * 100)

            #if tradesAnalyzer.getProfitableCount() > 0:
            #profits = tradesAnalyzer.getProfits()
            #losses = tradesAnalyzer.getLosses()
            #print "Avg. profit: $%2.f" % (profits.mean())
            #print "Avg. loss: $%2.f" % (losses.mean())

            #returns = tradesAnalyzer.getPositiveReturns()
            #returns = tradesAnalyzer.getAllReturns()
            #print "Avg. return: %2.f %%" % (returns.mean() * 100) # too much rounding
            #print "Returns std. dev.: %2.f %%" % (returns.std() * 100)
            #print "Max. return: %2.f %%" % (returns.max() * 100)
            #print "Min. return: %2.f %%" % (returns.min() * 100)

            #print "Trades std. dev.: $%2.f" % (profits.std())
            #print "Max. profit: $%2.f" % (profits.max())
            #print "Min. profit: $%2.f" % (profits.min())

            if paramsstring in resultsdict.keys():
                try:
                    resultsdict[paramsstring]['nr_of_trades'] = int(
                        resultsdict[paramsstring]['nr_of_trades']) + int(
                            nr_of_trades)
                    resultsdict[paramsstring][
                        'profitable_tradeprcnt'] = "%.2f" % (
                            (float(resultsdict[paramsstring]
                                   ['profitable_tradeprcnt']) +
                             float(profitable_tradeprcnt)) / 2.00)
                    resultsdict[paramsstring][
                        'trade_avg_result_prcnt'] = "%.2f" % (
                            (float(resultsdict[paramsstring]
                                   ['trade_avg_result_prcnt']) +
                             float(trade_avg_result_prcnt)) / 2.00)
                    resultsdict[paramsstring]['sharpe_ratio'] = "%.2f" % (
                        (float(resultsdict[paramsstring]['sharpe_ratio']) +
                         float(sharpe_ratio)) / 2.00)
                    resultsdict[paramsstring]['trade_max'] = "%.2f" % (
                        float(resultsdict[paramsstring]['trade_max']) +
                        float(trade_max) / 2.00)
                    resultsdict[paramsstring]['trade_min'] = "%.2f" % (
                        float(resultsdict[paramsstring]['trade_min']) +
                        float(trade_min) / 2.00)
                    resultsdict[paramsstring]['trade_stddev'] = "%.2f" % (
                        float(resultsdict[paramsstring]['trade_stddev']) +
                        float(trade_stddev) / 2.00)
                except ZeroDivisionError:
                    print "\nError (ZeroDivisionError) trying averaging with: %s\n" % paramsstring
            else:  # First time with params
                resultsdict[paramsstring] = dict(paramsarray)
                resultsdict[paramsstring]['params'] = paramsstring
                resultsdict[paramsstring]['nr_of_trades'] = nr_of_trades
                resultsdict[paramsstring][
                    'profitable_tradeprcnt'] = profitable_tradeprcnt
                resultsdict[paramsstring][
                    'trade_avg_result_prcnt'] = trade_avg_result_prcnt
                resultsdict[paramsstring]['sharpe_ratio'] = sharpe_ratio
                resultsdict[paramsstring]['trade_max'] = trade_max
                resultsdict[paramsstring]['trade_min'] = trade_min
                resultsdict[paramsstring]['trade_stddev'] = trade_stddev

            feed.reset()  # feed must be reset

            del sharpeRatioAnalyzer
            del tradesAnalyzer

    with open(filedir + "/" + strat.STRATNAME + '.csv', 'wb') as csvfile:
        fieldnames = ['params']
        fieldnames.extend(paramnames)
        fieldnames.extend(
            ('nr_of_trades', 'profitable_tradeprcnt', 'trade_avg_result_prcnt',
             'sharpe_ratio', 'trade_max', 'trade_min', 'trade_stddev'))

        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
        #csvheader = {'params':'Params: ' + strat.STRATNAME, paramnames, 'nr_of_trades':'Nr of trades',\
        #        'profitable_tradeprcnt':'Profitable trades%', 'trade_avg_result_prcnt':'Trade avg %', 'sharpe_ratio': 'Sharpe Ratio'}
        csvheader = {'params': 'Params: ' + strat.STRATNAME}
        for n in paramnames:
            csvheader[n] = n
        csvheader['nr_of_trades'] = 'Nr of trades'
        csvheader['profitable_tradeprcnt'] = 'Profitable trades%'
        csvheader['trade_avg_result_prcnt'] = 'Trade avg %'
        csvheader['sharpe_ratio'] = 'Sharpe Ratio'
        csvheader['trade_max'] = 'Trade Max'
        csvheader['trade_min'] = 'Trade Min'
        csvheader['trade_stddev'] = 'Trade Stddev'
        writer.writerow(csvheader)
        for result in resultsdict.keys():
            writer.writerow(resultsdict[result])
コード例 #7
0
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()))
    returns = tradesAnalyzer.getAllReturns()
    print("Avg. return: %2.f %%" % (returns.mean() * 100))
    print("Returns std. dev.: %2.f %%" % (returns.std() * 100))
    print("Max. return: %2.f %%" % (returns.max() * 100))
    print("Min. return: %2.f %%" % (returns.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()))
    returns = tradesAnalyzer.getPositiveReturns()
    print("Avg. return: %2.f %%" % (returns.mean() * 100))
    print("Returns std. dev.: %2.f %%" % (returns.std() * 100))
    print("Max. return: %2.f %%" % (returns.max() * 100))
    print("Min. return: %2.f %%" % (returns.min() * 100))
コード例 #8
0
ファイル: plot.py プロジェクト: TimonPeng/pi314
    myStrategy.info("Max. drawdown: %.2f %%" % (drawDownAnalyzer.getMaxDrawDown() * 100))
    myStrategy.info("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())
        returns = tradesAnalyzer.getAllReturns()
        print "Avg. return: %2.f %%" % (returns.mean() * 100)
        print "Returns std. dev.: %2.f %%" % (returns.std() * 100)
        print "Max. return: %2.f %%" % (returns.max() * 100)
        print "Min. return: %2.f %%" % (returns.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())
        returns = tradesAnalyzer.getPositiveReturns()
        print "Avg. return: %2.f %%" % (returns.mean() * 100)
        print "Returns std. dev.: %2.f %%" % (returns.std() * 100)
        print "Max. return: %2.f %%" % (returns.max() * 100)
        print "Min. return: %2.f %%" % (returns.min() * 100)
    
コード例 #9
0
def run_strategy(smaPeriod):
    # Load the yahoo feed from the CSV file
    feed = yahoofeed.Feed()
    feed.addBarsFromCSV("zggf", "E:/PythonData/CSV/000938.csv")

    # Evaluate the strategy with the feed.
    myStrategy = MyStrategy(feed, "zggf", smaPeriod)
    # Attach different analyzers to a strategy before executing it.
    returnsAnalyzer = returns.Returns()
    myStrategy.attachAnalyzer(returnsAnalyzer)
    sharpeRatioAnalyzer = sharpe.SharpeRatio()
    myStrategy.attachAnalyzer(sharpeRatioAnalyzer)
    drawDownAnalyzer = drawdown.DrawDown()
    myStrategy.attachAnalyzer(drawDownAnalyzer)
    tradesAnalyzer = trades.Trades()
    myStrategy.attachAnalyzer(tradesAnalyzer)
    myStrategy.run()
    print("Final portfolio value: $%.2f" % myStrategy.getResult())
    print("Cumulative returns: %.2f %%" %
          (returnsAnalyzer.getCumulativeReturns()[-1] * 100))
    print(returnsAnalyzer.getCumulativeReturns())
    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()))
        returns = tradesAnalyzer.getAllReturns()
        print("Avg. return: %2.f %%" % (returns.mean() * 100))
        print("Returns std. dev.: %2.f %%" % (returns.std() * 100))
        print("Max. return: %2.f %%" % (returns.max() * 100))
        print("Min. return: %2.f %%" % (returns.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()))
        returns = tradesAnalyzer.getPositiveReturns()
        print("Avg. return: %2.f %%" % (returns.mean() * 100))
        print("Returns std. dev.: %2.f %%" % (returns.std() * 100))
        print("Max. return: %2.f %%" % (returns.max() * 100))
        print("Min. return: %2.f %%" % (returns.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()))
        returns = tradesAnalyzer.getNegativeReturns()
        print("Avg. return: %2.f %%" % (returns.mean() * 100))
        print("Returns std. dev.: %2.f %%" % (returns.std() * 100))
        print("Max. return: %2.f %%" % (returns.max() * 100))
        print("Min. return: %2.f %%" % (returns.min() * 100))
コード例 #10
0
def setup_strategy(files, name, show_plot=False):
    #from pyalgotrade.feed import csvfeed, yahoofeed

    # Load the bar feed from the CSV file
    #feed = csvfeed.GenericBarFeed(frequency=Frequency.DAY)
    feed = yahoofeed.Feed(Frequency.DAY)
    #feed = csvfeed.Feed("Date", "%Y-%m-%d")

    for sym, filename in files:
        #print('loading', sym, filename)
        if 'predictions' not in filename:
            feed.addBarsFromCSV(sym, filename)
        else:
            feed.addBarsFromCSV('states', filename)

    instrument_1 = files[0][0]
    instrument_2 = files[1][0]
    instrument_3 = files[2][0]
    states_instrument = 'states'

    #print('got these instruments', instrument_1, instrument_2, instrument_3, states_instrument)
    #input()
    #print(files)
    # Evaluate the strategy with the feed.
    myStrategy = AccuracyStrat(feed, instrument_1, instrument_2, instrument_3,
                               states_instrument)

    from pyalgotrade.stratanalyzer import returns
    # Attach different analyzers to a strategy before executing it.
    retAnalyzer = returns.Returns()
    myStrategy.attachAnalyzer(retAnalyzer)
    sharpeRatioAnalyzer = sharpe.SharpeRatio()
    myStrategy.attachAnalyzer(sharpeRatioAnalyzer)
    drawDownAnalyzer = drawdown.DrawDown()
    myStrategy.attachAnalyzer(drawDownAnalyzer)
    tradesAnalyzer = trades.Trades()
    myStrategy.attachAnalyzer(tradesAnalyzer)

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

    # Include the SMA in the instrument's subplot to get it displayed along with the closing prices.
    #plt.getInstrumentSubplot("orcl").addDataSeries("SMA", myStrategy.getSMA())
    # Plot the simple returns on each bar.
    plt.getOrCreateSubplot("returns").addDataSeries("Simple returns",
                                                    retAnalyzer.getReturns())

    #

    # Run the strategy.
    myStrategy.run()

    if show_plot:
        plt.plot()
    fig = matplotlib.pyplot.gcf()
    fig.set_size_inches(10, 5)

    cum_returns = retAnalyzer.getCumulativeReturns()[-1] * 100
    sharpe_ratio = sharpeRatioAnalyzer.getSharpeRatio(0.05)
    results = {}
    results['final_value'] = myStrategy.getResult()
    results['cum_returns'] = cum_returns
    results['sharpe_ratio'] = sharpe_ratio
    if not show_plot and sharpe_ratio > 1 and cum_returns > 200:
        plt.savePlot('./backtest_plots/%s_%s.png' %
                     (str(int(results['cum_returns'])), name))

    del plt

    results['max_drawdown_%'] = drawDownAnalyzer.getMaxDrawDown() * 100
    results['longest_drawdown'] = str(
        drawDownAnalyzer.getLongestDrawDownDuration())

    results['total_trades'] = tradesAnalyzer.getCount()
    results['profitable_trades'] = tradesAnalyzer.getProfitableCount()

    try:
        results['win_rate'] = tradesAnalyzer.getProfitableCount(
        ) / tradesAnalyzer.getCount()

        profits = tradesAnalyzer.getAll()
        results['avg_profit_$'] = profits.mean()
        results['std_profit_$'] = profits.std()
        results['max_profit_$'] = profits.max()
        results['min_profit_$'] = profits.min()

        returns = tradesAnalyzer.getAllReturns()
        results['avg_profit_%'] = returns.mean() * 100
        results['std_profit_%'] = returns.std() * 100
        results['max_profit_%'] = returns.max() * 100
        results['min_profit_%'] = returns.min() * 100

        for sym, filename in files:
            os.remove(filename)

    except Exception as e:
        #print('backtest exception', e)
        pass
    results = pd.DataFrame.from_dict(results, orient='index')
    #print(results)

    return results
コード例 #11
0
def rsi2Trade(plot, storage, instrument, entrySMA, exitSMA, rsiPeriod,
              overBoughtThreshold, overSoldThreshold):
    # Download the bars.
    feed = yahoofinance.build_feed([instrument], 2015, 2017, storage)
    tm_hour = int(time.strftime('%H', time.localtime()))
    weekdayNumber = datetime.datetime.today().weekday()
    if (weekdayNumber >= 0 and weekdayNumber <= 4) and (tm_hour >= 9
                                                        and tm_hour <= 23):
        feed.addBarsFromCSV(
            instrument,
            sinafinance.download_current_trade(instrument, storage))

    strat = rsi2d.RSI2(feed, instrument, entrySMA, exitSMA, rsiPeriod,
                       overBoughtThreshold, overSoldThreshold)

    strat.attachAnalyzer(retAnalyzer)
    sharpeRatioAnalyzer = sharpe.SharpeRatio()
    strat.attachAnalyzer(sharpeRatioAnalyzer)
    drawDownAnalyzer = drawdown.DrawDown()
    strat.attachAnalyzer(drawDownAnalyzer)
    tradesAnalyzer = trades.Trades()
    strat.attachAnalyzer(tradesAnalyzer)

    if plot:
        plt = plotter.StrategyPlotter(strat, True, False, True)
        plt.getInstrumentSubplot(instrument).addDataSeries(
            "Entry SMA", strat.getEntrySMA())
        plt.getInstrumentSubplot(instrument).addDataSeries(
            "Exit SMA", strat.getExitSMA())
        plt.getOrCreateSubplot("rsi").addDataSeries("RSI", strat.getRSI())
        plt.getOrCreateSubplot("rsi").addLine("Overbought",
                                              overBoughtThreshold)
        plt.getOrCreateSubplot("rsi").addLine("Oversold", overSoldThreshold)

    strat.run()

    print "Correct Ratio: %.2f" % (
        (float(tradesAnalyzer.getProfitableCount()) /
         tradesAnalyzer.getCount()) if tradesAnalyzer.getCount() else -1.0)
    print "Evaluation Final portfolio value: %.2f" % strat.getResult()
    print "Evaluation Cumulative returns: %.2f" % (
        retAnalyzer.getCumulativeReturns()[-1] * 100)
    print "Evaluation Sharpe ratio: %.2f" % (
        sharpeRatioAnalyzer.getSharpeRatio(0.05))
    print "Evaluation Max. drawdown: %.2f" % (
        drawDownAnalyzer.getMaxDrawDown() * 100)
    print "Evaluation Longest drawdown duration: %s" % (
        drawDownAnalyzer.getLongestDrawDownDuration())

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

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

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

    if plot:
        plt.plot()
コード例 #12
0
ファイル: untitled1.py プロジェクト: nightrose79/try
def Function_form(bBandsPeriod,
                  smaPeriod_short,
                  smaPeriod_long,
                  slopePeriod,
                  plot=False):
    from pyalgotrade.stratanalyzer import returns
    from pyalgotrade.stratanalyzer import sharpe
    from pyalgotrade.stratanalyzer import drawdown
    from pyalgotrade.stratanalyzer import trades

    from pyalgotrade import strategy
    from pyalgotrade.strategy import position
    from pyalgotrade import plotter
    from pyalgotrade.tools import yahoofinance
    from pyalgotrade.barfeed import yahoofeed
    from pyalgotrade.technical import bollinger
    from pyalgotrade.stratanalyzer import sharpe
    import BBands_mod
    #import report
    import matplotlib.pyplot as plt

    # Load the yahoo feed from the CSV file
    feed = yahoofeed.Feed()
    feed.addBarsFromCSV("orcl", "data_daily.csv")

    #def main(plot):
    instrument = "orcl"

    # Evaluate the strategy with the feed's bars.
    myStrategy = BBands_mod.BBands(feed, instrument, bBandsPeriod,
                                   smaPeriod_short, smaPeriod_long,
                                   slopePeriod)

    if plot:
        plt = plotter.StrategyPlotter(myStrategy, True, True, True)
        plt.getInstrumentSubplot(instrument).addDataSeries(
            "upper",
            myStrategy.getBollingerBands().getUpperBand())
        plt.getInstrumentSubplot(instrument).addDataSeries(
            "middle",
            myStrategy.getBollingerBands().getMiddleBand())
        plt.getInstrumentSubplot(instrument).addDataSeries(
            "lower",
            myStrategy.getBollingerBands().getLowerBand())

    # Attach different analyzers to a strategy before executing it.
    retAnalyzer = returns.Returns()
    myStrategy.attachAnalyzer(retAnalyzer)
    sharpeRatioAnalyzer = sharpe.SharpeRatio()
    myStrategy.attachAnalyzer(sharpeRatioAnalyzer)
    drawDownAnalyzer = drawdown.DrawDown()
    myStrategy.attachAnalyzer(drawDownAnalyzer)
    tradesAnalyzer = trades.Trades()
    myStrategy.attachAnalyzer(tradesAnalyzer)

    # Run the strategy.
    myStrategy.run()

    print "Final portfolio value: $%.2f" % myStrategy.getResult()
    print "Cumulative returns: %.2f %%" % (
        retAnalyzer.getCumulativeReturns()[-1] * 100)
    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())
        returns = tradesAnalyzer.getAllReturns()
        print "Avg. return: %2.f %%" % (returns.mean() * 100)
        print "Returns std. dev.: %2.f %%" % (returns.std() * 100)
        print "Max. return: %2.f %%" % (returns.max() * 100)
        print "Min. return: %2.f %%" % (returns.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())
        returns = tradesAnalyzer.getPositiveReturns()
        print "Avg. return: %2.f %%" % (returns.mean() * 100)
        print "Returns std. dev.: %2.f %%" % (returns.std() * 100)
        print "Max. return: %2.f %%" % (returns.max() * 100)
        print "Min. return: %2.f %%" % (returns.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())
        returns = tradesAnalyzer.getNegativeReturns()
        print "Avg. return: %2.f %%" % (returns.mean() * 100)
        print "Returns std. dev.: %2.f %%" % (returns.std() * 100)
        print "Max. return: %2.f %%" % (returns.max() * 100)
        print "Min. return: %2.f %%" % (returns.min() * 100)

    if plot:
        plt.plot()
    return (myStrategy.getResult(),
            retAnalyzer.getCumulativeReturns()[-1] * 100,
            sharpeRatioAnalyzer.getSharpeRatio(0.05),
            drawDownAnalyzer.getMaxDrawDown() * 100)