Esempio n. 1
0
def bolling(code='600281'):
    try:
        dat = pd.read_csv("../../api/stock/csv/%sSH_5min.csv" % code,
                          encoding='gbk')
        dat = dat.fillna(method='pad')
        dat['Adj Close'] = dat['Close']
        dat = dat.rename(
            columns={
                'Open': 'open',
                'High': 'high',
                'Volume': 'volume',
                'Close': 'close',
                'Low': 'low'
            })
        dat.index = dat['Date Time']
        dat.index.name = 'date'
    except:
        from api.stock.lib import gm_api as gm
        dat = gm.gm_api().get_hist_data(code, '2015-01-01', ktype='5')
        print(dat)
        dat['Adj Close'] = dat['close']

    # dat = dat.ix[17000:18000,:]
    feed = dataFramefeed.Feed(frequency=bar.Frequency.MINUTE)
    feed.addBarsFromDataFrame("orcl", dat)

    myStrategy = mdd.bolling_backtest(feed, 'orcl')
    sharpeRatioAnalyzer = sharpe.SharpeRatio()
    myStrategy.attachAnalyzer(sharpeRatioAnalyzer)

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

    ds = pyalg_utils.dataSet(myStrategy)  # 抽取交易数据集语句,若使用系统自带画图功能则不需要该项
    myStrategy.run()
    plt.plot()

    print('最大回撤:\t%f\t 交易笔数:\t%d\t 盈利笔数:\t%d\n' %
          (ds.getMaxDrawDown(), ds.getCount(), ds.getProfitableCount()))
    print('累计收益:\t%f\t 夏普比率:\t%f\t' %
          (returnsAnalyzer.getCumulativeReturns()[-1], ds.getSharpeRatio()))
Esempio n. 2
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") is 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))
Esempio n. 3
0
def run_strategy(paras):
    feed = dataframefeed.Feed()
    feed.addBarsFromDataFrame(instrument, dat)
    strat = singleMA.SingleMA(feed, instrument, paras, initialCash)

    # attach analyzersgc
    returnsAnalyzer = returns.Returns()
    strat.attachAnalyzer(returnsAnalyzer)
    drawdownAnalyzer = drawdown.DrawDown()
    strat.attachAnalyzer(drawdownAnalyzer)
    sharpeRatioAnalyzer = sharpe.SharpeRatio()
    strat.attachAnalyzer(sharpeRatioAnalyzer)
    tradeAnalyzer = trades.Trades()
    strat.attachAnalyzer(tradeAnalyzer)

    strat.run()
    print "Final portfolio value: $%.2f with paras %d" % (
        strat.getBroker().getEquity(), paras)
    return {
        'returns':
        returnsAnalyzer.getCumulativeReturns()[-1],
        'drawdown':
        drawdownAnalyzer.getMaxDrawDown(),
        'longestDrawDownDuration':
        drawdownAnalyzer.getLongestDrawDownDuration(),
        'sr':
        sharpeRatioAnalyzer.getSharpeRatio(0.03),
        'total trades':
        tradeAnalyzer.getCount(),
        'win':
        tradeAnalyzer.getProfitableCount(),
        'lose':
        tradeAnalyzer.getUnprofitableCount(),
        'average win profit':
        tradeAnalyzer.getPositiveReturns().mean(),
        'average lose loss':
        tradeAnalyzer.getNegativeReturns().mean(),
        'wining ratio':
        tradeAnalyzer.getProfitableCount() / tradeAnalyzer.getCount(),
        'odds':
        -tradeAnalyzer.getPositiveReturns().mean() /
        tradeAnalyzer.getNegativeReturns().mean()
    }
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()
Esempio n. 5
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 = "yhoo" #使用新变量名cname替代
    #bBandsPeriod = 40
    bBandsPeriod = 10

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

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

    if plot:
        mpl.style.use('seaborn-whitegrid')
        plt = plotter.StrategyPlotter(strat, True, True, True)
        plt.getInstrumentSubplot(cname).addDataSeries(
            "upper",
            strat.getBollingerBands().getUpperBand())
        plt.getInstrumentSubplot(cname).addDataSeries(
            "middle",
            strat.getBollingerBands().getMiddleBand())
        plt.getInstrumentSubplot(cname).addDataSeries(
            "lower",
            strat.getBollingerBands().getLowerBand())

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

    if plot:
        plt.plot()
Esempio n. 6
0
def main():
    instruments = ["000651"]
    feeds = tools.build_feed(instruments, 2009, 2019, "histdata")

    # 3.实例化策略
    strat = MyStrategy(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()
Esempio n. 7
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()
Esempio n. 8
0
def main(plot):
    bBandsPeriod = 40

    start = datetime(2000, 1, 1, 0, 0, 0, 0, pytz.utc)
    end = datetime(2015, 7, 1, 0, 0, 0, 0, pytz.utc)
    data = web.DataReader('DEXJPUS', 'fred', start, end)

    frslt = open('./hoge.csv', 'w')
    frslt.write("Date,Open,High,Low,Close,Volume,Adj Close\n")
    for k, v in data["DEXJPUS"].iteritems():
        if v != v:  # if nan
            continue

        frslt.write(str(k) + "," + str(v) + "," + \
                    str(v) + "," + str(v) + \
                    "," + str(v) + ",1000000,"+ str(v) + "\n")
    frslt.close()

    instrument = "USDJPY"
    feed = yahoofeed.Feed()
    feed.addBarsFromCSV(instrument, "./hoge.csv")
    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()
Esempio n. 9
0
def main(plot):
    initialCash = 10000
    instrumentsByClass = {
        # "bitmex_LTCZ18": ["bitmex_LTCZ18"],
        "okex_LIGHTBTC": ["okex_LIGHTBTC"],
        "binance_ADABTC": ["binance_ADABTC"],
    }

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

    instrument = "bitmex_LTCZ18"
    feed = Feed(Frequency.MINUTE)
    # feed.loadBars(instrument, test_back=True)
    feed.loadBars('okex_LIGHTBTC', test_back=True)
    feed.loadBars("binance_ADABTC", test_back=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()
Esempio n. 10
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()
Esempio n. 11
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()
Esempio n. 12
0
def run_strategy(smaPeriod):
    # Evaluate the strategy with the feed.
    # Load the yahoo feed from the CSV file
    feed = yahoofeed.Feed()
    feed.addBarsFromCSV("zggf", "E:/PythonData/CSV/000938.csv")
    myStrategy = MyStrategy(feed, "zggf", smaPeriod)
    myStrategy2 = sma_crossover.SMACrossOver(feed, "zggf", smaPeriod)
    plt = plotter.StrategyPlotter(myStrategy)
    plt.getInstrumentSubplot("zggf").addDataSeries("SMA", myStrategy2.getSMA())
    sharpe_ratio = sharpe.SharpeRatio()
    trade_situation = trades.Trades()
    myStrategy.attachAnalyzer(sharpe_ratio)
    myStrategy.attachAnalyzer(trade_situation)
    myStrategy.run()
    print("Final portfolio value: $%.2f" % myStrategy.getBroker().getEquity())
    print("sharpe_ratio", sharpe_ratio.getSharpeRatio(0))
    print("total number of trades", trade_situation.getCount())
    print("Profit times number of trades ",
          trade_situation.getProfitableCount())
    plt.plot()
Esempio n. 13
0
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")
    def testSharpeRatioIGE_SPY_Broker(self):
        # 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"))
        barFeed.addBarsFromCSV(
            "spy", common.get_data_file_path("sharpe-ratio-test-spy.csv"))
        strat = strategy_test.TestStrategy(barFeed, 1000)
        strat.getBroker().setUseAdjustedValues(True)
        strat.setBrokerOrdersGTC(True)
        stratAnalyzer = sharpe.SharpeRatio()
        strat.attachAnalyzer(stratAnalyzer)

        # Manually place IGE 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(datetime.datetime(2007, 11, 13),
                       strat.getBroker().createMarketOrder,
                       broker.Order.Action.SELL, "ige", 1,
                       True)  # Adj. Close: 127.64

        # Manually place SPY order to get it filled on the first bar.
        order = strat.getBroker().createMarketOrder(
            broker.Order.Action.SELL_SHORT, "spy", 1,
            True)  # Adj. Close: 105.52
        order.setGoodTillCanceled(True)
        strat.getBroker().placeOrder(order)
        strat.addOrder(datetime.datetime(2007, 11, 13),
                       strat.getBroker().createMarketOrder,
                       broker.Order.Action.BUY_TO_COVER, "spy", 1,
                       True)  # Adj. Close: 147.67

        strat.run()
        self.assertTrue(
            round(strat.getBroker().getCash(), 2) == round(
                1000 + (127.64 - 42.09) + (105.52 - 147.67), 2))
        self.assertTrue(strat.getOrderUpdatedEvents() == 4)
Esempio n. 15
0
def kdj(param=[14, 3, 0, 3, 0, 70, 30]):
    # dat = ts.get_k_data("000001", start='2006-07-01', end='2017-01-05', index=True)
    # dat.to_csv("000001.csv",encoding='gbk',index=False)
    dat = pd.read_csv("../../api/stock/csv/000001.csv", encoding='gbk', parse_dates=[0], index_col=0)
    dat = dat.fillna(method='pad')
    dat['Adj Close'] = dat['close']
    dat.index.name = 'date'
    dat = dat[['open', 'close', 'high', 'low', 'volume', 'Adj Close']]  # the index catch high<open in 2010-02-01

    def handle_data(x):
        if x[2] < x[0]:
            x[2] = x[0]
        if x[3] > x[0]:
            x[3] = x[0]
        return x

    dat = dat.apply(handle_data, axis=1)
    # print dat.head()

    feed = dataFramefeed.Feed()
    feed.addBarsFromDataFrame("orcl", dat)

    myStrategy = kdj_backtest(feed, 'orcl', param=param,
                              df=BBcurve2.BBcurve(data=dat,plot=False))  # set the param of STOCH and crossover
    sharpeRatioAnalyzer = sharpe.SharpeRatio()
    myStrategy.attachAnalyzer(sharpeRatioAnalyzer)

    returnsAnalyzer = returns.Returns()
    myStrategy.attachAnalyzer(returnsAnalyzer)
    plt = plotter.StrategyPlotter(myStrategy, True, True, True)
    plt.getOrCreateSubplot("returns").addDataSeries("Simple returns", returnsAnalyzer.getReturns())
    ds = pyalg_utils.dataSet(myStrategy)  # 抽取交易数据集语句,若使用系统自带画图功能则不需要该项
    myStrategy.run()
    plt.plot()

    # slowk,slowd = talib.STOCH(dat.high.values,dat.low.values,dat.close.values,14,3,0,3,0)
    # print slowk[-1],slowd[-1]
    print('drawndown:\t%f\t tradingCount:\t%d\t profitCount:\t%d\n' % (
    ds.getMaxDrawDown(), ds.getCount(), ds.getProfitableCount()))
    print('culmutiveReturn:\t%f\t sharpRatio:\t%f\t' % (
    returnsAnalyzer.getCumulativeReturns()[-1], ds.getSharpeRatio()))
Esempio n. 16
0
def main():
    instrument = "aapl"
    vwapWindowSize = 5
    threshold = 0.01

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

    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)

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

    strat.run()
    plt.plot()

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

    # ===
    fss = 'tmp\k408vwap_dret.csv'
    xs1 = ret2csv(fss, retAnalyzer)
Esempio n. 17
0
def main(plot):
    instrument = "AMD"  #"orcl"
    bBandsPeriod = 40
    overBoughtThreshold = 70
    overSoldThreshold = 30

    # Download the bars.
    feed = quandlfeed.Feed()
    feed.addBarsFromCSV("AMD", "WIKI-AMD-2016-quandl.csv")

    strat = BBands(feed, instrument, bBandsPeriod, overBoughtThreshold,
                   overSoldThreshold)
    strat.getBroker().setCash(1000)
    sharpeRatioAnalyzer = sharpe.SharpeRatio()
    strat.attachAnalyzer(sharpeRatioAnalyzer)
    start = strat.getBroker().getEquity()

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

    final = strat.getBroker().getEquity()
    print("Net: " + str(final - start))

    if plot:
        plt.plot()
Esempio n. 18
0
def run_Ma_Macd(code, arg_set, ma_short, ma_long, macd_fast, macd_slow):
    result = {}
    feed = yahoofeed.Feed()
    trade = trades.Trades()
    sharpe_ratio = sharpe.SharpeRatio()
    draw_down = drawdown.DrawDown()
    if arg_set == "fixed":
        feed.addBarsFromCSV(code, csv_path + "%s.csv" % code)
    else:
        feed.addBarsFromCSV(code, csv_path + "%s_hfq.csv" % code)
    myStrategy = MyStrategy.Ma_Macd(feed, code, arg_set, ma_short, ma_long,
                                    macd_fast, macd_slow)
    myStrategy.attachAnalyzer(sharpe_ratio)
    myStrategy.attachAnalyzer(draw_down)
    myStrategy.attachAnalyzer(trade)
    plt = plotter.StrategyPlotter(myStrategy)
    myStrategy.run()
    ProfitableCount = trade.getProfitableCount()
    TradeCount = trade.getCount()
    result['code'] = code
    result['final'] = int(myStrategy.getBroker().getEquity())
    result['sharpe'] = "%.2f" % sharpe_ratio.getSharpeRatio(0.04)
    result['draw_back'] = "%.2f %%" % (draw_down.getMaxDrawDown() * 100)
    if TradeCount == 0:
        result['trade'] = 0
        result['suc_rate'] = 0
    else:
        result['trade'] = str(ProfitableCount) + "/" + str(TradeCount)
        result['suc_rate'] = "%.2f" % (float(ProfitableCount) /
                                       float(TradeCount))
    result["arg"] = "%s, %s, %s, %s" % (ma_short, ma_long, macd_fast,
                                        macd_slow)
    result["mode"] = "Ma_Macd"
    result["date"] = datetime.now().strftime('%Y-%m-%d')
    if myStrategy._Ma_Macd__position:
        result['L_state'] = "BUY"
    else:
        result['L_state'] = "SELL"
    if plot_flag:
        plt.plot()
    return result
Esempio n. 19
0
def ENE(type='old', code='600281SH'):
    dat = pd.read_csv("../../api/stock/csv/%s_5min.csv" % code, encoding='gbk')
    dat = dat.fillna(method='pad')
    dat['Adj Close'] = dat['Close']
    dat = dat.rename(
        columns={
            'Open': 'open',
            'High': 'high',
            'Volume': 'volume',
            'Close': 'close',
            'Low': 'low'
        })
    dat.index = dat['Date Time']
    dat.index.name = 'date'

    dat['year'] = dat['Date Time'].map(lambda x: x[0:4])
    # dat = dat.ix[17000:18000,:]
    feed = dataFramefeed.Feed(frequency=bar.Frequency.MINUTE)
    feed.addBarsFromDataFrame("orcl", dat[dat['year'] > '2015'])

    if type == 'macd':
        myStrategy = mdd.ENE_backtest(feed, 'orcl')
    elif type == 'old':
        myStrategy = mdd.ENE_backtest(feed, 'orcl')
    sharpeRatioAnalyzer = sharpe.SharpeRatio()
    myStrategy.attachAnalyzer(sharpeRatioAnalyzer)

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

    ds = pyalg_utils.dataSet(myStrategy)  # 抽取交易数据集语句,若使用系统自带画图功能则不需要该项
    myStrategy.run()
    plt.plot()

    print(u'最大回撤:\t%f\t 交易笔数:\t%d\t 盈利笔数:\t%d\n' %
          (ds.getMaxDrawDown(), ds.getCount(), ds.getProfitableCount()))
    print(u'累计收益:\t%f\t 夏普比率:\t%f\t' %
          (returnsAnalyzer.getCumulativeReturns()[-1], ds.getSharpeRatio()))
Esempio n. 20
0
def main(plot):
    symbol = "DIA"
    priceCurrency = "USD"
    instrument = "%s/%s" % (symbol, priceCurrency)
    entrySMA = 200
    exitSMA = 5
    rsiPeriod = 2
    overBoughtThreshold = 90
    overSoldThreshold = 10
    initialBalance = {priceCurrency: 1000000}

    # Load the bars. These files were manually downloaded from Yahoo Finance.
    feed = yahoofeed.Feed()
    for year in range(2009, 2013):
        fileName = "%s-%d-yahoofinance.csv" % (symbol, year)
        print("Loading bars from %s" % fileName)
        feed.addBarsFromCSV(instrument, fileName)

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

    if plot:
        from pyalgotrade import plotter

        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()
Esempio n. 21
0
    def __init__(self, myStrategy):
        self.myStrategy = myStrategy
        self.tradesAnalyzer = trades.Trades()
        self.myStrategy.attachAnalyzer(self.tradesAnalyzer)

        self.sharpeAnalyzer = sharpe.SharpeRatio()
        self.retAnalyzer = Returns()
        self.myStrategy.attachAnalyzer(self.retAnalyzer)
        self.myStrategy.attachAnalyzer(self.sharpeAnalyzer)
        self.myStrategy.run()
        self.myStrategy.getResult()
        self.retAnalyzer.getCumulativeReturns()
        self.result = self.sharpeAnalyzer.getSharpeRatio(0.025)
        tr = self.tradesAnalyzer.getAllReturns()
        self.streak = 0
        temp_streak = 0
        for i in tr:
            if i > 0:
                temp_streak = temp_streak + 1
            else:
                self.streak = temp_streak if temp_streak > self.streak else self.streak
Esempio n. 22
0
def main(plot):
    #    merge_csv("./hoge.csv", ["./USDJPY_M5_2001.txt","./USDJPY_M5_2002.txt","./USDJPY_M5_2003.txt","./USDJPY_M5_2004.txt",\
    #                             "./USDJPY_M5_2005.txt","./USDJPY_M5_2006.txt","./USDJPY_M5_2007.txt","./USDJPY_M5_2008.txt"])

    instrument = "USDJPY"
    feed = csvfeed.GenericBarFeed(Frequency.MINUTE, pytz.utc)
    feed.addBarsFromCSV(instrument, "./hoge.csv")
    strat = MATrade(feed, instrument)
    sharpeRatioAnalyzer = sharpe.SharpeRatio()
    strat.attachAnalyzer(sharpeRatioAnalyzer)

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

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

    if plot:
        plt.plot()
Esempio n. 23
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()
Esempio n. 24
0
	def __testIGE_BrokerImpl(self, 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, 1000)
		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", quantity, 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", quantity, True) # Adj. Close: 127.64
		strat.run()
		self.assertTrue(round(strat.getBroker().getCash(), 2) == 1000 + (127.64 - 42.09) * quantity)
		self.assertTrue(strat.getOrderUpdatedEvents() == 2)
		# The results are slightly different different only because I'm taking into account the first bar as well.
		self.assertTrue(round(stratAnalyzer.getSharpeRatio(0.04, 252, annualized=True), 4) == 0.7889)
def run_strategy(smaPeriod):
    # Load the yahoo feed from the CSV file
    # feed = yahoofeed.Feed()
    feed = GenericBarFeed(Frequency.DAY, None, None)
    feed.addBarsFromCSV("zggf", "E:\Stock\Data_Day/000831.SZ.csv")
    global myStrategy
    # Evaluate the strategy with the feed.
    myStrategy = MyStrategy(feed, "zggf", smaPeriod)
    plt = plotter.StrategyPlotter(myStrategy)
    sharpe_ratio = sharpe.SharpeRatio()
    trade_situation = trades.Trades()
    myStrategy.attachAnalyzer(sharpe_ratio)
    myStrategy.attachAnalyzer(trade_situation)
    myStrategy.run()
    print("Final portfolio value: $%.2f" % myStrategy.getBroker().getEquity())
    print("sharpe_ratio", sharpe_ratio.getSharpeRatio(0))
    print("total number of trades", trade_situation.getCount())
    print("Profit times number of trades ",
          trade_situation.getProfitableCount())
    print(myStrategy.Sma_price)
    plt.plot()
Esempio n. 26
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()
Esempio n. 27
0
def main(plot):
    from pyalgotrade import bar
    from pyalgotrade import plotter
    instrument = "002665"
    bBandsPeriod = 40
    strat = BBands
    frequency = bar.Frequency.DAY
    plot = True

    # Download the bars.
    from pyalgotrade.barfeed.csvfeed import GenericBarFeed
    barfeed = GenericBarFeed(frequency)
    barfeed.setDateTimeFormat('%Y-%m-%d %H:%M:%S')
    barfeed.addBarsFromCSV("002665", "F:/shuju/002665-barfeed.csv")
    strat = strat(barfeed, instrument, bBandsPeriod)

    strat = BBands(barfeed, 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()
Esempio n. 28
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()
Esempio n. 29
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()
    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.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", 1,
                                                    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", 1,
                       True)  # Adj. Close: 127.64

        strat.run()
        self.assertTrue(
            round(strat.getBroker().getCash(), 2) == initialCash +
            (127.64 - 42.09 - commision * 2))
        self.assertEqual(strat.orderUpdatedCalls, 6)
        # 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)