Пример #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
Пример #2
0
from datetime import datetime
from tradingene.algorithm_backtest.tng import TNG
from tradingene.backtest_statistics import backtest_statistics as bs

name = "example1"
regime = "SP"
start_date = datetime(2018, 1, 1)
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)
Пример #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
Пример #4
0
            'open'] * THRESHOLD  # Setting the take profit as big as the price threshold
        sl = tp  # Setting the stop loss equal to the take profit.
        alg.setTP(profit=tp)
        alg.setSL(loss=sl)
    elif prediction == 0:  # Class "0" predicts price to fall down
        alg.sell()
        tp = instrument.rates[0][
            'open'] * THRESHOLD  # Setting the take profit as big as the price threshold
        sl = tp  # Setting the stop loss equal to the take profit.
        alg.setTP(profit=tp)
        alg.setSL(loss=sl)


# 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
Пример #5
0
def calculate_output(data):
    return (data['close'][lookforward - 1] - data['open'][0]) / data['open'][0]


def onBar(instrument):
    inp = calculate_input(instrument.rates[1:lookback + 1])
    prediction1 = model1.predict([inp])
    prediction2 = model2.predict([inp])
    prediction3 = model3.predict([inp])
    if prediction1 > 0 and prediction2 > 0 and prediction3 > 0:  # If market rising is predicted...
        alg.buy()
    elif prediction1 < 0 and prediction2 < 0 and prediction3 < 0:  # If market falling is predicted...
        alg.sell()


model1, model2, model3 = prepare_model()
alg = TNG(end_train_date, end_test_date)
alg.addInstrument(ticker)
alg.addTimeframe(ticker, timeframe)
alg.run_backtest(onBar)

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

pnl = stat.calculate_PnL()  # Retrieving the PnL.
num_positions = stat.calculate_number_of_trades(
)  # Retrieving the number of trades done.
print("pnl=%f, num_positions=%d" % (pnl, num_positions))

stat.backtest_results()  # Displaying the backtest statistics
Пример #6
0

def calculate_output(data):
    return (data['close'][lookforward - 1] - data['open'][0]) / data['open'][0]


def onBar(instrument):
    inp = calculate_input(instrument.rates[1:lookback + 1])
    inp = scaler.transform(inp)
    prediction = model.predict([inp])
    if prediction > 0:  # If market rising is predicted...
        alg.buy()
    elif prediction < 0:  # If market falling is predicted...
        alg.sell()


model = prepare_model()
alg = TNG(end_train_date, end_test_date)
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()  # Retrieving the PnL.
num_positions = stat.calculate_number_of_trades(
)  # Retrieving the number of trades done.
print("pnl=%f, num_positions=%d" % (pnl, num_positions))

stat.backtest_results()  # Displaying the backtest statistics
Пример #7
0
end_date = datetime(2018, 2, 1)
ticker = "btcusd"
timeframe = 60


def onBar(instrument):
    bollinger10 = instrument.bollinger(
        10)  # Retrieving the value of the Bollinger indicator of period 10.
    if instrument.close[1] > bollinger10.top[
            1]:  # If the price soars above the Bollinger top line...
        alg.buy()
    elif instrument.close[1] < bollinger10.bottom[
            1]:  # If the price falls below the Bollinger bottom line...
        alg.sell()


alg = TNG(
    start_date, end_date
)  # Creating an instance of the class (TNG) to run the algorithm within.
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