Exemplo n.º 1
0
def main(code, start_date, end_date):
    data = getData(code, start_date, end_date)
    if data is None: return
    feed = dataFramefeed.Feed()
    feed.addBarsFromDataFrame(code, data)
    # Set Strategy
    brk = genBroker(feed)
    bands = [-0.40, -0.30, -0.20, -0.10, 0.10, 0.20, 0.30, 0.40]
    weights = [1.00, 0.90, 0.70, 0.60, 0.50, 0.35, 0.25, 0.05, 0.00]
    #base_price = np.mean(data.close) * 0.95
    base_day = 10
    myStrategy = GridSearchStrategy(feed, brk, code, base_day, weights, bands)
    # Attach a returns analyzers to the strategy
    returnsAnalyzer = returns.Returns()
    myStrategy.attachAnalyzer(returnsAnalyzer)
    # Attach a sharpe ratio analyzers to the strategy
    sharpeRatioAnalyzer = sharpe.SharpeRatio()
    myStrategy.attachAnalyzer(sharpeRatioAnalyzer)
    # Attach the plotter to the strategy
    plt = plotter.StrategyPlotter(myStrategy, True, True, True)
    plt.getOrCreateSubplot("returns").addDataSeries(
        "Simple returns", returnsAnalyzer.getReturns())
    # Run Strategy
    myStrategy.run()
    myStrategy.info("Final portfolio value: $%.2f" % myStrategy.getResult())
    plt.plot()
Exemplo n.º 2
0
def main(mode = ct.PAPER_TRADING, start_date = '20170815', end_date = '20171113'):
    if mode == ct.PAPER_TRADING:
        cash = 100000
        beta = 9.49
        mean = -0.282
        std  = 34.73
        feed = dataFramefeed.Feed()
        instruments = ['300296', '300613']
        fpath       = '/Users/hellobiek/Documents/workspace/python/quant/smart_deal_tool/configure/tushare.json' 
        ts_client   = get_tushare_client(fpath)
        for code in instruments:
            df = ts.pro_bar(pro_api = ts_client, ts_code = add_suffix(code), adj = 'qfq', start_date = start_date, end_date = end_date)
            df = df.rename(columns = {"ts_code": "code", "trade_date": "date", "vol": "volume", "pct_change": "pchange"})
            df['date'] = df.date.apply(lambda x: time.strftime('%Y-%m-%d', time.strptime(x, "%Y%m%d")))
            df = df.set_index("date")
            feed.addBarsFromDataFrame(code, df)

        # broker setting
        # broker commission类设置
        broker_commission = broker.backtesting.TradePercentage(0.002)
        # fill strategy设置
        fill_stra = broker.fillstrategy.DefaultStrategy(volumeLimit = 1.0)
        sli_stra  = broker.slippage.NoSlippage()
        fill_stra.setSlippageModel(sli_stra)
        # 完善broker类
        brk = broker.backtesting.Broker(cash, feed, broker_commission)
        brk.setFillStrategy(fill_stra)

    pStrategy = PairTradingStrategy(feed, instruments, brk, beta, mean, std, cash)

    returnsAnalyzer = sreturn.Returns()
    pStrategy.attachAnalyzer(returnsAnalyzer)

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

    drawDownAnalyzer = drawdown.DrawDown()
    pStrategy.attachAnalyzer(drawDownAnalyzer)

    tradesAnalyzer = trades.Trades()
    pStrategy.attachAnalyzer(tradesAnalyzer)

    plt = plotter.StrategyPlotter(pStrategy)

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

    pStrategy.run()

    plt.plot()

    print("Final portfolio value: $%.2f" % pStrategy.getResult())
    print("Cumulative returns: %.2f %%" % (returnsAnalyzer.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()))
Exemplo n.º 3
0
def grid_search(code, start_date, end_date):
    data = get_data(code, start_date, end_date)
    if data is None: return
    feed = dataFramefeed.Feed()
    feed.addBarsFromDataFrame(code, data)
    brk = gen_broker(feed)
    local.run(KDJStrategy,
              feed,
              parameters_generator(code, brk, data),
              workerCount=2)
Exemplo n.º 4
0
def get_feed(all_df, codes, start_date, end_date, peried, duaration):
    feed = dataFramefeed.Feed()
    for code in codes:
        data = all_df.loc[all_df.code == code]
        data = data.sort_values(by=['date'], ascending=True)
        data = data.reset_index(drop=True)
        data = data.set_index('date')
        if is_df_has_unexpected_data(data): return None, None
        data.index = pd.to_datetime(data.index)
        data = data.dropna(how='any')
        data = atr(data, ndays=duaration)
        feed.addBarsFromDataFrame(code, data)
    return feed
Exemplo n.º 5
0
def get_feed(all_df, code, start_date, end_date, peried):
    feed = dataFramefeed.Feed()
    #cindex_obj = CIndex(code, dbinfo = ct.OUT_DB_INFO, redis_host = '127.0.0.1')
    #cstock_obj = CStock(code, dbinfo = ct.OUT_DB_INFO, redis_host = '127.0.0.1')
    #data = cstock_obj.get_k_data_in_range(start_date, end_date)
    #data = data.set_index('date')
    data = all_df.loc[all_df.code == code]
    data = data.sort_values(by=['date'], ascending=True)
    data = data.reset_index(drop=True)
    data = data.set_index('date')
    if is_df_has_unexpected_data(data): return None, None
    data.index = pd.to_datetime(data.index)
    data = data.dropna(how='any')
    data = atr(data)
    feed.addBarsFromDataFrame(code, data)
    return feed
Exemplo n.º 6
0
def plate_momentum(mode=ct.PAPER_TRADING,
                   start_date='2018-03-01',
                   end_date='2018-10-28'):
    if mode == ct.PAPER_TRADING:
        threshold = 100000
        feed = dataFramefeed.Feed()
        instruments = choose_plate()
        if len(instruments): return 0
        for code in instruments:
            data = CStock(code,
                          should_create_influxdb=False,
                          should_create_mysqldb=False).get_k_data_in_range(
                              start_date, end_date)
            data = data.set_index('date')
            feed.addBarsFromDataFrame(code, data)

        # broker setting
        # broker commission类设置
        broker_commission = broker.backtesting.TradePercentage(0.002)
        # fill strategy设置
        fill_stra = broker.fillstrategy.DefaultStrategy(volumeLimit=1.0)
        sli_stra = broker.slippage.NoSlippage()
        fill_stra.setSlippageModel(sli_stra)
        # 完善broker类
        brk = broker.backtesting.Broker(threshold * len(instruments), feed,
                                        broker_commission)
        brk.setFillStrategy(fill_stra)

    myStrategy = PlateMomentumStrategy(feed, instruments, brk, threshold)

    # Attach a returns analyzers to the strategy.
    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())

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

    plt.plot()
Exemplo n.º 7
0
def main(code, start_date, end_date):
    data = get_data(code, start_date, end_date)
    if data is None: return
    feed = dataFramefeed.Feed()
    feed.addBarsFromDataFrame(code, data)
    # Set Strategy
    brk = gen_broker(feed)
    myStrategy = KDJStrategy(feed, brk, data, code, 45, 100, -0.05, 0.1, 5, 5,
                             1.5, 1.2)
    # Attach a returns analyzers to the strategy
    returnsAnalyzer = returns.Returns()
    myStrategy.attachAnalyzer(returnsAnalyzer)
    # Attach a sharpe ratio analyzers to the strategy
    sharpeRatioAnalyzer = sharpe.SharpeRatio()
    myStrategy.attachAnalyzer(sharpeRatioAnalyzer)
    # Attach the plotter to the strategy
    plt = plotter.StrategyPlotter(myStrategy, True, True, True)
    plt.getOrCreateSubplot("returns").addDataSeries(
        "Simple returns", returnsAnalyzer.getReturns())
    # Run Strategy
    myStrategy.run()
    myStrategy.info("Final portfolio value: $%.2f" % myStrategy.getResult())
    plt.plot()