Пример #1
0
    def testInvalidDates(self):
        instrument = "orcl"

        # Don't skip errors.
        with self.assertRaisesRegexp(Exception, "HTTP Error 404: Not Found"):
            with common.TmpDir() as tmpPath:
                bf = yahoofinance.build_feed([instrument], 2100, 2101, storage=tmpPath, frequency=bar.Frequency.DAY)

        # Skip errors.
        with common.TmpDir() as tmpPath:
            bf = yahoofinance.build_feed(
                [instrument], 2100, 2101, storage=tmpPath, frequency=bar.Frequency.DAY, skipErrors=True
            )
            bf.loadAll()
            self.assertNotIn(instrument, bf)
Пример #2
0
def main(plot):
    initialCash = 10000
    instrumentsByClass = {
        "Technology": ["MSFT", "ORCL", "IBM", "HPQ"],
        "Services": ["WMT", "UPS", "TGT", "CCL"],
        "Basic Materials": ["XOM", "CVX", "COP", "OXY"],
        "Financial": ["BAC", "JPM", "WFC", "GS"],
        "Consumer Goods": ["PG", "PEP", "CL", "KO"],
    }

    # Download the bars.
    instruments = []
    for assetClass in instrumentsByClass:
        instruments.extend(instrumentsByClass[assetClass])
    feed = yahoofinance.build_feed(instruments, 2005, 2013, "data", skipErrors=True)

    strat = MarketTiming(feed, instrumentsByClass, initialCash)
    sharpeRatioAnalyzer = sharpe.SharpeRatio()
    strat.attachAnalyzer(sharpeRatioAnalyzer)

    if plot:
        plt = plotter.StrategyPlotter(strat, False, False, True)
        plt.getOrCreateSubplot("cash").addCallback("Cash", lambda x: strat.getBroker().getCash())

    strat.run()
    print "Sharpe ratio: %.2f" % sharpeRatioAnalyzer.getSharpeRatio(0.05)

    if plot:
        plt.plot()
Пример #3
0
def main2(plot, instrument, entry_sma_period, exit_sma_period):
    # Download the bars.
    feed = yahoofinance.build_feed([instrument], 2014, 2014, ".")
    
    # Evaluate the strategy with the feed's bars.
    strat = SMACrossOver2(feed, instrument, entry_sma_period, exit_sma_period)
    
    # Attach a returns analyzers to the strategy.
    returnsAnalyzer = returns.Returns()
    strat.attachAnalyzer(returnsAnalyzer)
    
    # Attach the plotter to the strategy.
    plt = plotter.StrategyPlotter(strat)
    # Include the SMA in the instrument's subplot to get it displayed along with the closing prices.
    plt.getInstrumentSubplot(instrument).addDataSeries("SMA", strat.getSMA())
    plt.getInstrumentSubplot(instrument).addDataSeries("exit SMA", strat.get_exit_SMA())
    # Plot the simple returns on each bar.
    plt.getOrCreateSubplot("returns").addDataSeries("Simple returns", returnsAnalyzer.getReturns())
    
    # Run the strategy.
    strat.run()
    strat.info("Final portfolio value: $%.2f" % strat.getResult())
    
    # Plot the strategy.
    plt.plot()
Пример #4
0
def main(plot):
    use_ex = True

    instrument = "tcehy"
    feed = yahoofinance.build_feed([instrument], 2015, 2016, ".")

    if (use_ex):
        strat = SMACrossOverEx(feed, instrument)
    else:
        strat = SMACrossOver(feed, instrument, 15)
    sharpeRatioAnalyzer = sharpe.SharpeRatio()
    strat.attachAnalyzer(sharpeRatioAnalyzer)

    # Attach a returns analyzers to the strategy.
    returnsAnalyzer = returns.Returns()
    strat.attachAnalyzer(returnsAnalyzer)

    if plot:
        plt = plotter.StrategyPlotter(strat, True, False, True)
        if (use_ex):
            plt.getInstrumentSubplot(instrument).addDataSeries("sma-15", strat.getSMA(15))
            plt.getInstrumentSubplot(instrument).addDataSeries("sma-30", strat.getSMA(30))
        else:
            plt.getInstrumentSubplot(instrument).addDataSeries("sma", strat.getSMA())

        # Plot the simple returns on each bar.
        plt.getOrCreateSubplot("returns").addDataSeries("Simple returns", returnsAnalyzer.getReturns())

    strat.run()
    strat.info("Final portfolio value: $%.2f" % strat.getResult())

    print "Sharpe ratio: %.2f" % sharpeRatioAnalyzer.getSharpeRatio(0.05)

    if plot:
        plt.plot()
Пример #5
0
def main(plot):
    al1 = Analyst('Ivy Kang')
    al1.assign_weight('cmg', 0.673)
    al1.assign_weight('aapl', 0.215)

    al2 = Analyst('Charlie Brown')
    al2.assign_weight('cmg', 0.420)
    al2.assign_weight('orcl', 0.130)
    al2.assign_weight('bk', 0.32)
    al2.assign_weight('bk', 0.40)
    al2.assign_weight('cmg', 0.30)

    org = Organization()
    org.add_analyst(al1)
    org.add_analyst(al2)

    # Download the bars.
    feed = yahoofinance.build_feed(org.get_weights().keys(), 2014, 2015, ".instr_data")

    strat = OrgStrat(feed, org)
    sharpeRatioAnalyzer = sharpe.SharpeRatio()
    strat.attachAnalyzer(sharpeRatioAnalyzer)

    if plot:
        plt = plotter.StrategyPlotter(strat, True, False, True)

    strat.run()

    if plot:
        plt.plot()
Пример #6
0
def pickAsFunToLoop2(instrument):

    #code = pickle.load(open(r'C:\Users\pmhgms\Desktop\machine_leaning\DataSet\stock_code.pickle','rb'))
    #instrument = code[randint(0, len(code))]
    # Load the yahoo feed from the CSV file
    instruments = [instrument]
    sy, ey = 2000, 2015
    smaPeriod = 60
    feed = yahoofinance.build_feed(instruments, sy, ey, "yhfeed", skipErrors=True)
    
    # Evaluate the strategy with the feed's bars.
    myStrategy = tut.SMACrossOver(feed, instrument, smaPeriod)
    
    # Attach a returns analyzers to the strategy.
    returnsAnalyzer = returns.Returns()
    myStrategy.attachAnalyzer(returnsAnalyzer)
    sharpeRatioAnalyzer = sharpe.SharpeRatio()
    myStrategy.attachAnalyzer(sharpeRatioAnalyzer)
    # 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(instrument).addDataSeries("sma", myStrategy.getSMA())
    # Plot the simple returns on each bar.
    #plt.getOrCreateSubplot("returns").addDataSeries("Simple returns", returnsAnalyzer.getReturns())
    
    # Run the strategy.
    myStrategy.run()
    myStrategy.info("Final portfolio value: $%.2f" % (myStrategy.getResult()))
    
    # Plot the strategy.
    directory = 'smajpg'
    picname = instrument+'_From_'+str(sy)+'_To_'+str(ey)+'_smaPeriod_'+str(smaPeriod)+'.jpg'
    path = os.path.join(directory, picname)
    plt.plot(savefige=True, path=path)
Пример #7
0
def pickAsFunToLoop(instrument,usevir=0):

    #code = pickle.load(open(r'C:\Users\pmhgms\Desktop\machine_leaning\DataSet\stock_code.pickle','rb'))
    #instrument = code[randint(0, len(code))]
    # Load the yahoo feed from the CSV file
    instruments = [instrument]
    sy, ey = 2000, 2015
    p1, p2 = 20, 10
    usevir = usevir
    feed = yahoofinance.build_feed(instruments, sy, ey, "yhfeed", skipErrors=True)
    
    # Evaluate the strategy with the feed's bars.
    myStrategy = tut.MyStrategy(feed, instrument, p1, p1, usevir)
    
    # Attach a returns analyzers to the strategy.
    returnsAnalyzer = returns.Returns()
    myStrategy.attachAnalyzer(returnsAnalyzer)
    
    # 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(instrument).addDataSeries("high", myStrategy.getHigh())
    plt.getInstrumentSubplot(instrument).addDataSeries("low", myStrategy.getLow())
    # Plot the simple returns on each bar.
    #plt.getOrCreateSubplot("returns").addDataSeries("Simple returns", returnsAnalyzer.getReturns())
    
    # Run the strategy.
    myStrategy.run()
    myStrategy.info("Final portfolio value: $%.2f, Stop loss %d time, Skip buy %d time" % (myStrategy.getResult(), myStrategy.stoplosstimes, myStrategy.skipbuy))
    
    # Plot the strategy.
    directory = 'temjpg'
    picname = instrument+'_From_'+str(sy)+'_To_'+str(ey)+'_p1_'+str(p1)+'_p2_'+str(p2)+'_usevir_'+str(usevir)+'.jpg'
    path = os.path.join(directory, picname)
    plt.plot(savefige=True, path=path)
Пример #8
0
def algoparser(**kwargs):
    """
    编译用户代码
    :param args:
    :param kwargs:
              sid: 资产ID
              start: 策略开始时间
              end: 策略结束时间
              code: 用户策略代码(字符串)
              filename: 用户策略文件名(.py)
    :return:
    """
    sid = kwargs.pop('sid', None)
    start = kwargs.pop('start', None)
    end = kwargs.pop('end', None)
    code = kwargs.pop('code',None)

    Algo = compile(code, '<string>', 'exec')
    exec Algo

    instrument = sid
    feed = yahoofinance.build_feed([instrument], start, end, ".")

    strat = Strategy(feed, instrument)

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

    plt = plotter.StrategyPlotter(strat,True,False,False)
    strat.run()
    stat = plt.plotjson()
    print stat
    return stat
Пример #9
0
def main(plot):
    initialCash = 1000000
    commodity_tickers=["B","TA","BR"]
    instrumentsByClass = {
        "commodity": commodity_tickers
    }

    # Download the bars.
    instruments = []
    for assetClass in instrumentsByClass:
        instruments.extend(instrumentsByClass[assetClass])
    feed = yahoofinance.build_feed(instruments, 2007, 2013, "data", skipErrors=True)

    strat = MarketTiming(feed, instrumentsByClass, initialCash)
    sharpeRatioAnalyzer = sharpe.SharpeRatio()
    strat.attachAnalyzer(sharpeRatioAnalyzer)
    returnsAnalyzer = returns.Returns()
    strat.attachAnalyzer(returnsAnalyzer)

    if plot:
        plt = plotter.StrategyPlotter(strat, False, False, True)
        plt.getOrCreateSubplot("cash").addCallback("Cash", lambda x: strat.getBroker().getCash())
        # Plot strategy vs. SPY cumulative returns.
        plt.getOrCreateSubplot("returns").addDataSeries("SPY", cumret.CumulativeReturn(feed["SPY"].getPriceDataSeries()))
        plt.getOrCreateSubplot("returns").addDataSeries("Strategy", returnsAnalyzer.getCumulativeReturns())

    strat.run()
    print "Sharpe ratio: %.2f" % sharpeRatioAnalyzer.getSharpeRatio(0.05)
    print "Returns: %.2f %%" % (returnsAnalyzer.getCumulativeReturns()[-1] * 100)

    if plot:
        plt.plot()
Пример #10
0
def main(plot):
    instrument = "000300.ss"
    feed = yahoofinance.build_feed([instrument], 2013, 2015, ".")

    period = 100
    strat = HurstBasedStrategy(feed, instrument, period)

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

    # Attach a returns analyzers to the strategy.
    returnsAnalyzer = returns.Returns()
    strat.attachAnalyzer(returnsAnalyzer)

    if plot:
        plt = plotter.StrategyPlotter(strat, True, False, True)

        plt.getOrCreateSubplot("hurst").addDataSeries("Hurst",  strat.getHurst())
        plt.getOrCreateSubplot("hurst").addLine("random", 0.5)

        # Plot the simple returns on each bar.
        # plt.getOrCreateSubplot("returns").addDataSeries("Simple returns", returnsAnalyzer.getReturns())

    strat.run()
    strat.info("Final portfolio value: $%.2f" % strat.getResult())

    # print "Sharpe ratio: %.2f" % sharpeRatioAnalyzer.getSharpeRatio(0.05)

    if plot:
        plt.plot()
Пример #11
0
def main(plot):
    initialCash = 10000
    instrumentsByClass = {
        "US Stocks": ["VTI"],
        "Foreign Stocks": ["VEU"],
        "US 10 Year Government Bonds": ["IEF"],
        "Real Estate": ["VNQ"],
        "Commodities": ["DBC"],
    }

    # Download the bars.
    instruments = ["SPY"]
    for assetClass in instrumentsByClass:
        instruments.extend(instrumentsByClass[assetClass])
    feed = yahoofinance.build_feed(instruments, 2007, 2013, "data", skipErrors=True)

    strat = MarketTiming(feed, instrumentsByClass, initialCash)
    sharpeRatioAnalyzer = sharpe.SharpeRatio()
    strat.attachAnalyzer(sharpeRatioAnalyzer)
    returnsAnalyzer = returns.Returns()
    strat.attachAnalyzer(returnsAnalyzer)

    if plot:
        plt = plotter.StrategyPlotter(strat, False, False, True)
        plt.getOrCreateSubplot("cash").addCallback("Cash", lambda x: strat.getBroker().getCash())
        # Plot strategy vs. SPY cumulative returns.
        plt.getOrCreateSubplot("returns").addDataSeries("SPY", cumret.CumulativeReturn(feed["SPY"].getPriceDataSeries()))
        plt.getOrCreateSubplot("returns").addDataSeries("Strategy", returnsAnalyzer.getCumulativeReturns())

    strat.run()
    print "Sharpe ratio: %.2f" % sharpeRatioAnalyzer.getSharpeRatio(0.05)
    print "Returns: %.2f %%" % (returnsAnalyzer.getCumulativeReturns()[-1] * 100)

    if plot:
        plt.plot()
Пример #12
0
 def testBuildDailyFeed(self):
     with common.TmpDir() as tmpPath:
         instrument = "orcl"
         bf = yahoofinance.build_feed([instrument], 2010, 2010, storage=tmpPath)
         bf.loadAll()
         self.assertEqual(bf[instrument][-1].getOpen(), 31.22)
         self.assertEqual(bf[instrument][-1].getClose(), 31.30)
Пример #13
0
def main(plot, instruments, smaPeriod, cash):

    # Download the bars.
    # In the instruments,I can provide more instruments.The instruments name can be got from yahoo finance.
    #instruments = ["c07.si","C09.SI","C31.SI","E5H.SI"]
    #instruments = ["h78.si"]
    #feed is a Feed type defined in yahoofeed.py
    feed = yahoofinance.build_feed(instruments, 2008, 2009, "./Historical_Price")

    for instrument in instruments:
        myStrategy = MyStrategy(feed, instrument, smaPeriod, cash)

        if plot == True :
            # Attach a returns analyzers to the strategy.
            returnsAnalyzer = returns.Returns()
            myStrategy.attachAnalyzer(returnsAnalyzer)

            # 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(instrument).addDataSeries("SMA", myStrategy.getSMA())
            # Plot adjusted close values instead of regular close.
            plt.getInstrumentSubplot(instrument).setUseAdjClose(True)
            # Plot the strategy returns at each bar.
            #plt.getOrCreateSubplot("returns").addDataSeries("Net return", returnsAnalyzer.getReturns())
            #plt.getOrCreateSubplot("returns").addDataSeries("Cum. return", returnsAnalyzer.getCumulativeReturns())

        myStrategy.run()
        print "Result for %s : %.2f" % (instrument, myStrategy.getResult())

        # Plot the strategy.
        if plot == True :
            plt.plot()
Пример #14
0
def main2(plot):
    instrument = "ivv"
    smaPeriod = 20
    
    # Download the bars.
    feed = yahoofinance.build_feed([instrument], 2013, 2014, ".")
    
    # Evaluate the strategy with the feed's bars.
    myStrategy = SMACrossOver(feed, instrument, smaPeriod)
    
    # Attach a returns analyzers to the strategy.
    returnsAnalyzer = returns.Returns()
    myStrategy.attachAnalyzer(returnsAnalyzer)
    
    # 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(instrument).addDataSeries("SMA", myStrategy.getSMA())
    # Plot the simple returns on each bar.
    plt.getOrCreateSubplot("returns").addDataSeries("Simple returns", returnsAnalyzer.getReturns())
    
    # Run the strategy.
    myStrategy.run()
    myStrategy.info("Final portfolio value: $%.2f" % myStrategy.getResult())
    
    # Plot the strategy.
    plt.plot()    
Пример #15
0
def main(plot):
    instrument = "yhoo"
    bBandsPeriod = 20

    # Download the bars.
    feed = yahoofinance.build_feed([instrument], 2011, 2015, ".")
    # feed = ts.get_hist_data('601198')
    print type(feed)
    # import sys;sys.exit(0)

    strat = BBands(feed, instrument, bBandsPeriod)
    sharpeRatioAnalyzer = sharpe.SharpeRatio()
    strat.attachAnalyzer(sharpeRatioAnalyzer)

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

    strat.run()
    print "Sharpe ratio: %.2f" % sharpeRatioAnalyzer.getSharpeRatio(0.05)

    if plot:
        plt.plot()
Пример #16
0
def main(plot):
    entrySMA = 200
    exitSMA = 5
    rsiPeriod = 2
    overBoughtThreshold = 90
    overSoldThreshold = 10

    # Download the bars.
    instrument = "tcehy"
    feed = yahoofinance.build_feed([instrument], 2014, 2016, ".")

    strat = RSI2(feed, instrument, entrySMA, exitSMA, rsiPeriod, overBoughtThreshold, overSoldThreshold)
    sharpeRatioAnalyzer = sharpe.SharpeRatio()
    strat.attachAnalyzer(sharpeRatioAnalyzer)

    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()
    strat.info("Final portfolio value: $%.2f" % strat.getResult())

    print "Sharpe ratio: %.2f" % sharpeRatioAnalyzer.getSharpeRatio(0.05)

    if plot:
        plt.plot()
Пример #17
0
 def testBuildWeeklyFeed(self):
     with common.TmpDir() as tmpPath:
         instrument = "aapl"
         bf = yahoofinance.build_feed([instrument], 2013, 2013, storage=tmpPath, frequency=bar.Frequency.WEEK)
         bf.loadAll()
         self.assertEqual(round(bf[instrument][-1].getOpen(), 2), 557.46)
         self.assertEqual(round(bf[instrument][-1].getHigh(), 2), 561.28)
         self.assertEqual(round(bf[instrument][-1].getLow(), 2), 540.43)
         self.assertEqual(round(bf[instrument][-1].getClose(), 2), 540.98)
         self.assertTrue(bf[instrument][-1].getVolume() in (9852500, 9855900, 68991600))
Пример #18
0
Файл: test.py Проект: Ronin11/AI
def run_strategy():
	# Load the yahoo feed from the CSV file
	securities = ["app"]
	feed = yahoofinance.build_feed(securities, 2006, 2014, "stockdata")

	# Evaluate the strategy with the feed.
	masterTrader = MasterTrader(feed, securities[0])
	masterTrader.run()
	print "Final portfolio value: $%.2f" % masterTrader.getBroker().getEquity()
	masterTrader.datamanager.close()
	print "Highest portfolio value: $%.2f" % masterTrader.highValue
def acquire_daily_data(instrument, year):
    if year == 'all':
        this_year = date.today().year  # Get current year
        final_year = this_year
        in_business = True
        while in_business:
            try:
                yahoofinance.build_feed(
                    [instrument], this_year, this_year,
                    './data/historical/daily-atrader',
                    frequency=86400, skipErrors=False)
            except:
                in_business = False
                log_business_years(instrument, [this_year + 1, final_year])
            else:
                this_year -= 1
    else:
        yahoofinance.build_feed([instrument], year[0], year[1],
                                './data/historical/daily-atrader',
                                frequency=86400, skipErrors=False)
Пример #20
0
 def __init__(self):
     instruments = get_sp500_2()
     #instruments = ['A', 'AA']
     tmp_dir = "/home/work/workplace/tmp"
     if not os.path.exists(tmp_dir):
         os.mkdir(tmp_dir)
     feed = yahoofinance.build_feed(instruments, 2010,2014,"/home/work/workplace/tmp/")
     strategy.BacktestingStrategy.__init__(self, feed)
     self.__instruments = instruments;
     self.__positions = {}
     for instrument in instruments:
         self.__positions[instrument] = []
Пример #21
0
def main(plot):
    instruments = ["AA", "AES", "AIG"]
    feed = yahoofinance.build_feed(instruments, 2008, 2009, ".")

    predicate = BuyOnGap(feed)
    eventProfiler = eventprofiler.Profiler(predicate, 5, 5)
    eventProfiler.run(feed, True)

    results = eventProfiler.getResults()
    print "%d events found" % (results.getEventCount())
    if plot:
        eventprofiler.plot(results)
Пример #22
0
def main(plot):
    instruments = ["AA", "AES", "AIG"]
    feed = yahoofinance.build_feed(instruments, 2008, 2009, ".")

    predicate = BuyOnGap(feed)
    eventProfiler = eventprofiler.Profiler(predicate, 5, 5)
    eventProfiler.run(feed, True)

    results = eventProfiler.getResults()
    print "%d events found" % (results.getEventCount())
    if plot:
        eventprofiler.plot(results)
Пример #23
0
    def testInvalidDates(self):
        instrument = "orcl"

        # Don't skip errors.
        with self.assertRaisesRegexp(Exception, "404 Client Error: Not Found"):
            with common.TmpDir() as tmpPath:
                bf = yahoofinance.build_feed([instrument],
                                             2100,
                                             2101,
                                             storage=tmpPath,
                                             frequency=bar.Frequency.DAY)

        # Skip errors.
        with common.TmpDir() as tmpPath:
            bf = yahoofinance.build_feed([instrument],
                                         2100,
                                         2101,
                                         storage=tmpPath,
                                         frequency=bar.Frequency.DAY,
                                         skipErrors=True)
            bf.loadAll()
            self.assertNotIn(instrument, bf)
Пример #24
0
 def __init__(self):
     instruments = get_sp500_2()
     #instruments = ['A', 'AA']
     tmp_dir = "/home/work/workplace/tmp"
     if not os.path.exists(tmp_dir):
         os.mkdir(tmp_dir)
     feed = yahoofinance.build_feed(instruments, 2010, 2014,
                                    "/home/work/workplace/tmp/")
     strategy.BacktestingStrategy.__init__(self, feed)
     self.__instruments = instruments
     self.__positions = {}
     for instrument in instruments:
         self.__positions[instrument] = []
def run_strategy(smaPeriod):
    
    instrument = "orcl"
    feed = yahoofinance.build_feed([instrument], 2000, 2000, ".") 
    
    # Load the yahoo feed from the CSV file
    feed = yahoofeed.Feed()
    feed.addBarsFromCSV("orcl", "orcl-2000-yahoofinance.csv")

    # Evaluate the strategy with the feed.
    myStrategy = MyStrategy(feed, "orcl", smaPeriod)
    myStrategy.run()
    print "Final portfolio value: $%.2f" % myStrategy.getBroker().getEquity()
    print "Profit %s Win: %s Loss: %s Win rate: %s%% " % (myStrategy.profit, myStrategy.win, myStrategy.loss, round(decimal.Decimal(myStrategy.win)/(decimal.Decimal(myStrategy.win)+decimal.Decimal(myStrategy.loss))*100,2))    
Пример #26
0
def main(plot):

    smaPeriod = 10
    cash = 20000

    # Download the bars.
    # In the instruments,I can provide more instruments.The instruments name can be got from yahoo finance.
    #instruments = ["c07.si","C09.SI","C31.SI"]
    instruments = ["c09.si"]
    #feed is a Feed type defined in yahoofeed.py
    feed = yahoofinance.build_feed(instruments, 2012, 2013, ".")

    for instrument in instruments:
        myStrategy = MyStrategy(feed, instrument, smaPeriod, cash)
        myStrategy.run()
        print "Result for %s : %.2f" % (instrument, myStrategy.getResult())
Пример #27
0
 def testBuildWeeklyFeed(self):
     with common.TmpDir() as tmpPath:
         instrument = "aapl"
         bf = yahoofinance.build_feed([instrument],
                                      2013,
                                      2013,
                                      storage=tmpPath,
                                      frequency=bar.Frequency.WEEK)
         bf.loadAll()
         self.assertEqual(bf[instrument][-1].getOpen(), 557.46)
         self.assertEqual(bf[instrument][-1].getHigh(), 561.28)
         self.assertEqual(bf[instrument][-1].getLow(), 540.43)
         self.assertEqual(bf[instrument][-1].getClose(), 540.98)
         self.assertTrue(bf[instrument][-1].getVolume() in (9852500,
                                                            9855900,
                                                            68991600))
Пример #28
0
def main(plot, instrument, entry_sma_period, exit_sma_period):
    # Download the bars.
    feed = yahoofinance.build_feed([instrument], 2014, 2014, ".")
    
    strat = SMACrossOver2(feed, instrument, entry_sma_period, exit_sma_period)
    sharpeRatioAnalyzer = sharpe.SharpeRatio()
    strat.attachAnalyzer(sharpeRatioAnalyzer)

    if plot:
        plt = plotter.StrategyPlotter(strat, True, False, True)
        plt.getInstrumentSubplot(instrument).addDataSeries("sma", strat.getSMA())

    strat.run()
    print "Sharpe ratio: %.2f" % sharpeRatioAnalyzer.getSharpeRatio(0.05)

    if plot:
        plt.plot()
Пример #29
0
def run_strategy(smaPeriod, rsiPeriod, instrument, amount, plot):
    # Load the yahoo feed from the CSV file
    try:
        feed = yahoofinance.build_feed([instrument], 2009, 2015, "/home/pwu/stock/database")
    except:
        print "can't download..."
        pass
    else:
    # Evaluate the strategy with the feed's bars.
        myStrategy = MyStrategy(feed, instrument, smaPeriod, rsiPeriod, amount)
        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())
        myStrategy.run()
        if plot:
                plt.plot()
Пример #30
0
def main(plot):
    instrument = "aapl"
    vwapWindowSize = 5

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

    myStrategy = MyStrategy(feed, instrument, vwapWindowSize)

    if plot:
        plt = plotter.StrategyPlotter(myStrategy, True, False, True)
        plt.getInstrumentSubplot(instrument).addDataSeries("vwap", myStrategy.getVWAPDS())

    myStrategy.run()
    print "Result: %.2f" % myStrategy.getResult()

    if plot:
        plt.plot()
Пример #31
0
def main(plot):
    instruments = ["gld", "gdx"]
    windowSize = 50

    # Download the bars.
    feed = yahoofinance.build_feed(instruments, 2006, 2012, ".")

    myStrategy = MyStrategy(feed, instruments[0], instruments[1], windowSize)

    if plot:
        plt = plotter.StrategyPlotter(myStrategy, False, False, True)
        plt.getOrCreateSubplot("hedge").addDataSeries("Hedge Ratio", myStrategy.getHedgeRatioDS())
        plt.getOrCreateSubplot("spread").addDataSeries("Spread", myStrategy.getSpreadDS())

    myStrategy.run()
    print "Result: %.2f" % myStrategy.getResult()

    if plot:
        plt.plot()
Пример #32
0
def main(plot):
    initialCash = 10000
    instrumentsByClass = {
        "US Stocks": ["VTI"],
        "Foreign Stocks": ["VEU"],
        "US 10 Year Government Bonds": ["IEF"],
        "Real Estate": ["VNQ"],
        "Commodities": ["DBC"],
    }

    # Download the bars.
    instruments = ["SPY"]
    for assetClass in instrumentsByClass:
        instruments.extend(instrumentsByClass[assetClass])
    feed = yahoofinance.build_feed(instruments,
                                   2007,
                                   2013,
                                   "data",
                                   skipErrors=True)

    strat = MarketTiming(feed, instrumentsByClass, initialCash)
    sharpeRatioAnalyzer = sharpe.SharpeRatio()
    strat.attachAnalyzer(sharpeRatioAnalyzer)
    returnsAnalyzer = returns.Returns()
    strat.attachAnalyzer(returnsAnalyzer)

    if plot:
        plt = plotter.StrategyPlotter(strat, False, False, True)
        plt.getOrCreateSubplot("cash").addCallback(
            "Cash", lambda x: strat.getBroker().getCash())
        # Plot strategy vs. SPY cumulative returns.
        plt.getOrCreateSubplot("returns").addDataSeries(
            "SPY", cumret.CumulativeReturn(feed["SPY"].getPriceDataSeries()))
        plt.getOrCreateSubplot("returns").addDataSeries(
            "Strategy", returnsAnalyzer.getCumulativeReturns())

    strat.run()
    print "Sharpe ratio: %.2f" % sharpeRatioAnalyzer.getSharpeRatio(0.05)
    print "Returns: %.2f %%" % (returnsAnalyzer.getCumulativeReturns()[-1] *
                                100)

    if plot:
        plt.plot()
Пример #33
0
def main(plot):
    instrument = "aapl"
    vwapWindowSize = 5

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

    myStrategy = MyStrategy(feed, instrument, vwapWindowSize)

    if plot:
        plt = plotter.StrategyPlotter(myStrategy, True, False, True)
        plt.getInstrumentSubplot(instrument).addDataSeries(
            "vwap", myStrategy.getVWAPDS())

    myStrategy.run()
    print "Result: %.2f" % myStrategy.getResult()

    if plot:
        plt.plot()
Пример #34
0
def main(plot):
	instrument = "aapl"
	smaPeriod = 20
	
	feed = yahoofinance.build_feed([instrument],2014,2015,".")
	
	strat = sma_crossover.SMACrossOver(feed, instrument,smaPeriod)
	sharpeRatioAnalyzer = sharpe.SharpeRatio()
	strat.attachAnalyzer(sharpeRatioAnalyzer)
	
	if plot:
		plt = plotter.StrategyPlotter(strat, True, False, True)
		plt.getInstrumentSubplot(instrument).addDataSeries("sma",strat.getSMA())
		
	strat.run()
	print "Sharpe ratio: %.2f" % sharpeRatioAnalyzer.getSharpeRatio(0.05)
	
	if plot:
		plt.plot()
Пример #35
0
def main(plot):
    instrument = "yhoo"
    bBandsPeriod = 40

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

    myStrategy = MyStrategy(feed, instrument, bBandsPeriod)

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

    myStrategy.run()
    print "Result: %.2f" % myStrategy.getResult()

    if plot:
        plt.plot()
Пример #36
0
def main(plot):
    instrument = "aapl"
    smaPeriod = 20

    feed = yahoofinance.build_feed([instrument], 2014, 2015, ".")

    strat = sma_crossover.SMACrossOver(feed, instrument, smaPeriod)
    sharpeRatioAnalyzer = sharpe.SharpeRatio()
    strat.attachAnalyzer(sharpeRatioAnalyzer)

    if plot:
        plt = plotter.StrategyPlotter(strat, True, False, True)
        plt.getInstrumentSubplot(instrument).addDataSeries(
            "sma", strat.getSMA())

    strat.run()
    print "Sharpe ratio: %.2f" % sharpeRatioAnalyzer.getSharpeRatio(0.05)

    if plot:
        plt.plot()
Пример #37
0
def main(plot):
    instrument = "yhoo"
    bBandsPeriod = 40

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

    myStrategy = MyStrategy(feed, instrument, bBandsPeriod)

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

    myStrategy.run()
    print "Result: %.2f" % myStrategy.getResult()

    if plot:
        plt.plot()
Пример #38
0
def main(plot):
    instruments = ["gld", "gdx"]
    windowSize = 50

    # Download the bars.
    feed = yahoofinance.build_feed(instruments, 2006, 2012, ".")

    strat = StatArb(feed, instruments[0], instruments[1], windowSize)
    sharpeRatioAnalyzer = sharpe.SharpeRatio()
    strat.attachAnalyzer(sharpeRatioAnalyzer)

    if plot:
        plt = plotter.StrategyPlotter(strat, False, False, True)
        plt.getOrCreateSubplot("hedge").addDataSeries("Hedge Ratio", strat.getHedgeRatioDS())
        plt.getOrCreateSubplot("spread").addDataSeries("Spread", strat.getSpreadDS())

    strat.run()
    print("Sharpe ratio: %.2f" % sharpeRatioAnalyzer.getSharpeRatio(0.05))

    if plot:
        plt.plot()
Пример #39
0
def main(plot):
    instrument = "aapl"
    vwapWindowSize = 5
    threshold = 0.01

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

    strat = VWAPMomentum(feed, instrument, vwapWindowSize, threshold)
    sharpeRatioAnalyzer = sharpe.SharpeRatio()
    strat.attachAnalyzer(sharpeRatioAnalyzer)

    if plot:
        plt = plotter.StrategyPlotter(strat, True, False, True)
        plt.getInstrumentSubplot(instrument).addDataSeries("vwap", strat.getVWAP())

    strat.run()
    print "Sharpe ratio: %.2f" % sharpeRatioAnalyzer.getSharpeRatio(0.05)

    if plot:
        plt.plot()
Пример #40
0
def main(plot):
    instrument = "yhoo"
    bBandsPeriod = 40

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

    strat = BBands(feed, instrument, bBandsPeriod)
    sharpeRatioAnalyzer = sharpe.SharpeRatio()
    strat.attachAnalyzer(sharpeRatioAnalyzer)

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

    strat.run()
    print(("Sharpe ratio: %.2f" % sharpeRatioAnalyzer.getSharpeRatio(0.05)))

    if plot:
        plt.plot()
Пример #41
0
def main(plot):
    instrument = "aapl"
    vwapWindowSize = 5
    threshold = 0.01

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

    strat = VWAPMomentum(feed, instrument, vwapWindowSize, threshold)
    sharpeRatioAnalyzer = sharpe.SharpeRatio()
    strat.attachAnalyzer(sharpeRatioAnalyzer)

    if plot:
        plt = plotter.StrategyPlotter(strat, True, False, True)
        plt.getInstrumentSubplot(instrument).addDataSeries(
            "vwap", strat.getVWAP())

    strat.run()
    print("Sharpe ratio: %.2f" % sharpeRatioAnalyzer.getSharpeRatio(0.05))

    if plot:
        plt.plot()
Пример #42
0
def main(plot):
    symbol_file = open("TFEX", "r")
    #Read each symbol and remove \n from each symbol
    symbols = [x.strip('\n') for x in symbol_file.readlines()]

    #symbols = ["aot.bk","bbl.bk","tpipl.bk","ichi.bk"]
    bBandsPeriod = 21

    f = open("bbands_result.txt", "w")
    # Download the bars.
    for instrument in symbols:
        instrument = instrument + ".BK"
        feed = yahoofinance.build_feed([instrument], 2015, 2016, ".")

        strat = BBands(feed, instrument, bBandsPeriod)
        sharpeRatioAnalyzer = sharpe.SharpeRatio()
        strat.attachAnalyzer(sharpeRatioAnalyzer)

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

        strat.run()
        print "%s" % instrument
        print "Sharpe ratio: %.2f" % sharpeRatioAnalyzer.getSharpeRatio(0.03)
        f.write("%s\n" % instrument)
        f.write("Sharpe ratio: %.2f\n" %
                sharpeRatioAnalyzer.getSharpeRatio(0.03))
        if plot:
            plt.plot()
Пример #43
0
from pyalgotrade.optimizer import server
import sys, os
from pyalgotrade.barfeed import yahoofeed
from pyalgotrade.technical import ma
from pyalgotrade.tools import yahoofinance


def parameters_generator():
    entrySMA = range(251, 281)
    exitSMA = range(11, 21)
    rsiPeriod = range(10, 14)
    overBoughtThreshold = range(75, 90)
    overSoldThreshold = range(5, 21)
    return itertools.product(entrySMA, exitSMA, rsiPeriod, overBoughtThreshold,
                             overSoldThreshold)


# The if __name__ == '__main__' part is necessary if running on Windows.
if __name__ == '__main__':
    # Load the feed from the CSV files.
    #feed = yahoofeed.Feed()
    instrument = sys.argv[1]
    os.system("rm -rf %s-*" % (instrument))
    feed = yahoofinance.build_feed([instrument], 2011, 2014, "./database")
    #feed.addBarsFromCSV(instrument, "%s-2011-yahoofinance.csv"%(instrument))
    #feed.addBarsFromCSV(instrument, "%s-2012-yahoofinance.csv"%(instrument))
    #feed.addBarsFromCSV(instrument, "%s-2013-yahoofinance.csv"%(instrument))
    #feed.addBarsFromCSV(instrument, "%s-2014-yahoofinance.csv"%(instrument))
    # Run the server.
    server.serve(feed, parameters_generator(), "localhost", 5000)
Пример #44
0
 def setStats(self, instrument):
     y_info = yahoofinance.build_feed([instrument], 2008, 2008, ".")
     t = Test(y_info, instrument, self.Weight)
     stats = Statistics(t)
     self.stats = stats
Пример #45
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()
Пример #46
0
        return bar.getClose() < self.__exitSMA[-1]


def parameters_generator():
    entrySMA = range(150, 251)
    exitSMA = range(5, 16)
    rsiPeriod = range(2, 11)
    overBoughtThreshold = range(75, 96)
    overSoldThreshold = range(5, 26)
    return itertools.product(entrySMA, exitSMA, rsiPeriod, overBoughtThreshold,
                             overSoldThreshold)


# The if __name__ == '__main__' part is necessary if running on Windows.
instrument = sys.argv[1]
if __name__ == '__main__':
    # Load the feed from the CSV files.
    #feed = yahoofeed.Feed()
    #feed.addBarsFromCSV("dia", "dia-2009.csv")
    #feed.addBarsFromCSV("dia", "dia-2010.csv")
    #feed.addBarsFromCSV("dia", "dia-2011.csv")
    try:
        feed = yahoofinance.build_feed([instrument], 2011, 2014, ".")
    except:
        print "can't download..."
        pass
    else:
        #strategy1 = MyStrategy(feed, instrument, parameters_generator())
        local.run(MyStrategy, feed, parameters_generator())
        #strategy1.run()
Пример #47
0
def main(plot, code):
    #instrument = "yhoo"
    #.SS .SZ

    instrument = code + (".SS" if (code[0:3] == '600') else ".SZ")
    bBandsPeriod = 13

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

    strat = BBandsAll(feed, instrument, bBandsPeriod)
    sharpeRatioAnalyzer = sharpe.SharpeRatio()
    strat.attachAnalyzer(sharpeRatioAnalyzer)

    retAnalyzer = returns.Returns()
    strat.attachAnalyzer(retAnalyzer)
    drawDownAnalyzer = drawdown.DrawDown()
    strat.attachAnalyzer(drawDownAnalyzer)
    tradesAnalyzer = trades.Trades()
    strat.attachAnalyzer(tradesAnalyzer)

    tradesAnalyzer = trades.Trades()
    strat.attachAnalyzer(tradesAnalyzer)
    ##print 'retAnalyzer.getReturns()[-1]:', retAnalyzer.getReturns()[-1]
    ##print 'size retAnalyzer.getReturns()[-1]:', len(retAnalyzer.getReturns()[-1])

    #print 'last price:',strat.getLastPrice(instrument)
    #print  len(feed)

    if plot:
        plt = plotter.StrategyPlotter(strat, True, True, True)
        plt.getInstrumentSubplot(instrument).addDataSeries(
            "upper",
            strat.getBollingerBands().getUpperBand())
        plt.getInstrumentSubplot(instrument).addDataSeries(
            "middle",
            strat.getBollingerBands().getMiddleBand())
        plt.getInstrumentSubplot(instrument).addDataSeries(
            "lower",
            strat.getBollingerBands().getLowerBand())
        plt.getInstrumentSubplot(instrument).addDataSeries(
            "price", feed[instrument].getAdjCloseDataSeries())

    strat.run()
    #print "Sharpe ratio: %.2f" % sharpeRatioAnalyzer.getSharpeRatio(0.05)

    #logger.info("%s value: $%.2f" % (code, strat.getResult()))
    #logger.getLogger("custom").info("ble")
    logging.info("%s value: $%.2f" % (code, strat.getResult()))
    print "Final portfolio value: $%.2f" % strat.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())
        returns0 = tradesAnalyzer.getAllReturns()
        print "Avg. return: %2.f %%" % (returns0.mean() * 100)
        print "Returns std. dev.: %2.f %%" % (returns0.std() * 100)
        print "Max. return: %2.f %%" % (returns0.max() * 100)
        print "Min. return: %2.f %%" % (returns0.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())
        returns0 = tradesAnalyzer.getPositiveReturns()
        print "Avg. return: %2.f %%" % (returns0.mean() * 100)
        print "Returns std. dev.: %2.f %%" % (returns0.std() * 100)
        print "Max. return: %2.f %%" % (returns0.max() * 100)
        print "Min. return: %2.f %%" % (returns0.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())
        returns0 = tradesAnalyzer.getNegativeReturns()
        print "Avg. return: %2.f %%" % (returns0.mean() * 100)
        print "Returns std. dev.: %2.f %%" % (returns0.std() * 100)
        print "Max. return: %2.f %%" % (returns0.max() * 100)
        print "Min. return: %2.f %%" % (returns0.min() * 100)

    if plot:
        plt.plot()
Пример #48
0
from numpy import asarray
from numpy import diag
from numpy import zeros_like
from numpy import genfromtxt

from UtilityFunctions import  GetReturns
from CoreFunctions import ObjectiveFunction
from CoreFunctions import ComputeF
from CoreFunctions import RewardFunction
from CoreFunctions import SharpeRatio
#### MAIN ####


# Download the testing data from yahoo Finance.
instruments = ["aapl"] # Set the instruments to download data.
feed = yahoofinance.build_feed(instruments, 2011, 2012, "./Data") # Download the specified data.

# Retrieve data as an NP array.
trainingData = genfromtxt('./Data/aapl-2011-yahoofinance.csv', delimiter=',') # Read the data from CSV file.
trainingData = trainingData[1:, 6]  # Select the adjusted close

trainingData2012 = genfromtxt('./Data/aapl-2012-yahoofinance.csv', delimiter=',') # Read the data from CSV file.
trainingData2012 = trainingData2012[1:, 6]  # Select the adjusted close

#print(trainingData.size)
trainingData = np.concatenate([trainingData,trainingData2012],axis=0)
#print (trainingData.size)

# Set the parameters
M = 10
T = 150
from pyalgotrade import strategy
from pyalgotrade.barfeed import yahoofeed
from pyalgotrade.tools import yahoofinance
from pyalgotrade.technical import ma
from pyalgotrade.technical import rsi
from pyalgotrade import dataseries
from pyalgotrade import technical

import technicalfilters as tf

feed = yahoofinance.build_feed(['GE', 'JCI', 'AAPL', 'ADI'],
                               2000,
                               2015,
                               './data/historical/daily-atrader',
                               frequency=86400,
                               skipErrors=False)


class MyStrategy(strategy.BacktestingStrategy):
    def __init__(self, feed, instrument, cash):
        strategy.BacktestingStrategy.__init__(self, feed, cash)
        self.__rsi = rsi.RSI(feed[instrument].getCloseDataSeries(), 14)
        self.__sma = ma.SMA(self.__rsi, 15)
        self.__instrument = instrument
        self.__EMA = tf.EMA(feed[instrument].getCloseDataSeries(), 16, .3)
        self.__DT = tf.Derivative(feed[instrument])

    def onBars(self, bars):

        bar = bars[self.__instrument]
        self.info(
Пример #50
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])
Пример #51
0
def fetchMyPortfolio():
    if not os.path.exists(dataDir):
        os.makedirs(dataDir)

    yahoofinance.build_feed(myPortfolio, 2017, 2017, dataDir,skipErrors=False)
Пример #52
0
def fitnessProgressTest(instrument, start, end):
    start_year = int(start.split('-')[0])
    data = get_stock(instrument, start, end, save=True)
    tech_indicators = get_indicators(data)
    result = parse_data_to_levels(data, tech_indicators)

    data = result["data"]
    maxDr = 0.0
    ret = 0.0
    unprofit = 0
    profit = 0
    sharpe = 0.0
    streak = 0.0
    train_maxDr = 0.0
    train_ret = 0.0
    train_profit = 0
    train_unprofit = 0
    train_sharpe = 0.0
    train_streak = 0
    lens = 1
    for i in range(lens):

        import time
        start1 = time.time()
        print "Start GENETIC"
        calc_str = genetic_algoritm(100, 1, 0.25, 0.3, data, tech_indicators,
                                    instrument, start)

        end = time.time()
        elapsed = end - start1
        print "Total time: %f" % elapsed
        train_maxDr += calc_str.stats.drawDownAnalyzer.getMaxDrawDown() * 100
        train_ret += calc_str.stats.retAnalyzer.getCumulativeReturns(
        )[-1] * 100
        train_profit += calc_str.stats.tradesAnalyzer.getProfitableCount()
        train_unprofit += calc_str.stats.tradesAnalyzer.getUnprofitableCount()
        train_sharpe += calc_str.stats.sharpeRatioAnalyzer.getSharpeRatio(
            0.025)
        train_streak += calc_str.stats.streak

        start2 = '%d-01-03' % (start_year + 1)
        end2 = '%d-12-30' % (start_year + 1)

        data2 = get_stock(instrument, start2, end2)
        data2 = parse_data_to_levels(data2, tech_indicators)
        getFitness(data2["data"], calc_str, setResults=True)

        weights = data2["data"]["Weight"]
        t = Test(
            yahoofinance.build_feed([instrument], start_year + 1,
                                    start_year + 1, "."), instrument, weights)
        stats = Statistics(t)
        maxDr += stats.drawDownAnalyzer.getMaxDrawDown() * 100
        ret += stats.retAnalyzer.getCumulativeReturns()[-1] * 100
        profit += stats.tradesAnalyzer.getProfitableCount()
        unprofit += stats.tradesAnalyzer.getUnprofitableCount()
        sharpe += stats.sharpeRatioAnalyzer.getSharpeRatio(0.025)
        streak += stats.streak

    result3 = []
    result3.append(train_sharpe)
    result3.append(train_ret)
    result3.append(train_maxDr)
    result3.append(train_profit)
    result3.append(train_unprofit)
    result3.append(train_streak)

    result3.append(sharpe)
    result3.append(ret)
    result3.append(maxDr)
    result3.append(profit)
    result3.append(unprofit)
    result3.append(streak)
    return result3
Пример #53
0
 def __getFeedFromYahoo(self,instrument):
     from pyalgotrade.tools import yahoofinance        
     import sys,os
     dataPath = os.path.abspath(os.path.join(os.path.dirname(__file__),'data','yahoodb','csv'))          
     feed = yahoofinance.build_feed([instrument], 2015, 2015, dataPath)    
     return feed