예제 #1
0
    def testInvalidInstrument(self):
        instrument = "inexistent"

        # Don't skip errors.
        with self.assertRaisesRegexp(Exception, "404 Client Error: Not Found"):
            with common.TmpDir() as tmpPath:
                quandl.build_feed(instrument, [instrument],
                                  PRICE_CURRENCY,
                                  2010,
                                  2010,
                                  tmpPath,
                                  bar.Frequency.WEEK,
                                  authToken=QUANDL_API_KEY)

        # Skip errors.
        with common.TmpDir() as tmpPath:
            bf = quandl.build_feed(instrument, [instrument],
                                   PRICE_CURRENCY,
                                   2010,
                                   2010,
                                   tmpPath,
                                   bar.Frequency.WEEK,
                                   skipErrors=True,
                                   authToken=QUANDL_API_KEY)
            bf.loadAll()
            self.assertNotIn(instrument, bf)
예제 #2
0
 def testBuildFeedWeekly(self):
     with common.TmpDir() as tmpPath:
         instrument = "AAPL"
         bf = quandl.build_feed("WIKI", [instrument],
                                2010,
                                2010,
                                tmpPath,
                                bar.Frequency.WEEK,
                                authToken=auth_token)
         bf.loadAll()
         # Quandl used to report 2010-1-3 as the first week of 2010.
         self.assertTrue(bf[instrument][0].getDateTime() in [
             datetime.datetime(2010, 1, 3),
             datetime.datetime(2010, 1, 10)
         ])
         self.assertEquals(bf[instrument][-1].getDateTime(),
                           datetime.datetime(2010, 12, 26))
         self.assertEquals(bf[instrument][-1].getOpen(), 325.0)
         self.assertEquals(bf[instrument][-1].getHigh(), 325.15)
         self.assertEquals(bf[instrument][-1].getLow(), 323.17)
         self.assertEquals(bf[instrument][-1].getClose(), 323.6)
         self.assertEquals(bf[instrument][-1].getVolume(), 7969900)
         self.assertEquals(bf[instrument][-1].getPrice(), 323.6)
         # Not checking against a specific value since this is going to change
         # as time passes by.
         self.assertNotEquals(bf[instrument][-1].getAdjClose(), None)
예제 #3
0
def main(plot):
    symbol = "GORO"
    priceCurrency = "USD"
    instrument = "%s/%s" % (symbol, priceCurrency)
    initialBalance = {priceCurrency: 1000000}

    # Download GORO bars using WIKI source code.
    feed = quandl.build_feed("WIKI", [symbol], "USD", 2006, 2012, ".")

    # Load Quandl CSV downloaded from http://www.quandl.com/OFDP-Open-Financial-Data-Project/GOLD_2-LBMA-Gold-Price-London-Fixings-P-M
    quandlFeed = csvfeed.Feed("Date", "%Y-%m-%d")
    quandlFeed.setDateRange(datetime.datetime(2006, 1, 1),
                            datetime.datetime(2012, 12, 31))
    quandlFeed.addValuesFromCSV("quandl_gold_2.csv")

    myStrategy = MyStrategy(feed, quandlFeed, instrument, initialBalance)

    if plot:
        from pyalgotrade import plotter

        plt = plotter.StrategyPlotter(myStrategy, True, False, False)
        plt.getOrCreateSubplot("quandl").addDataSeries("USD",
                                                       quandlFeed["USD"])
        plt.getOrCreateSubplot("quandl").addDataSeries("EUR",
                                                       quandlFeed["EUR"])
        plt.getOrCreateSubplot("quandl").addDataSeries("GBP",
                                                       quandlFeed["GBP"])

    myStrategy.run()

    if plot:
        plt.plot()
예제 #4
0
    def testBuildFeedDailyCreatingDir(self):
        tmpPath = tempfile.mkdtemp()
        shutil.rmtree(tmpPath)
        try:
            symbol = "ORCL"
            instrument = "%s/%s" % (symbol, PRICE_CURRENCY)
            bf = quandl.build_feed("WIKI", [symbol],
                                   PRICE_CURRENCY,
                                   2010,
                                   2010,
                                   tmpPath,
                                   authToken=QUANDL_API_KEY)
            bf.loadAll()
            ds = bf.getDataSeries(instrument)

            self.assertEqual(ds[-1].getDateTime(),
                             datetime.datetime(2010, 12, 31))
            self.assertEqual(ds[-1].getOpen(), 31.22)
            self.assertEqual(ds[-1].getHigh(), 31.33)
            self.assertEqual(ds[-1].getLow(), 30.93)
            self.assertEqual(ds[-1].getClose(), 31.3)
            self.assertEqual(ds[-1].getVolume(), 11716300)
            self.assertEqual(ds[-1].getPrice(), 31.3)
            # Not checking against a specific value since this is going to change
            # as time passes by.
            self.assertNotEqual(ds[-1].getAdjClose(), None)
        finally:
            shutil.rmtree(tmpPath)
예제 #5
0
    def testBuildFeedWeekly(self):
        with common.TmpDir() as tmpPath:
            symbol = "AAPL"
            instrument = "%s/%s" % (symbol, PRICE_CURRENCY)
            bf = quandl.build_feed("WIKI", [symbol],
                                   PRICE_CURRENCY,
                                   2010,
                                   2010,
                                   tmpPath,
                                   bar.Frequency.WEEK,
                                   authToken=QUANDL_API_KEY)
            bf.loadAll()
            ds = bf.getDataSeries(instrument)

            # Quandl used to report 2010-1-3 as the first week of 2010.
            self.assertTrue(ds[0].getDateTime() in [
                datetime.datetime(2010, 1, 3),
                datetime.datetime(2010, 1, 10)
            ])
            self.assertEqual(ds[-1].getDateTime(),
                             datetime.datetime(2010, 12, 26))
            self.assertEqual(ds[-1].getOpen(), 325.0)
            self.assertEqual(ds[-1].getHigh(), 325.15)
            self.assertEqual(ds[-1].getLow(), 323.17)
            self.assertEqual(ds[-1].getClose(), 323.6)
            self.assertEqual(ds[-1].getVolume(), 7969900)
            self.assertEqual(ds[-1].getPrice(), 323.6)
            # Not checking against a specific value since this is going to change
            # as time passes by.
            self.assertNotEqual(ds[-1].getAdjClose(), None)
예제 #6
0
def main(plot):
    instruments = ["GORO"]

    # Download GORO bars using WIKI source code.
    feed = quandl.build_feed("WIKI", instruments, 2006, 2012, ".")

    # Load Quandl CSV downloaded from http://www.quandl.com/OFDP-Open-Financial-Data-Project/GOLD_2-LBMA-Gold-Price-London-Fixings-P-M
    quandlFeed = csvfeed.Feed("Date", "%Y-%m-%d")
    quandlFeed.setDateRange(datetime.datetime(2006, 1, 1),
                            datetime.datetime(2012, 12, 31))
    quandlFeed.addValuesFromCSV("WIKI-GORO-2006-quandl.csv")

    myStrategy = MyStrategy(feed, quandlFeed, instruments[0])

    if plot:
        plt = plotter.StrategyPlotter(myStrategy, True, False, False)
        plt.getOrCreateSubplot("quandl").addDataSeries("USD",
                                                       quandlFeed["USD"])
        plt.getOrCreateSubplot("quandl").addDataSeries("EUR",
                                                       quandlFeed["EUR"])
        plt.getOrCreateSubplot("quandl").addDataSeries("GBP",
                                                       quandlFeed["GBP"])

    myStrategy.run()

    if plot:
        plt.plot()
예제 #7
0
def genetic_algoritm(N,
                     gens,
                     s,
                     m,
                     data,
                     tech_indicators,
                     instrument,
                     year,
                     red_rules=None):
    global data_set, total_crossovers, total_mutate, y_info, inst
    inst = instrument
    start = int(year.split('-')[2])
    y_info = quandl.build_feed("WIKI", [instrument], start, start, ".")

    total_crossovers = 0
    total_mutate = 0
    population = makePopulation(data, tech_indicators, N)
    if red_rules is not None:
        population = set_red_rules(population, red_rules)

    for i in range(gens):
        print "Create %d generation" % i
        population = next_generation(s, m, population)

    #createPic(population[len(population)-1],"1")
    print "Delete logic violation"
    print "Testing stage is over, best fitness is %f" % population[
        len(population) - 1].fitness
    print "Total mutates %d" % total_mutate
    print "Total crossovers %d" % total_crossovers
    #createPic(population[len(population)-1],"data/strat_fruct")
    #population[len(population)-1].getFitness(data_set,False)
    return population[len(population) - 1]
예제 #8
0
    def testMapColumnNames(self):
        column_names = {
            "open": "Open",
            "high": "High",
            "low": "Low",
            "close": "Last",
            "volume": "Volume",
        }
        with common.TmpDir() as tmpPath:
            symbol = "ADYEN"
            instrument = "%s/%s" % (symbol, PRICE_CURRENCY)
            year = 2018
            bf = quandl.build_feed("EURONEXT", [symbol],
                                   PRICE_CURRENCY,
                                   year,
                                   year,
                                   tmpPath,
                                   columnNames=column_names,
                                   skipMalformedBars=True,
                                   authToken=QUANDL_API_KEY)
            bf.setNoAdjClose()
            bf.loadAll()
            ds = bf.getDataSeries(instrument)

            self.assertEqual(ds[0].getDateTime(),
                             datetime.datetime(year, 6, 13))
            self.assertEqual(ds[0].getOpen(), 400.00)
            self.assertEqual(ds[0].getHigh(), 503.90)
            self.assertEqual(ds[0].getLow(), 400.00)
            self.assertEqual(ds[0].getClose(), 455.00)
            self.assertEqual(ds[0].getVolume(), 1529232)
            self.assertEqual(ds[0].getAdjClose(), None)
            self.assertEqual(ds[0].getPrice(), 455.00)
예제 #9
0
def main(plot):
    instrument = "yhoo"
    bBandsPeriod = 40

    # Download the bars.
    feed = quandl.build_feed("WIKI", [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()
예제 #10
0
 def testMapColumnNames(self):
     column_names = {
         "open": "Price",
         "close": "Price",
     }
     with common.TmpDir() as tmpPath:
         instrument = "IWG"
         year = 2017
         bf = quandl.build_feed("LSE", [instrument],
                                year,
                                year,
                                tmpPath,
                                columnNames=column_names,
                                skipMalformedBars=True,
                                authToken=QUANDL_API_KEY)
         bf.setNoAdjClose()
         bf.loadAll()
         self.assertEqual(bf[instrument][0].getDateTime(),
                          datetime.datetime(year, 1, 3))
         self.assertEqual(bf[instrument][0].getOpen(), 237.80)
         self.assertEqual(bf[instrument][0].getHigh(), 247.00)
         self.assertEqual(bf[instrument][0].getLow(), 236.30)
         self.assertEqual(bf[instrument][0].getClose(), 237.80)
         self.assertEqual(bf[instrument][0].getVolume(), 3494173)
         self.assertEqual(bf[instrument][0].getAdjClose(), None)
         self.assertEqual(bf[instrument][0].getPrice(), 237.80)
예제 #11
0
파일: main.py 프로젝트: iskrich/diploma
def calcStrategy(instrument, start, end, size, gens):
    data = get_stock(instrument, start, end, save=True)
    tech_indicators = get_indicators(data)
    result = parse_data_to_levels(data, tech_indicators)
    data = result["data"]
    calc_str = genetic_algoritm(size, gens, 0.25, 0.3, data, tech_indicators,
                                instrument, start)

    start_year2 = int(start.split('-')[2]) + 1
    start2 = start.split('-')[0] + "-" + start.split('-')[1] + "-" + str(
        start_year2)
    end2 = end.split('-')[0] + "-" + end.split('-')[1] + "-" + str(start_year2)
    data2 = get_stock(instrument, start2, end2)
    data2 = parse_data_to_levels(data2, tech_indicators)
    getFitness(data2["data"], calc_str, setResults=True)
    result = data2["data"]
    weights = result["Weight"]
    t = Test(
        quandl.build_feed("WIKI", [instrument], start_year2, start_year2, "."),
        instrument, weights)
    stats = Statistics(t)
    print "Final Strategy"
    print calc_str
    #generatePDF(stats, start+" по " +end, start2 + " по " + end2)
    stats.printResults()
예제 #12
0
def main(plot):
    symbol = "yhoo"
    priceCurrency = "USD"
    instrument = "%s/%s" % (symbol, priceCurrency)
    bBandsPeriod = 40

    # Download the bars.
    feed = quandl.build_feed("WIKI", [symbol], priceCurrency, 2011, 2012, ".")
    broker = backtesting.Broker({priceCurrency: 1000000}, feed)

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

    if plot:
        from pyalgotrade import plotter

        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()
예제 #13
0
def main(plot):
    symbol = "AAPL"
    priceCurrency = "USD"
    instrument = "%s/%s" % (symbol, priceCurrency)
    initialBalance = {priceCurrency: 1000000}
    vwapWindowSize = 5
    threshold = 0.01

    # Download the bars.
    feed = quandl.build_feed("WIKI", [symbol], priceCurrency, 2011, 2012, ".")

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

    if plot:
        from pyalgotrade import plotter

        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()
예제 #14
0
    def testInvalidInstrument(self):
        instrument = "inexistent"

        # Don't skip errors.
        with self.assertRaisesRegexp(Exception, "HTTP Error 404: Not Found"):
            with common.TmpDir() as tmpPath:
                quandl.build_feed(
                    instrument, [instrument], 2010, 2010, tmpPath, bar.Frequency.WEEK, authToken=auth_token
                )

        # Skip errors.
        with common.TmpDir() as tmpPath:
            bf = quandl.build_feed(
                instrument, [instrument], 2010, 2010, tmpPath, bar.Frequency.WEEK, authToken=auth_token, skipErrors=True
            )
            bf.loadAll()
            self.assertNotIn(instrument, bf)
예제 #15
0
 def testMapColumnNames(self):
     with common.TmpDir() as tmpPath:
         bf = quandl.build_feed("YAHOO", ["AAPL"], 2010, 2010, tmpPath, columnNames={"adj_close": "Adjusted Close"})
         bf.setUseAdjustedValues(True)
         bf.loadAll()
         self.assertEquals(bf["AAPL"][-1].getClose(), 322.560013)
         self.assertIsNotNone(bf["AAPL"][-1].getAdjClose())
         self.assertIsNotNone(bf["AAPL"][-1].getPrice())
예제 #16
0
def main(plot):
    instruments = ["IBM", "AES", "AIG"]
    feed = quandl.build_feed("WIKI", 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)
예제 #17
0
 def testExtraColumns(self):
     with common.TmpDir() as tmpPath:
         columnNames = {
             "open": "Last",
             "close": "Last"
         }
         bf = quandl.build_feed("BITSTAMP", ["USD"], 2014, 2014, tmpPath, columnNames=columnNames)
         bf.loadAll()
         self.assertEquals(bf["USD"][-1].getExtraColumns()["Bid"], 319.19)
         self.assertEquals(bf["USD"][-1].getExtraColumns()["Ask"], 319.63)
         bids = bf["USD"].getExtraDataSeries("Bid")
         self.assertEquals(bids[-1], 319.19)
예제 #18
0
 def testMapColumnNames(self):
     with common.TmpDir() as tmpPath:
         bf = quandl.build_feed("YAHOO", ["AAPL"],
                                2010,
                                2010,
                                tmpPath,
                                columnNames={"adj_close": "Adjusted Close"})
         bf.setUseAdjustedValues(True)
         bf.loadAll()
         self.assertEquals(bf["AAPL"][-1].getClose(), 322.560013)
         self.assertIsNotNone(bf["AAPL"][-1].getAdjClose())
         self.assertIsNotNone(bf["AAPL"][-1].getPrice())
예제 #19
0
 def testBuildFeedDaily(self):
     with common.TmpDir() as tmpPath:
         instrument = "ORCL"
         bf = quandl.build_feed("WIKI", [instrument], 2010, 2010, tmpPath, authToken=auth_token)
         bf.loadAll()
         self.assertEquals(bf[instrument][-1].getDateTime(), datetime.datetime(2010, 12, 31))
         self.assertEquals(bf[instrument][-1].getOpen(), 31.22)
         self.assertEquals(bf[instrument][-1].getHigh(), 31.33)
         self.assertEquals(bf[instrument][-1].getLow(), 30.93)
         self.assertEquals(bf[instrument][-1].getClose(), 31.3)
         self.assertEquals(bf[instrument][-1].getVolume(), 11716300)
         self.assertEquals(bf[instrument][-1].getAdjClose(), 30.23179912467581)
         self.assertEquals(bf[instrument][-1].getPrice(), 31.3)
예제 #20
0
    def testNoAdjClose(self):
        with common.TmpDir() as tmpPath:
            columnNames = {"open": "Last", "close": "Last", "adj_close": None}
            bf = quandl.build_feed("BITSTAMP", ["USD"],
                                   2014,
                                   2014,
                                   tmpPath,
                                   columnNames=columnNames,
                                   authToken=QUANDL_API_KEY)
            bf.loadAll()

            self.assertFalse(bf.barsHaveAdjClose())
            self.assertEqual(bf["USD"][-1].getAdjClose(), None)
예제 #21
0
 def testExtraColumns(self):
     with common.TmpDir() as tmpPath:
         columnNames = {"open": "Last", "close": "Last"}
         bf = quandl.build_feed("BITSTAMP", ["USD"],
                                2014,
                                2014,
                                tmpPath,
                                columnNames=columnNames)
         bf.loadAll()
         self.assertEquals(bf["USD"][-1].getExtraColumns()["Bid"], 319.19)
         self.assertEquals(bf["USD"][-1].getExtraColumns()["Ask"], 319.63)
         bids = bf["USD"].getExtraDataSeries("Bid")
         self.assertEquals(bids[-1], 319.19)
예제 #22
0
def main(plot):
    symbols = ["IBM", "AES", "AIG"]
    priceCurrency = "USD"
    feed = quandl.build_feed("WIKI", symbols, priceCurrency, 2008, 2009, ".")
    instruments = ["%s/%s" % (symbol, priceCurrency) for symbol in symbols]

    predicate = BuyOnGap(feed, instruments)
    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 testBuildFeedDaily(self):
     with common.TmpDir() as tmpPath:
         instrument = "ORCL"
         bf = quandl.build_feed("WIKI", [instrument], 2010, 2010, tmpPath, authToken=auth_token)
         bf.loadAll()
         self.assertEquals(bf[instrument][-1].getDateTime(), datetime.datetime(2010, 12, 31))
         self.assertEquals(bf[instrument][-1].getOpen(), 31.22)
         self.assertEquals(bf[instrument][-1].getHigh(), 31.33)
         self.assertEquals(bf[instrument][-1].getLow(), 30.93)
         self.assertEquals(bf[instrument][-1].getClose(), 31.3)
         self.assertEquals(bf[instrument][-1].getVolume(), 11716300)
         self.assertEquals(bf[instrument][-1].getPrice(), 31.3)
         # Not checking against a specific value since this is going to change
         # as time passes by.
         self.assertNotEquals(bf[instrument][-1].getAdjClose(), None)
예제 #24
0
 def testBuildFeedDaily(self):
     with common.TmpDir() as tmpPath:
         instrument = "ORCL"
         bf = quandl.build_feed("WIKI", [instrument], 2010, 2010, tmpPath, authToken=auth_token)
         bf.loadAll()
         self.assertEquals(bf[instrument][-1].getDateTime(), datetime.datetime(2010, 12, 31))
         self.assertEquals(bf[instrument][-1].getOpen(), 31.22)
         self.assertEquals(bf[instrument][-1].getHigh(), 31.33)
         self.assertEquals(bf[instrument][-1].getLow(), 30.93)
         self.assertEquals(bf[instrument][-1].getClose(), 31.3)
         self.assertEquals(bf[instrument][-1].getVolume(), 11716300)
         self.assertEquals(bf[instrument][-1].getPrice(), 31.3)
         # Not checking against a specific value since this is going to change
         # as time passes by.
         self.assertNotEquals(bf[instrument][-1].getAdjClose(), None)
예제 #25
0
    def testNoAdjClose(self):
        with common.TmpDir() as tmpPath:
            columnNames = {
                "open": "Last",
                "close": "Last",
                "adj_close": None
            }
            bf = quandl.build_feed(
                "BITSTAMP", ["USD"], 2014, 2014, tmpPath, columnNames=columnNames,
                authToken=QUANDL_API_KEY
            )
            bf.loadAll()

            self.assertFalse(bf.barsHaveAdjClose())
            self.assertEquals(bf["USD"][-1].getAdjClose(), None)
예제 #26
0
 def testBuildFeedWeekly(self):
     with common.TmpDir() as tmpPath:
         instrument = "AAPL"
         bf = quandl.build_feed("WIKI", [instrument], 2010, 2010, tmpPath, bar.Frequency.WEEK, authToken=auth_token)
         bf.loadAll()
         self.assertEquals(bf[instrument][0].getDateTime(), datetime.datetime(2010, 1, 3))
         self.assertEquals(bf[instrument][-1].getDateTime(), datetime.datetime(2010, 12, 26))
         self.assertEquals(bf[instrument][-1].getOpen(), 325.0)
         self.assertEquals(bf[instrument][-1].getHigh(), 325.15)
         self.assertEquals(bf[instrument][-1].getLow(), 323.17)
         self.assertEquals(bf[instrument][-1].getClose(), 323.6)
         self.assertEquals(bf[instrument][-1].getVolume(), 7969900)
         self.assertEquals(bf[instrument][-1].getPrice(), 323.6)
         # Not checking against a specific value since this is going to change
         # as time passes by.
         self.assertNotEquals(bf[instrument][-1].getAdjClose(), None)
예제 #27
0
    def testNoAdjClose(self):
        with common.TmpDir() as tmpPath:
            columnNames = {"open": "Last", "close": "Last", "adj_close": None}
            symbol = "BTC"
            instrument = "%s/%s" % (symbol, PRICE_CURRENCY)
            bf = quandl.build_feed("BITSTAMP", {"USD": symbol},
                                   PRICE_CURRENCY,
                                   2014,
                                   2014,
                                   tmpPath,
                                   columnNames=columnNames,
                                   authToken=QUANDL_API_KEY)
            bf.loadAll()
            ds = bf.getDataSeries(instrument)

            self.assertFalse(bf.barsHaveAdjClose())
            self.assertEqual(ds[-1].getAdjClose(), None)
예제 #28
0
 def testBuildFeedDaily(self):
     with common.TmpDir() as tmpPath:
         instrument = "ORCL"
         bf = quandl.build_feed("WIKI", [instrument],
                                2010,
                                2010,
                                tmpPath,
                                authToken=auth_token)
         bf.loadAll()
         self.assertEquals(bf[instrument][-1].getDateTime(),
                           datetime.datetime(2010, 12, 31))
         self.assertEquals(bf[instrument][-1].getOpen(), 31.22)
         self.assertEquals(bf[instrument][-1].getHigh(), 31.33)
         self.assertEquals(bf[instrument][-1].getLow(), 30.93)
         self.assertEquals(bf[instrument][-1].getClose(), 31.3)
         self.assertEquals(bf[instrument][-1].getVolume(), 11716300)
         self.assertEquals(bf[instrument][-1].getAdjClose(),
                           30.23179912467581)
         self.assertEquals(bf[instrument][-1].getPrice(), 31.3)
def main(plot):
    instrument = "TSLA"
    vwapWindowSize = 60
    threshold = 0.00000001

    # Download the bars.
    feed = quandl.build_feed("WIKI", [instrument], 2007, 2018, ".")

    strat = VWAPMomentum(feed, instrument, vwapWindowSize, threshold)
    sharpeRatioAnalyzer = sharpe.SharpeRatio()
    strat.attachAnalyzer(sharpeRatioAnalyzer)
    retAnalyzer = returns.Returns()
    strat.attachAnalyzer(retAnalyzer)
    drawDownAnalyzer = drawdown.DrawDown()
    strat.attachAnalyzer(drawDownAnalyzer)
    tradesAnalyzer = trades.Trades()
    strat.attachAnalyzer(tradesAnalyzer)
    returns3 = tradesAnalyzer.getAllReturns()
    if plot:
        plt = plotter.StrategyPlotter(strat, True, False, True)
        plt.getInstrumentSubplot(instrument).addDataSeries(
            "vwap", strat.getVWAP())

    strat.run()
    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(retAnalyzer.getReturns())
    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()))
        print(stats.ttest_1samp(tradesAnalyzer.getAllReturns(), 0))
    if plot:
        plt.plot()
예제 #30
0
def main(plot):
    instrument = "AAPL"
    smaPeriod = 163

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

    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()
예제 #31
0
    def testBuildFeedDailyCreatingDir(self):
        tmpPath = tempfile.mkdtemp()
        shutil.rmtree(tmpPath)
        try:
            instrument = "ORCL"
            bf = quandl.build_feed("WIKI", [instrument], 2010, 2010, tmpPath, authToken=QUANDL_API_KEY)
            bf.loadAll()

            self.assertEquals(bf[instrument][-1].getDateTime(), datetime.datetime(2010, 12, 31))
            self.assertEquals(bf[instrument][-1].getOpen(), 31.22)
            self.assertEquals(bf[instrument][-1].getHigh(), 31.33)
            self.assertEquals(bf[instrument][-1].getLow(), 30.93)
            self.assertEquals(bf[instrument][-1].getClose(), 31.3)
            self.assertEquals(bf[instrument][-1].getVolume(), 11716300)
            self.assertEquals(bf[instrument][-1].getPrice(), 31.3)
            # Not checking against a specific value since this is going to change
            # as time passes by.
            self.assertNotEquals(bf[instrument][-1].getAdjClose(), None)
        finally:
            shutil.rmtree(tmpPath)
예제 #32
0
def main(plot):
    instrument = "AAPL"
    smaPeriod = 30

    # Download the bars.
    feed = quandl.build_feed("WIKI", [instrument,"NVDA"], 2016, 2018, Constants.data_directory)

    strategy = sma_crossover.SMACrossOver(feed, instrument, smaPeriod)
    sharpeRatioAnalyzer = sharpe.SharpeRatio()
    strategy.attachAnalyzer(sharpeRatioAnalyzer)
    if plot:
        plt = plotter.StrategyPlotter(strategy, True, True, True)
        plt.getInstrumentSubplot(instrument).addDataSeries("sma", strategy.getSMA())

    strategy.run()

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

    if plot:
        plt.plot()
예제 #33
0
파일: mytry.py 프로젝트: yjy-1999/MyQuant
def main():
    instrument = "AAPL"
    vwapWindowSize = 5
    threshold = 0.01

    feed = quandl.build_feed("WIKI", [instrument], 2011, 2012, ".")

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

    plter = plotter.StrategyPlotter(strat, True, True, True)
    plter.getInstrumentSubplot(instrument).addDataSeries(
        "vwap", strat.getVWAP())

    strat.run()
    print("夏普比例:%.2f" % sharpeRatioAnalyzer.getSharpeRatio(0.03))
    print("期末策略市值:%.2f" % strat.getResult())

    plter.savePlot("mytry.png")
예제 #34
0
def main(plot):
    instrument = "AAPL"
    vwapWindowSize = 5
    threshold = 0.01

    # Download the bars.
    feed = quandl.build_feed("WIKI", [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()
예제 #35
0
def main(plot):
    instrument = "AAPL"
    smaPeriod = 163

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

    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()
예제 #36
0
    def testExtraColumns(self):
        with common.TmpDir() as tmpPath:
            columnNames = {"open": "Last", "close": "Last"}
            symbol = "BTC"
            instrument = "%s/%s" % (symbol, PRICE_CURRENCY)
            bf = quandl.build_feed("BITSTAMP", {"USD": symbol},
                                   PRICE_CURRENCY,
                                   2014,
                                   2014,
                                   tmpPath,
                                   columnNames=columnNames,
                                   authToken=QUANDL_API_KEY)
            bf.loadAll()
            ds = bf.getDataSeries(instrument)

            self.assertEqual(len(ds[-1].getExtraColumns()), 3)
            self.assertEqual(ds[-1].getExtraColumns()["Bid"], 319.19)
            self.assertEqual(ds[-1].getExtraColumns()["Ask"], 319.63)

            bids = ds.getExtraDataSeries("Bid")
            self.assertEqual(bids[-1], 319.19)
예제 #37
0
 def testMapColumnNames(self):
     column_names = {
         "open": "Price",
         "close": "Price",
     }
     with common.TmpDir() as tmpPath:
         instrument = "IWG"
         year = 2017
         bf = quandl.build_feed(
             "LSE", [instrument], year, year, tmpPath, columnNames=column_names, skipMalformedBars=True,
             authToken=QUANDL_API_KEY
         )
         bf.setNoAdjClose()
         bf.loadAll()
         self.assertEquals(bf[instrument][0].getDateTime(), datetime.datetime(year, 1, 3))
         self.assertEquals(bf[instrument][0].getOpen(), 237.80)
         self.assertEquals(bf[instrument][0].getHigh(), 247.00)
         self.assertEquals(bf[instrument][0].getLow(), 236.30)
         self.assertEquals(bf[instrument][0].getClose(), 237.80)
         self.assertEquals(bf[instrument][0].getVolume(), 3494173)
         self.assertEquals(bf[instrument][0].getAdjClose(), None)
         self.assertEquals(bf[instrument][0].getPrice(), 237.80)
예제 #38
0
def main(plot):
    instrument = "yhoo"
    bBandsPeriod = 40

    # Download the bars.
    feed = quandl.build_feed("WIKI", [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()
예제 #39
0
def main(plot):
    instrument = "AAPL"
    vwapWindowSize = 5
    threshold = 0.01

    # Download the bars.
    feed = quandl.build_feed("WIKI", [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):
    instruments = ["GORO"]

    # Download GORO bars using WIKI source code.
    feed = quandl.build_feed("WIKI", instruments, 2006, 2012, "data")

    # Load Quandl CSV downloaded from http://www.quandl.com/OFDP-Open-Financial-Data-Project/GOLD_2-LBMA-Gold-Price-London-Fixings-P-M
    quandlFeed = csvfeed.Feed("Date", "%Y-%m-%d")
    quandlFeed.setDateRange(datetime.datetime(2006, 1, 1), datetime.datetime(2012, 12, 31))
    quandlFeed.addValuesFromCSV("quandl_gold_2.csv")

    myStrategy = MyStrategy(feed, quandlFeed, instruments[0])

    if plot:
        plt = plotter.StrategyPlotter(myStrategy, True, False, False)
        plt.getOrCreateSubplot("quandl").addDataSeries("USD", quandlFeed["USD"])
        plt.getOrCreateSubplot("quandl").addDataSeries("EUR", quandlFeed["EUR"])
        plt.getOrCreateSubplot("quandl").addDataSeries("GBP", quandlFeed["GBP"])

    myStrategy.run()

    if plot:
        plt.plot()
예제 #41
0
def main():
    instruments = ["AAPL", "NVDA"]
    feed = quandl.build_feed("WIKI", instruments, 2016, 2018,
                             Constants.data_directory)
    strategy = MultipleInstrumentStrategy(feed, instruments)
    strategy.run()
예제 #42
0
                             bars[self.__instrument].getPrice())
                # Enter a buy market order. The order is good till canceled.
                self.__position = self.enterLong(self.__instrument, shares,
                                                 True)
        # Check if we have to exit the position.
        elif not self.__position.exitActive() and cross.cross_below(
                self.__prices, self.__sma) > 0:
            self.__position.exitMarket()


from pyalgotrade import plotter
from pyalgotrade.barfeed import quandlfeed
from pyalgotrade.stratanalyzer import returns
#import sma_crossover

data = quandl.build_feed("WIKI", ['ORCL'], 2000, 2000, ".")
# Load the bar feed from the CSV file
feed = quandlfeed.Feed()
feed.addBarsFromCSV("orcl", "WIKI-ORCL-2000-quandl.csv")

# Evaluate the strategy with the feed's bars.
myStrategy = SMACrossOver(feed, "orcl", 20)

# 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("orcl").addDataSeries("SMA", myStrategy.getSMA())