Esempio n. 1
0
end_date = datetime(2018, 5, 1)
timeframe = 1440

alg = TNG(name, regime, start_date, end_date)
alg.addInstrument("btcusd")
alg.addTimeframe("btcusd", timeframe)
positionId = None


def onBar(instrument):
    global positionId
    if positionId is None:
        if instrument.macd().histogram[2] > instrument.macd().histogram[1]:
            positionId = alg.openLong(1)
        if instrument.macd().histogram[2] < instrument.macd().histogram[1]:
            positionId = alg.openShort(1)
    else:
        if instrument.macd().histogram[2] > instrument.macd().histogram[1] and\
           alg.getPositionSide(positionId) <=0:
            alg.closePosition(positionId)
            positionId = alg.openLong(1)
        if instrument.macd().histogram[2] < instrument.macd().histogram[1] and \
           alg.getPositionSide(positionId) >= 0:
            alg.closePosition(positionId)
            positionId = alg.openShort(1)


alg.run_backtest(onBar)
stat = bs.BacktestStatistics(alg)
stat.backtest_results()
Esempio n. 2
0
        return 1
    elif data['close'][lookforward - 1] * 1.01 < data['open'][0]:
        return -1
    else:
        return 0


def onBar(instrument):
    inp = calculate_input(
        instrument.rates[1:lookback + 1])  # Calculating inputs
    prediction = model.predict([inp])[0]  # Making prediction
    if prediction > 0:
        alg.buy()
    elif prediction < 0:
        alg.sell()
# end of onBar()

model = prepare_model()  # Creating an ML-model.
alg = TNG(end_train_date, end_test_date)  # Creating an instance of environment to run algorithm in.
alg.addInstrument(ticker)  # Adding an instrument.
alg.addTimeframe(ticker, timeframe)  # Adding a time frame.
alg.run_backtest(onBar)  # Backtesting...

stat = bs.BacktestStatistics(alg)  # Retrieving statistics of the backtest

pnl = stat.calculate_PnL()
num_positions = stat.calculate_number_of_trades()
print("pnl=%f, num_positions=%d" % (pnl, num_positions))

stat.backtest_results()  # Displaying the backtest statistics