def testIGE_BrokerWithCommission(self):
        commision = 0.5
        initialCash = 42.09 + commision
        # This testcase is based on an example from Ernie Chan's book:
        # 'Quantitative Trading: How to Build Your Own Algorithmic Trading Business'
        barFeed = yahoofeed.Feed()
        barFeed.addBarsFromCSV(
            "ige", common.get_data_file_path("sharpe-ratio-test-ige.csv"))
        strat = strategy_test.TestStrategy(barFeed, initialCash)
        strat.getBroker().setCommission(backtesting.FixedPerTrade(commision))
        strat.getBroker().setUseAdjustedValues(True)
        strat.setBrokerOrdersGTC(True)
        stratAnalyzer = sharpe.SharpeRatio()
        strat.attachAnalyzer(stratAnalyzer)

        # Manually place the order to get it filled on the first bar.
        order = strat.getBroker().createMarketOrder(broker.Order.Action.BUY,
                                                    "ige", 1,
                                                    True)  # Adj. Close: 42.09
        order.setGoodTillCanceled(True)
        strat.getBroker().placeOrder(order)
        strat.addOrder(strategy_test.datetime_from_date(2007, 11, 13),
                       strat.getBroker().createMarketOrder,
                       broker.Order.Action.SELL, "ige", 1,
                       True)  # Adj. Close: 127.64
        strat.run()
        self.assertTrue(
            round(strat.getBroker().getCash(), 2) == initialCash +
            (127.64 - 42.09 - commision * 2))
        self.assertTrue(strat.getOrderUpdatedEvents() == 4)
        # The results are slightly different only because I'm taking into account the first bar as well,
        # and I'm also adding commissions.
        self.assertEqual(round(stratAnalyzer.getSharpeRatio(0.04, True), 6),
                         0.776443)
Beispiel #2
0
    def testTwoBarReturns_CloseClose(self):
        initialCash = 15.90
        barFeed = yahoofeed.Feed()
        barFeed.setBarFilter(
            csvfeed.DateRangeFilter(datetime.datetime(2001, 12, 06),
                                    datetime.datetime(2001, 12, 07)))
        barFeed.addBarsFromCSV(
            AnalyzerTestCase.TestInstrument,
            common.get_data_file_path("orcl-2001-yahoofinance.csv"))
        strat = strategy_test.TestStrategy(barFeed, initialCash)

        # 2001-12-06,15.61,16.03,15.50,15.90,66944900,15.55
        # 2001-12-07,15.74,15.95,15.55,15.91,42463200,15.56
        # Manually place the entry order, to get it filled on the first bar.
        order = strat.getBroker().createMarketOrder(
            broker.Order.Action.BUY, AnalyzerTestCase.TestInstrument, 1,
            True)  # Close: 15.90
        strat.getBroker().submitOrder(order)
        strat.addOrder(datetime.datetime(2001, 12, 06),
                       strat.getBroker().createMarketOrder,
                       broker.Order.Action.SELL,
                       AnalyzerTestCase.TestInstrument, 1,
                       True)  # Close: 15.91

        stratAnalyzer = returns.Returns()
        strat.attachAnalyzer(stratAnalyzer)
        strat.run()
        self.assertTrue(strat.getBroker().getCash() == initialCash +
                        (15.91 - 15.90))
        # First day returns: 0
        self.assertTrue(stratAnalyzer.getReturns()[0] == 0)
        # Second day returns: Open vs Prev. day's close
        self.assertTrue(stratAnalyzer.getReturns()[1] == (15.91 - 15.90) /
                        15.90)
Beispiel #3
0
def main():
	# Load the orders file.
	ordersFile = OrdersFile("orders.csv")
	print "First date", ordersFile.getFirstDate()
	print "Last date", ordersFile.getLastDate()
	print "Symbols", ordersFile.getInstruments()

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

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

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

	myStrategy.run()

	# Print the results.
	print "Final portfolio value: $%.2f" % myStrategy.getResult()
	print "Anual return: %.2f %%" % (retAnalyzer.getCumulativeReturns()[-1] * 100)
	print "Average daily return: %.2f %%" % (stats.mean(retAnalyzer.getReturns()) * 100)
	print "Std. dev. daily return: %.4f" % (stats.stddev(retAnalyzer.getReturns()))
	print "Sharpe ratio: %.2f" % (sharpeRatioAnalyzer.getSharpeRatio(0, 252))
Beispiel #4
0
def turtle_test(dataString='pyalg'):
    """
    :param dataString:
    :return:
    """
    feed = yahoofeed.Feed()
    feed.addBarsFromCSV("orcl", "../../api/stock/csv/orcl-2000.csv")   #注意查看该csv的格式,Open为大写

    myStrategy = pdr.turtle(feed, "orcl", 20, 10)
    # Attach a returns analyzers to the trategy.
    returnsAnalyzer = returns.Returns()
    myStrategy.attachAnalyzer(returnsAnalyzer)

    # Attach the plotter to the strategy.
    plt = plotter.StrategyPlotter(myStrategy)
    # Plot the simple returns on each bar.
    plt.getOrCreateSubplot("returns").addDataSeries("Simple returns", returnsAnalyzer.getReturns())

    if dataString == 'pyalg_util':
        ds = pyalg_utils.dataSet(myStrategy)  # 抽取交易数据集语句,若使用系统自带画图功能则不需要该项
    myStrategy.run()
    myStrategy.info("Final portfolio value: $%.2f" % myStrategy.getResult())

    if dataString == 'pyalg_util':
        rs = ds.getDefault()  # 获取默认的交易信息,dic格式
        plot(rs["cumulativeReturns"][:, 0], rs["cumulativeReturns"][:, 1])  # 简单作图示例

    plt.plot()
Beispiel #5
0
def build_feed(instruments,
               fromYear,
               toYear,
               storage,
               frequency=bar.Frequency.DAY,
               timezone=None,
               skipErrors=False):
    logger = pyalgotrade.logger.getLogger("yahoofinance")
    ret = yahoofeed.Feed(frequency, timezone)

    if not os.path.exists(storage):
        logger.info("Creating %s directory" % (storage))
        os.mkdir(storage)

    for year in range(fromYear, toYear + 1):
        for instrument in instruments:
            fileName = os.path.join(
                storage, "%s-%d-yahoofinance.csv" % (instrument, year))
            if not os.path.exists(fileName):
                logger.info("Downloading %s %d to %s" %
                            (instrument, year, fileName))
                try:
                    if frequency == bar.Frequency.DAY:
                        download_daily_bars(instrument, year, fileName)
                    elif frequency == bar.Frequency.WEEK:
                        download_weekly_bars(instrument, year, fileName)
                    else:
                        raise Exception("Invalid frequency")
                except Exception, e:
                    if skipErrors:
                        logger.error(str(e))
                        continue
                    else:
                        raise e
            ret.addBarsFromCSV(instrument, fileName)
Beispiel #6
0
    def __testIGE_BrokerImpl(self, quantity):
        initialCash = 42.09 * quantity
        # This testcase is based on an example from Ernie Chan's book:
        # 'Quantitative Trading: How to Build Your Own Algorithmic Trading Business'
        barFeed = yahoofeed.Feed()
        barFeed.addBarsFromCSV(
            "ige", common.get_data_file_path("sharpe-ratio-test-ige.csv"))
        strat = strategy_test.TestStrategy(barFeed, initialCash)
        strat.setUseAdjustedValues(True)
        strat.setBrokerOrdersGTC(True)
        stratAnalyzer = sharpe.SharpeRatio()
        strat.attachAnalyzer(stratAnalyzer)

        # Disable volume checks to match book results.
        strat.getBroker().getFillStrategy().setVolumeLimit(None)

        # Manually place the order to get it filled on the first bar.
        order = strat.getBroker().createMarketOrder(broker.Order.Action.BUY,
                                                    "ige", quantity,
                                                    True)  # Adj. Close: 42.09
        order.setGoodTillCanceled(True)
        strat.getBroker().submitOrder(order)
        strat.addOrder(datetime.datetime(2007, 11, 13),
                       strat.getBroker().createMarketOrder,
                       broker.Order.Action.SELL, "ige", quantity,
                       True)  # Adj. Close: 127.64
        strat.run()
        self.assertEqual(round(strat.getBroker().getCash(), 2),
                         initialCash + (127.64 - 42.09) * quantity)
        self.assertEqual(strat.orderUpdatedCalls, 6)
        # The results are slightly different only because I'm taking into account the first bar as well.
        self.assertEqual(round(stratAnalyzer.getSharpeRatio(0.04, True), 4),
                         0.7889)
        self.assertEqual(round(stratAnalyzer.getSharpeRatio(0.04, False), 4),
                         0.0497)
    def __testIGE_BrokerImpl(self, quantity):
        initialCash = 42.09*quantity
        # This testcase is based on an example from Ernie Chan's book:
        # 'Quantitative Trading: How to Build Your Own Algorithmic Trading Business'
        barFeed = yahoofeed.Feed()
        barFeed.addBarsFromCSV("ige", common.get_data_file_path("sharpe-ratio-test-ige.csv"))
        strat = strategy_test.TestStrategy(barFeed, initialCash)
        strat.setUseAdjustedValues(True)
        strat.setBrokerOrdersGTC(True)
        stratAnalyzer = drawdown.DrawDown()
        strat.attachAnalyzer(stratAnalyzer)

        # Disable volume checks to match book results.
        strat.getBroker().getFillStrategy().setVolumeLimit(None)

        # Manually place the order to get it filled on the first bar.
        order = strat.getBroker().createMarketOrder(broker.Order.Action.BUY, "ige", quantity, True)  # Adj. Close: 42.09
        order.setGoodTillCanceled(True)
        strat.getBroker().submitOrder(order)
        strat.addOrder(datetime.datetime(2007, 11, 13), strat.getBroker().createMarketOrder, broker.Order.Action.SELL, "ige", quantity, True)  # Adj. Close: 127.64
        strat.run()

        self.assertTrue(round(strat.getBroker().getCash(), 2) == initialCash + (127.64 - 42.09) * quantity)
        self.assertEqual(strat.orderUpdatedCalls, 6)
        self.assertTrue(round(stratAnalyzer.getMaxDrawDown(), 5) == 0.31178)
        self.assertTrue(stratAnalyzer.getLongestDrawDownDuration() == datetime.timedelta(days=623))
	def __test(self, strategyClass, finalValue):
		feed = yahoofeed.Feed()
		feed.addBarsFromCSV("orcl", common.get_data_file_path("orcl-2001-yahoofinance.csv"))
		myStrategy = strategyClass(feed, 10, 25)
		myStrategy.run()
		myStrategy.printDebug("Final result:", round(myStrategy.getFinalValue(), 2))
		self.assertTrue(round(myStrategy.getFinalValue(), 2) == finalValue)
 def testBaseBarFeed(self):
     barFeed = yahoofeed.Feed()
     barFeed.sanitizeBars(True)
     barFeed.addBarsFromCSV(
         FeedTestCase.TestInstrument,
         common.get_data_file_path("orcl-2000-yahoofinance.csv"))
     barfeed_test.check_base_barfeed(self, barFeed, True)
    def testCumulativeReturn(self):
        initialCash = 33.06
        barFeed = yahoofeed.Feed()
        barFeed.addBarsFromCSV(
            AnalyzerTestCase.TestInstrument,
            common.get_data_file_path("orcl-2001-yahoofinance.csv"))
        strat = position_test.TestStrategy(barFeed,
                                           AnalyzerTestCase.TestInstrument,
                                           initialCash)

        strat.addPosEntry(datetime.datetime(2001, 1, 12), strat.enterLong,
                          AnalyzerTestCase.TestInstrument, 1)  # 33.06
        strat.addPosExitMarket(datetime.datetime(2001, 11, 27))  # 14.32

        stratAnalyzer = returns.Returns(maxLen=10)
        strat.attachAnalyzer(stratAnalyzer)
        strat.run()
        self.assertTrue(
            round(strat.getBroker().getCash(), 2) == round(
                initialCash + (14.32 - 33.06), 2))
        self.assertTrue(
            round(33.06 *
                  (1 + stratAnalyzer.getCumulativeReturns()[-1]), 2) == 14.32)
        self.assertEqual(len(stratAnalyzer.getCumulativeReturns()), 10)
        self.assertEqual(len(stratAnalyzer.getReturns()), 10)
 def __getFeed(self):
     # Load the feed and process all bars.
     barFeed = yahoofeed.Feed()
     barFeed.addBarsFromCSV(
         INSTRUMENT,
         common.get_data_file_path("orcl-2001-yahoofinance.csv"))
     return barFeed
Beispiel #12
0
def main(plot):
    cod = "002739"
    #万达院线
    cname = 'wanda'
    fss = "dat\\" + cod + ".csv"
    df = pd.read_csv(fss, encoding='gbk')
    #df2=zwBox.zw_df2yhaoo(df);
    df2 = zwx.df2yhaoo(df)
    cfn = "dat\\" + cod + "_yh.csv"
    print(fss)
    df2.to_csv(cfn, encoding='utf-8')
    #
    #instrument = "aapl" #使用新变量名cname替代
    vwapWindowSize = 5
    threshold = 0.01

    # Download the bars.
    #feed = yahoofinance.build_feed([cname], 2011, 2012, ".")
    feed = yahoofeed.Feed()
    feed.addBarsFromCSV(cname, cfn)

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

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

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

    if plot:
        plt.plot()
Beispiel #13
0
    def testBounded(self):
        tmpFeed = TemporarySQLiteFeed(SQLiteFeedTestCase.dbName,
                                      bar.Frequency.DAY,
                                      maxLen=2)
        with tmpFeed:
            # Load bars using a Yahoo! feed.
            yahooFeed = yahoofeed.Feed(maxLen=1)
            yahooFeed.addBarsFromCSV(
                "orcl",
                common.get_data_file_path("orcl-2000-yahoofinance.csv"),
                marketsession.USEquities.timezone)
            yahooFeed.addBarsFromCSV(
                "orcl",
                common.get_data_file_path("orcl-2001-yahoofinance.csv"),
                marketsession.USEquities.timezone)

            # Fill the database using the bars from the Yahoo! feed.
            sqliteFeed = tmpFeed.getFeed()
            sqliteFeed.getDatabase().addBarsFromFeed(yahooFeed)

            # Load the SQLite feed and process all bars.
            sqliteFeed.loadBars("orcl")
            for bars in sqliteFeed:
                pass

            barDS = sqliteFeed["orcl"]
            self.assertEqual(len(barDS), 2)
            self.assertEqual(len(barDS.getDateTimes()), 2)
            self.assertEqual(len(barDS.getCloseDataSeries()), 2)
            self.assertEqual(len(barDS.getCloseDataSeries().getDateTimes()), 2)
            self.assertEqual(len(barDS.getOpenDataSeries()), 2)
            self.assertEqual(len(barDS.getHighDataSeries()), 2)
            self.assertEqual(len(barDS.getLowDataSeries()), 2)
            self.assertEqual(len(barDS.getAdjCloseDataSeries()), 2)
Beispiel #14
0
    def testLoadDailyBars(self):
        tmpFeed = TemporarySQLiteFeed(SQLiteFeedTestCase.dbName, barfeed.Frequency.DAY)
        with tmpFeed:
            # Load bars using a Yahoo! feed.
            yahooFeed = yahoofeed.Feed()
            yahooFeed.addBarsFromCSV("orcl", common.get_data_file_path("orcl-2000-yahoofinance.csv"), marketsession.USEquities.timezone)
            yahooFeed.addBarsFromCSV("orcl", common.get_data_file_path("orcl-2001-yahoofinance.csv"), marketsession.USEquities.timezone)

            # Fill the database using the bars from the Yahoo! feed.
            sqliteFeed = tmpFeed.getFeed()
            sqliteFeed.getDatabase().addBarsFromFeed(yahooFeed)

            # Load the SQLite feed and process all bars.
            sqliteFeed.loadBars("orcl")
            for bars in sqliteFeed:
                pass

            # Check that both dataseries have the same bars.
            yahooDS = yahooFeed["orcl"]
            sqliteDS = sqliteFeed["orcl"]
            self.assertEqual(len(yahooDS), len(sqliteDS))
            for i in xrange(len(yahooDS)):
                self.assertEqual(yahooDS[i].getDateTime(), sqliteDS[i].getDateTime())
                self.assertEqual(yahooDS[i].getOpen(), sqliteDS[i].getOpen())
                self.assertEqual(yahooDS[i].getHigh(), sqliteDS[i].getHigh())
                self.assertEqual(yahooDS[i].getLow(), sqliteDS[i].getLow())
                self.assertEqual(yahooDS[i].getClose(), sqliteDS[i].getClose())
                self.assertEqual(yahooDS[i].getAdjClose(), sqliteDS[i].getAdjClose())
                self.assertEqual(yahooDS[i].getBarsTillSessionClose(), sqliteDS[i].getBarsTillSessionClose())
                self.assertEqual(yahooDS[i].getSessionClose(), sqliteDS[i].getSessionClose())
Beispiel #15
0
def main(plot):
    instrument = "yhoo"
    bBandsPeriod = 40

    # Download the bars.
    # feed = yahoofinance.build_feed([instrument], 2011, 2012, ".")
    feed = yahoofeed.Feed()
    feed.addBarsFromCSV(instrument, "dat\\yhoo-201x.csv")

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

    if plot:
        mpl.style.use('seaborn-whitegrid')
        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()
def write_intermediate_csv(instrument, csvFiles, csvToUpload):
    csvToUpload.write("key,instrument,barType,dateTime,open_,close_,high,low,volume,adjClose\n")

    instrument = instrument.upper()
    barType = 1

    feed = yahoofeed.Feed()
    for csvFile in csvFiles:
        print "Loading bars from %s" % csvFile
        feed.addBarsFromCSV(instrument, csvFile)

    print "Writing intermediate csv into %s" % csvToUpload.name
    for dateTime, bars in feed:
        bar = bars[instrument]
        csvToUpload.write("%s,%s,%d,%s,%s,%s,%s,%s,%s,%s\n" % (
            gen_bar_key(instrument, barType, bar),
            instrument,
            barType,
            datetimeToCSV(bar.getDateTime()),
            bar.getOpen(),
            bar.getClose(),
            bar.getHigh(),
            bar.getLow(),
            bar.getVolume(),
            bar.getAdjClose()
            ))
    csvToUpload.flush()
 def __getFeed(self):
     # Load the feed and process all bars.
     barFeed = yahoofeed.Feed()
     barFeed.addBarsFromCSV(
         VWAPTestCase.Instrument,
         common.get_data_file_path("orcl-2001-yahoofinance.csv"))
     return barFeed
Beispiel #18
0
    def __init__(self, start=None, end=None):
        ''' load all the ashare feed'''
        project_root_dir = os.path.dirname(
            os.path.dirname(os.path.abspath(__file__)))
        data_root_dir = os.path.join(project_root_dir, "data", "history")
        feed = yahoofeed.Feed()
        for _, _, filenames in os.walk(data_root_dir):
            for filename in filenames:
                if os.path.splitext(filename)[1] == '.csv':
                    stock_code = os.path.splitext(filename)[0]
                    csvfile = os.path.join(data_root_dir, filename)
                    feed.addBarsFromCSV(stock_code, csvfile)
        strategy.BacktestingStrategy.__init__(self, feed)
        self.setUseAdjustedValues(True)
        self._feed = self.getFeed()
        self._universe = []
        self._start_date = None
        self._end_date = None
        if start is not None:
            self._start_date = datetime.datetime.strptime(start, '%Y-%m-%d')
        if end is not None:
            self._end_date = datetime.datetime.strptime(end, '%Y-%m-%d')

        self.__instruments = self._feed.getRegisteredInstruments()
        self.__sma = {}
        self.__prices = {}
        self.__position = {}
        'add the techical indectitor to the feed'
        for instrument in self.__instruments:
            self.__sma[instrument] = ma.SMA(
                self._feed[instrument].getCloseDataSeries(), 15)
            self.__prices[instrument] = self._feed[
                instrument].getPriceDataSeries()
            self.__position[instrument] = None
Beispiel #19
0
    def testResampledBarFeed(self):
        barFeed = yahoofeed.Feed()
        barFeed.addBarsFromCSV(
            "spy", common.get_data_file_path("spy-2010-yahoofinance.csv"))
        barFeed.addBarsFromCSV(
            "nikkei",
            common.get_data_file_path("nikkei-2010-yahoofinance.csv"))
        resampledBarFeed = resampled_bf.ResampledBarFeed(
            barFeed, bar.Frequency.MONTH)

        disp = dispatcher.Dispatcher()
        disp.addSubject(barFeed)
        disp.addSubject(resampledBarFeed)
        disp.run()

        weeklySpyBarDS = resampledBarFeed["spy"]
        weeklyNikkeiBarDS = resampledBarFeed["nikkei"]

        # Check first bar
        self.assertEqual(weeklySpyBarDS[0].getDateTime().date(),
                         datetime.date(2010, 1, 1))
        self.assertEqual(weeklyNikkeiBarDS[0].getDateTime().date(),
                         datetime.date(2010, 1, 1))

        # Check last bar
        self.assertEqual(weeklySpyBarDS[-1].getDateTime().date(),
                         datetime.date(2010, 11, 1))
        self.assertEqual(weeklyNikkeiBarDS[-1].getDateTime().date(),
                         datetime.date(2010, 11, 1))
def main(plot):
    instruments = ["gld/USD", "gdx/USD"]
    priceCurrency = "USD"
    initialBalance = {priceCurrency: 1000000}
    windowSize = 50

    # Load the bars. These files were manually downloaded from Yahoo Finance.
    feed = yahoofeed.Feed()
    for year in range(2006, 2012 + 1):
        for instrument in instruments:
            symbol = instrument.split("/")[0]
            fileName = "%s-%d-yahoofinance.csv" % (symbol, year)
            print("Loading bars from %s" % fileName)
            feed.addBarsFromCSV(instrument, fileName)

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

    if plot:
        from pyalgotrade import plotter

        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()
Beispiel #21
0
def runStrategy():
    # 下载数据
    jdf = ts.get_k_data("000725")

    # 新建Adj Close字段
    jdf["Adj Close"] = jdf.close

    # 将tushare下的数据的字段保存为pyalgotrade所要求的数据格式
    jdf.columns = [
        "Date", "Open", "Close", "High", "Low", "Volume", "code", "Adj Close"
    ]

    # 将数据保存成本地csv文件
    jdf.to_csv("jdf.csv", index=False)

    feed = yahoofeed.Feed()
    feed.addBarsFromCSV("jdf", "jdf.csv")

    myStrategy = MyStrategy(feed, "jdf")

    returnsAnalyzer = returns.Returns()
    myStrategy.attachAnalyzer(returnsAnalyzer)
    plt = plotter.StrategyPlotter(myStrategy)
    plt.getInstrumentSubplot("jdf")
    plt.getOrCreateSubplot("returns").addDataSeries(
        "Simple returns", returnsAnalyzer.getReturns())

    myStrategy.run()
    print("Final portfolio value: $%.2f" % myStrategy.getResult())
    plt.plot()
 def testLocal(self):
     barFeed = yahoofeed.Feed()
     instrument = "orcl"
     barFeed.addBarsFromCSV(instrument, common.get_data_file_path("orcl-2000-yahoofinance.csv"))
     res = local.run(sma_crossover.SMACrossOver, barFeed, parameters_generator(instrument, 5, 100))
     self.assertEquals(round(res.getResult(), 2), 1295462.6)
     self.assertEquals(res.getParameters()[1], 20)
Beispiel #23
0
def run_strategy(index, startYear, endYear, smaShort, smaLong):

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

    myStrategy = MyStrategy(feed, index, smaShort, smaLong)
    myStrategy.run()

    # Important! Otherwise the Benchmark won't run (nor fail)
    feed.reset()

    myBenchmark = MyBenchmark(feed, index, smaShort, smaLong)
    myBenchmark.run()

    retStrategy = myStrategy.getBroker().getEquity()
    retBenchmark = myBenchmark.getBroker().getEquity()

    return [
        str(startYear) + "-" + str(endYear), retStrategy, retBenchmark,
        (retStrategy - retBenchmark)
    ]
Beispiel #24
0
def main(plot):
    #--------数据格式转换,常用国内A股数据,转换为yahoo财经格式
    cod = "002739"
    #万达院线
    cname = 'wanda'
    fss = "dat\\" + cod + ".csv"
    df = pd.read_csv(fss, encoding='gbk')
    df2 = zwx.df2yhaoo(df)
    cfn = "dat\\" + cod + "_yh.csv"
    print(fss)
    df2.to_csv(cfn, encoding='utf-8')
    #------------
    #instrument = "aapl",使用新变量名cname替代
    #smaPeriod = 163
    smaPeriod = 20

    # Download the bars.
    #feed = yahoofinance.build_feed([instrument], 2011, 2012, ".")
    feed = yahoofeed.Feed()
    feed.addBarsFromCSV(cname, cfn)

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

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

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

    if plot:
        plt.plot()
Beispiel #25
0
    def testOneBarReturn(self):
        initialCash = 1000
        barFeed = yahoofeed.Feed()
        barFeed.setBarFilter(
            csvfeed.DateRangeFilter(datetime.datetime(2001, 12, 07),
                                    datetime.datetime(2001, 12, 07)))
        barFeed.addBarsFromCSV(
            AnalyzerTestCase.TestInstrument,
            common.get_data_file_path("orcl-2001-yahoofinance.csv"))
        strat = strategy_test.TestStrategy(barFeed, initialCash)

        # 2001-12-07,15.74,15.95,15.55,15.91,42463200,15.56
        # Manually place the orders to get them filled on the first (and only) bar.
        order = strat.getBroker().createMarketOrder(
            broker.Order.Action.BUY, AnalyzerTestCase.TestInstrument, 1,
            False)  # Open: 15.74
        strat.getBroker().submitOrder(order)
        order = strat.getBroker().createMarketOrder(
            broker.Order.Action.SELL, AnalyzerTestCase.TestInstrument, 1,
            True)  # Close: 15.91
        strat.getBroker().submitOrder(order)

        stratAnalyzer = returns.Returns()
        strat.attachAnalyzer(stratAnalyzer)
        strat.run()
        self.assertTrue(strat.getBroker().getCash() == initialCash +
                        (15.91 - 15.74))

        finalValue = 1000 - 15.74 + 15.91
        rets = (finalValue - initialCash) / float(initialCash)
        self.assertEqual(stratAnalyzer.getReturns()[-1], rets)
Beispiel #26
0
def main(plot):
    instrument = "DIA"
    entrySMA = 200
    exitSMA = 5
    rsiPeriod = 2
    overBoughtThreshold = 90
    overSoldThreshold = 10

    # Download the bars.
    #feed = yahoofinance.build_feed([instrument], 2009, 2012, ".")
    feed = yahoofeed.Feed()
    feed.addBarsFromCSV(instrument, "dat\\dia-201x.csv")

    strat = rsi2.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()
    print "Sharpe ratio: %.2f" % sharpeRatioAnalyzer.getSharpeRatio(0.05)

    if plot:
        plt.plot()
Beispiel #27
0
    def testFirstBar(self):
        initialCash = 1000
        barFeed = yahoofeed.Feed()
        barFeed.addBarsFromCSV(
            AnalyzerTestCase.TestInstrument,
            common.get_data_file_path("orcl-2001-yahoofinance.csv"))
        strat = strategy_test.TestStrategy(barFeed, initialCash)

        strat.addOrder(datetime.datetime(2001, 01, 02),
                       strat.getBroker().createMarketOrder,
                       broker.Order.Action.BUY,
                       AnalyzerTestCase.TestInstrument, 1,
                       False)  # 2001-01-03 Open: 25.25 Close: 32.00

        stratAnalyzer = returns.Returns()
        strat.attachAnalyzer(stratAnalyzer)
        strat.run()
        self.assertEqual(stratAnalyzer.getReturns()[0], 0)
        self.assertEqual(stratAnalyzer.getReturns()[1], (32.00 - 25.25) / 1000)

        # Check date times.
        datetimes = barFeed[AnalyzerTestCase.TestInstrument].getDateTimes()
        for i in [0, -1]:
            self.assertEqual(stratAnalyzer.getReturns().getDateTimes()[i],
                             datetimes[i])
            self.assertEqual(
                stratAnalyzer.getCumulativeReturns().getDateTimes()[i],
                datetimes[i])
Beispiel #28
0
def vwap(plot):
    """
    组合管理示例
    :param plot:
    :return:
    """
    instrument = ["lenovo", "mi"]
    vwapWindowSize = 5
    threshold = 0.01
    # Download the bars.
    feed = yahoofeed.Feed()
    feed.addBarsFromCSV("lenovo", "../../api/stock/csv/600847.csv")
    feed.addBarsFromCSV("mi", "../../api/stock/csv/600848.csv")

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

    if plot:
        plt = plotter.StrategyPlotter(strat, True, True, True)
        # plt.getPortfolioSubplot().addDataSeries("vwap", strat.getVWAP()[instrument[-1]])
    ds = pyalg_utils.dataSet(strat)  # 抽取交易数据集语句,若使用系统自带画图功能则不需要该项
    strat.run()
    print("Sharpe ratio: %.2f" % sharpeRatioAnalyzer.getSharpeRatio(0.05))

    if plot:
        plt.plot()

    rs = ds.getReturns()  # 获取默认的交易信息,dic格式,可忽略
Beispiel #29
0
def run_strategy(smaPeriod):
    feed = yahoofeed.Feed()
    feed.addBarsFromCSV("fb", "fb.csv")

    myStrategy = MyStrategy(feed, "fb", smaPeriod)
    myStrategy.run()
    print "Final portfolio value: $%.2f" % myStrategy.getBroker().getEquity()
Beispiel #30
0
    def testSetSharesWithNoStartingCash(self):
        barFeed = yahoofeed.Feed()
        barFeed.addBarsFromCSV(
            AnalyzerTestCase.TestInstrument,
            common.get_data_file_path("orcl-2001-yahoofinance.csv"))

        strat = test_strategy.BacktestingStrategy(barFeed, 0)

        initialShares = 2
        initialPrice = 16.25
        strat.getBroker().setShares(AnalyzerTestCase.TestInstrument,
                                    initialShares, initialPrice)

        # Close initial position
        closingPrice = 32.50
        strat.scheduleCall(
            datetime.datetime(2001, 1, 4), lambda: strat.marketOrder(
                AnalyzerTestCase.TestInstrument, -initialShares))

        stratAnalyzer = returns.Returns()
        strat.attachAnalyzer(stratAnalyzer)
        strat.run()

        self.assertEqual(
            strat.getBroker().getShares(AnalyzerTestCase.TestInstrument), 0)
        self.assertEqual(strat.getBroker().getCash(),
                         closingPrice * initialShares)

        # Check period returns.
        expectedPeriodReturns = [
            (26.37 - initialPrice) / initialPrice,
            (32.00 - 26.37) / 26.37,
            (32.56 - 32.00) / 32.00,
            (32.50 - 32.56) / 32.56,
            0,
            # Nothing should change moving forward
            0,
            0,
        ]
        for i, expectedReturn in enumerate(expectedPeriodReturns):
            self.assertEqual(stratAnalyzer.getReturns()[i], expectedReturn)
        self.assertEqual(stratAnalyzer.getReturns()[-1],
                         expectedPeriodReturns[-1])

        # Check cumulative returns.
        expectedCumulativeReturns = [
            (26.37 - initialPrice) / initialPrice,
            (32.00 - initialPrice) / initialPrice,
            (32.56 - initialPrice) / initialPrice,
            (32.50 - initialPrice) / initialPrice,
            # Nothing should change moving forward
            (32.50 - initialPrice) / initialPrice,
            (32.50 - initialPrice) / initialPrice,
        ]
        for i, expectedReturn in enumerate(expectedCumulativeReturns):
            self.assertEqual(round(stratAnalyzer.getCumulativeReturns()[i], 4),
                             round(expectedReturn, 4))
        self.assertEqual(round(stratAnalyzer.getCumulativeReturns()[-1], 4),
                         round(expectedCumulativeReturns[-1], 4))