Пример #1
0
def main():
    strat = thrSMA
    instrument = '600288'
    paras = [2, 20, 60, 10]

    feeds = tushare.build_feed([instrument], 2016, 2017, "histdata/tushare")
    strat = strat(feeds, instrument, *paras)

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

    plter = plotter.StrategyPlotter(strat, True, True, True)
    strat.run()
    plter.plot()

    # 夏普率
    sharp = sharpeRatioAnalyzer.getSharpeRatio(0.05)

    # 最大回撤
    maxdd = drawDownAnalyzer.getMaxDrawDown()

    # 收益率
    return_ = retAnalyzer.getCumulativeReturns()[-1]

    # 收益曲线
    return_list = []

    for item in retAnalyzer.getCumulativeReturns():
        return_list.append(item)
Пример #2
0
    def testDownloadAndParseDaily(self):
        instrument = "orcl"
        barFeed = yahoofeed.Feed()
        barFeed.addBarsFromCSV(
            instrument,
            common.get_data_file_path("orcl-2000-yahoofinance.csv"))

        strat = sma_crossover.SMACrossOver(barFeed, instrument, 20)

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

        strat.run()

        with common.TmpDir() as tmpPath:
            fig, subplots = plt.buildFigureAndSubplots()

            self.assertIsNotNone(fig)
            self.assertIsNotNone(subplots)

            # fig = plt.buildFigure()
            fig, _ = plt.buildFigureAndSubplots()
            fig.set_size_inches(10, 8)

            png = os.path.join(tmpPath, "plotter_test.png")
            fig.savefig(png)
Пример #3
0
def main():
    '''
    策略执行
    :return:
    '''
    instrument = "600036"
    feeds = mootdx.build_feed([instrument], 2008, 2018, "histdata/mootdx")

    # 3.实例化策略
    strat = MyStrategy(feeds, instrument)

    # 4.设置指标和绘图
    ratio = sharpe.SharpeRatio()
    strat.attachAnalyzer(ratio)
    # plter = plotter.StrategyPlotter(strat)

    # 4.设置指标和绘图
    draws = drawdown.DrawDown()
    strat.attachAnalyzer(draws)

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

    plter = plotter.StrategyPlotter(strat)

    # 5.运行策略
    strat.run()
    strat.info("最终收益: {}".format(strat.getResult()))

    # 6.输出夏普率、绘图
    strat.info("夏普比率: {}".format(ratio.getSharpeRatio(0)))
    strat.info("最大回撤: {}".format(draws.getMaxDrawDown()))
    strat.info("回撤时间: {}".format(draws.getLongestDrawDownDuration()))
    plter.plot()
Пример #4
0
def main(plot):
    import coloredlogs
    coloredlogs.install(level='DEBUG',
                        fmt='[%(asctime)s] %(levelname)s %(message)s')

    instrument = "600036"
    bBandsPeriod = 40

    feeds = mootdx.build_feed([instrument], 2003, 2018, "histdata/mootdx")
    strat = BBands(feeds, 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()
Пример #5
0
def main(plot):
    instruments = [
        "GORO",
    ]
    windowSize = 50

    # Download the bars.
    feed = quandl.build_feed('WIKI', 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()
Пример #6
0
def testStrategy():
    instrument = '600288'
    frequency = bar.Frequency.TRADE
    fromDate = '20160815'
    toDate = '20160820'
    strat = OrderBook

    paras = [5, 20]
    plot = True

    from mooquant.tools import tushare
    feeds = tushare.build_feed([instrument], 2016, 2017, "histdata/tushare")
    strat = strat(feeds, instrument, *paras)

    retAnalyzer = returns.Returns()
    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, True, True)

    strat.run()

    if plot:
        plt.plot()

    # 夏普率
    sharp = sharpeRatioAnalyzer.getSharpeRatio(0.05)

    # 最大回撤
    maxdd = drawDownAnalyzer.getMaxDrawDown()

    # 收益率
    return_ = retAnalyzer.getCumulativeReturns()[-1]

    # 收益曲线
    return_list = []

    for item in retAnalyzer.getCumulativeReturns():
        return_list.append(item)
Пример #7
0
def main():
    instruments = ["GORO"]

    # Download GORO bars using WIKI source code.
    feed = quandl.build_feed("WIKI", instruments, 2006, 2012, "./histdata")
    quandlFeed = csvfeed.Feed("Date", "%Y-%m-%d")
    quandlFeed.setDateRange(datetime.datetime(2006, 1, 1),
                            datetime.datetime(2012, 12, 31))
    quandlFeed.addValuesFromCSV("histdata/quandl_gold_2.csv")

    strat = MyStrategy(feed, quandlFeed, instruments[0])
    plter = plotter.StrategyPlotter(strat, True, False, False)

    plter.getOrCreateSubplot("quandl").addDataSeries("USD", quandlFeed["USD"])
    plter.getOrCreateSubplot("quandl").addDataSeries("EUR", quandlFeed["EUR"])
    plter.getOrCreateSubplot("quandl").addDataSeries("GBP", quandlFeed["GBP"])

    strat.run()
    plter.plot()
Пример #8
0
def main(plot):
    instrument = '600016'
    vwapWindowSize = 5
    threshold = 0.01

    feeds = tushare.build_feed([instrument], 2010, 2018, './histdata/tushare')
    strat = VWAPMomentum(feeds, instrument, vwapWindowSize, threshold)

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

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

    strat.run()

    strat.info("Sharpe ratio: %.2f" % sharpeRatioAnalyzer.getSharpeRatio(0.05))
    plter.plot()
Пример #9
0
def main():
    instruments = ["600036"]
    feeds = mootdx.build_feed(instruments, 2003, 2018, "histdata/mootdx")

    # 3.实例化策略
    strat = Strategy(feeds, instruments[0])

    # 4.设置指标和绘图
    ratio = sharpe.SharpeRatio()
    strat.attachAnalyzer(ratio)
    plter = plotter.StrategyPlotter(strat)

    # 5.运行策略
    strat.run()
    strat.info("最终收益: %.2f" % strat.getResult())

    # 6.输出夏普率、绘图
    strat.info("夏普比率: " + str(ratio.getSharpeRatio(0)))
    plter.plot()
Пример #10
0
def main(plot):
    instrument = "BTC"
    initialCash = 1000
    vwapWindowSize = 100
    buyThreshold = 0.02
    sellThreshold = 0.01

    barFeed = csvfeed.GenericBarFeed(bar.Frequency.MINUTE * 30)
    barFeed.addBarsFromCSV(instrument, "./tests/data/30min-bitstampUSD.csv")
    brk = broker.BacktestingBroker(initialCash, barFeed)
    strat = VWAPMomentum(barFeed, brk, instrument, vwapWindowSize, buyThreshold, sellThreshold)

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

    strat.run()

    if plot:
        plt.plot()
Пример #11
0
def main(plot):
    instrument = "600016"
    smaPeriod = 163

    feed = tushare.build_feed([instrument], 2011, 2012, "./histdata/tushare")
    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()
Пример #12
0
def main(plot):
    instrument = "600036"
    vwapWindowSize = 5
    threshold = 0.01

    # Download the bars.
    feed = tushare.build_feed([instrument], 2011, 2012, "./tests/data")

    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()
Пример #13
0
def main(plot=False):
    instruments = ["600036"]
    bBandsPeriod = 20

    feeds = tushare.build_feed(instruments, 2017, 2018, "./tests/data")
    strat = BBandsStrategy(feeds, instruments[0], bBandsPeriod)
    sharp = sharpe.SharpeRatio()
    strat.attachAnalyzer(sharp)

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

    strat.run()

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

    if plot:
        plt.plot()
Пример #14
0
def main(plot):
    instrument = "600016"
    entrySMA = 150
    exitSMA = 5
    rsiPeriod = 3
    overBoughtThreshold = 93
    overSoldThreshold = 25

    # Download the bars.
    # feed = quandl.build_feed("WIKI", [instrument], 2009, 2012, "./data")
    # feeds = yahoofeed.Feed()
    # feeds.addBarsFromCSV("dia", "./tests/data/DIA-2009-yahoofinance.csv")
    # feeds.addBarsFromCSV("dia", "./tests/data/DIA-2010-yahoofinance.csv")
    # feeds.addBarsFromCSV("dia", "./tests/data/DIA-2011-yahoofinance.csv")

    # instruments = ["600036"]

    feeds = tushare.build_feed([instrument], 2009, 2011, "histdata/mootdx")

    strat = RSI2(feeds, 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("夏普比率: %.2f" % sharpeRatioAnalyzer.getSharpeRatio(0.05))

    if plot:
        plt.plot()
Пример #15
0
def run_strategy():
    # Load the yahoo feed from the CSV file
    feed = GenericBarFeed(Frequency.DAY, None, None)
    feed.addBarsFromCSV("orcl", "2000.csv")

    # commission
    broker_commission = broker.backtesting.TradePercentage(0.002)
    broker_brk = floatBroker(500000, feed, broker_commission)
    # Evaluate the strategy with the feed.
    myStrategy = MyStrategy(feed, "orcl", broker_brk)

    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("SMA60",
                                                   myStrategy.getSMA(60))
    plt.getInstrumentSubplot("orcl").addDataSeries("SMA10",
                                                   myStrategy.getSMA(10))
    plt.getInstrumentSubplot("orcl").addDataSeries("SMA30",
                                                   myStrategy.getSMA(30))
    # Plot the simple returns on each bar.
    plt.getOrCreateSubplot("returns").addDataSeries(
        "Simple returns", returnsAnalyzer.getReturns())

    myStrategy.run()
    print(
        "Final portfolio value: $%.2f %.2f %.2f" %
        (myStrategy.getBroker().getEquity(), myStrategy.getBroker().getCash(),
         myStrategy.getBroker().getShares('orcl')))
    myStrategy.totalEnd()
    #    myStrategy.info("Final portfolio value: $%.2f" % myStrategy.getResult())

    # Plot the strategy.
    plt.plot()
    print(myStrategy.getJSL())
Пример #16
0
from mooquant import plotter
from mooquant.analyzer import returns
from mooquant.tools import tushare

from samples import sma_crossover

if __name__ == '__main__':
    instrument = '600016'

    feeds = tushare.build_feed([instrument], 2016, 2018, './histdata/tushare')
    strat = sma_crossover.SMACrossOver(feeds, instrument, 20)

    # 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("orcl").addDataSeries("SMA", strat.getSMA())
    # 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()
Пример #17
0
def testStrategy():
    from mooquant import bar
    from mooquant import plotter

    strat = fourSMA
    instrument = '600288'
    market = 'SH'
    fromDate = '20150101'
    toDate = '20150601'
    frequency = bar.Frequency.MINUTE
    paras = [2, 20, 60, 10]
    plot = True

    # path set ############################33

    # if frequency == bar.Frequency.MINUTE:
    #     path = os.path.join('..', 'histdata', 'minute')
    # elif frequency == bar.Frequency.DAY:
    #     path = os.path.join('..', 'histdata', 'day')
    # filepath = os.path.join(path, instrument + market + ".csv")

    # don't change ############################33

    # barfeed = Feed(frequency)
    # barfeed.setDateTimeFormat('%Y-%m-%d %H:%M:%S')
    # barfeed.loadBars(instrument, market, fromDate, toDate, filepath)

    # mooquant_id = instrument + '.' + market
    # strat = strat(barfeed, mooquant_id, *paras)
    from mooquant.tools import tushare
    feeds = tushare.build_feed([instrument], 2016, 2017, "histdata/tushare")
    strat = strat(feeds, instrument, *paras)

    retAnalyzer = returns.Returns()
    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, True, True)

    strat.run()

    if plot:
        plt.plot()

    # 夏普率
    sharp = sharpeRatioAnalyzer.getSharpeRatio(0.05)

    # 最大回撤
    maxdd = drawDownAnalyzer.getMaxDrawDown()

    # 收益率
    return_ = retAnalyzer.getCumulativeReturns()[-1]

    # 收益曲线
    return_list = []

    for item in retAnalyzer.getCumulativeReturns():
        return_list.append(item)