Esempio n. 1
0
def run(start_date, end_date, file_name):
    global file_handle, model

    try:
        file_handle = open(file_name, "w")

        if model is None:
            model = prepare_model()  # Creating an ML-model.
        alg = TNG(start_date, end_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(on_bar)  # Backtesting...
        del alg

    except IOError:
        sys.stderr.write("Error while running a backtest for %s.\n" %
                         (file_name))
    else:
        sys.stderr.write("File %s done.\n" % (file_name))

    if file_handle is not None:
        file_handle.close()
        file_handle = None

    return model
Esempio n. 2
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. 3
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