Exemple #1
0
def myTradingSystem(DATE, OPEN, HIGH, LOW, CLOSE, VOL,
                    settings) -> Tuple[np.ndarray, dict]:
    """
    Trading system that uses the LSTM model to predict changes in price.
    """

    current_date: pd.Timestamp = pd.to_datetime(DATE[-1], format="%Y%m%d")
    positions = []

    print(f"Testing: {current_date.strftime('%Y-%m-%d')}")

    for index, ticker in enumerate(settings["markets"]):
        if ticker == "CASH":
            positions.append(1)
            continue

        print(f"Predicting for: {ticker}")
        ohclv_data = build_ohclv_dataframe(DATE, OPEN, HIGH, LOW, CLOSE, VOL,
                                           index)
        predictors = DataProcessor(data=ohclv_data).build_predictors()
        model = settings["models"][ticker]

        # On some days, data might not be available
        if len(predictors) < model.time_step:
            positions.append(0)
        elif predictors.index[-1] != current_date:
            positions.append(0)
        else:
            prediction = model.predict_last(predictors=predictors)
            positions.append(prediction)

    weights = normalize_weights(weights=positions)

    return weights, settings
def myTradingSystem(DATE, OPEN, HIGH, LOW, CLOSE, VOL, settings):
    """
    Trading system that uses the XGBoost model to predict changes in price.
    """

    current_date = pd.to_datetime(DATE[-1], format="%Y%m%d")
    positions = []

    print(f"Testing: {current_date.strftime('%Y-%m-%d')}")

    for index, ticker in enumerate(settings["markets"]):
        if ticker == "CASH":
            positions.append(0)
            continue

        print(f"Predicting for: {ticker}")

        ohclv_data = build_ohclv_dataframe(DATE, OPEN, HIGH, LOW, CLOSE, VOL,
                                           index)
        predictors = DataProcessor(data=ohclv_data).build_predictors()
        predictors_last = predictors.loc[current_date:]

        # On some days, data might not be available
        if len(predictors_last) == 0:
            positions.append(0)
            continue

        xgb_model = settings["xgb_models"][ticker]
        xgb_prediction = int(xgb_model.predict(predictors_last.to_numpy())[0])
        positions.append(xgb_prediction)

    weights = normalize_weights(positions)

    return weights, settings
Exemple #3
0
def myTradingSystem(DATE: List[int], OPEN: np.ndarray, HIGH: np.ndarray,
                    LOW: np.ndarray, CLOSE: np.ndarray, VOL: np.ndarray,
                    settings) -> Tuple[np.ndarray, dict]:
    """
    Base trading system that simply longs every asset with equal weight.
    """
    print(f"Date: {DATE[-1]}")

    positions: List[int] = []

    for index, ticker in enumerate(settings["markets"]):
        if ticker == "CASH":
            positions.append(0)
            continue

        ohclv_data = build_ohclv_dataframe(DATE, OPEN, HIGH, LOW, CLOSE, VOL,
                                           index)
        predictors = DataProcessor(data=ohclv_data).build_predictors()
        prediction = train(ticker).predict(predictors.to_numpy())
        predicted_labels = {0: -1, 1: 1, 2: 0}
        predictions = [predicted_labels[np.argmax(x)] for x in prediction]

        predicted_labels = {0: -1, 1: 1, 2: 0}

        print(predictions)
        try:
            positions.append(predictions[-1])
        except:
            positions.append(0)

    weights = normalize_weights(weights=positions)

    return weights, settings
def myTradingSystem(DATE, OPEN, HIGH, LOW, CLOSE, VOL,
                    settings) -> Tuple[np.ndarray, dict]:
    """
    Trading system that ensembles the ARIMA, LSTM and XGBoost model to predict changes in price.
    """
    current_date: pd.Timestamp = pd.to_datetime(DATE[-1], format="%Y%m%d")
    positions = []

    print(f"Testing: {current_date.strftime('%Y-%m-%d')}")

    for index, ticker in enumerate(settings["markets"]):
        if ticker == "CASH":
            positions.append(0)
            continue

        print(f"Predicting for: {ticker}")

        # Data Preparation
        ohclv_data = build_ohclv_dataframe(DATE, OPEN, HIGH, LOW, CLOSE, VOL,
                                           index)
        predictors = DataProcessor(data=ohclv_data).build_predictors()

        # LSTM prediction
        lstm_model = settings["lstm_models"][ticker]
        lstm_prediction = get_lstm_prediction(model=lstm_model,
                                              predictors=predictors,
                                              current_date=current_date)

        # XGBoost prediction
        xgb_model = settings["xgb_models"][ticker]
        xgb_prediction = get_xgb_prediction(model=xgb_model,
                                            predictors=predictors,
                                            current_date=current_date)

        # ARIMA prediction
        arima_order = settings["arima_params"][ticker]
        arima_prediction = get_arima_prediction(price_data=CLOSE[:, index],
                                                order=arima_order)

        # Ensemble the predictions
        combined_prediction = lstm_prediction + xgb_prediction + arima_prediction
        if combined_prediction >= 2:
            positions.append(1)
        elif combined_prediction <= -2:
            positions.append(-1)
        else:
            positions.append(0)

    weights = normalize_weights(weights=positions)

    return weights, settings
Exemple #5
0
def myTradingSystem(DATE: List[int], OPEN: np.ndarray, HIGH: np.ndarray,
                    LOW: np.ndarray, CLOSE: np.ndarray, VOL: np.ndarray,
                    settings) -> Tuple[np.ndarray, dict]:
    """
    Trading system that uses the simple moving average crossover strategy to predict future trends.
    """

    print(f"Date: {DATE[-1]}")

    positions: List[int] = []

    for index, ticker in enumerate(settings["markets"]):
        if ticker == "CASH":
            positions.append(0)
            continue

        fast_periods = 12
        slow_periods = 26

        print(f"Predicting for: {ticker}")
        ohclv_data = build_ohclv_dataframe(DATE, OPEN, HIGH, LOW, CLOSE, VOL,
                                           index)
        predictors = (DataProcessor(data=ohclv_data).add_ema(
            periods=fast_periods).add_ema(periods=slow_periods).get_data())

        fast_ema = predictors[f"{fast_periods}-PERIOD EMA"].iloc[-1]
        slow_ema = predictors[f"{slow_periods}-PERIOD EMA"].iloc[-1]
        fast_ema_is_increasing = (
            (predictors[f"{fast_periods}-PERIOD EMA"].iloc[-1] -
             predictors[f"{fast_periods}-PERIOD EMA"].iloc[-2])) > 0

        # Fast EMA crosses above slow SMA and fast EMA appears to be increasing - buy signal
        if fast_ema > slow_ema and fast_ema_is_increasing:
            positions.append(1)

        # Fast EMA crosses below slow SMA and fast EMA appears to be decreasing - sell signal
        elif slow_ema > fast_ema and not fast_ema_is_increasing:
            positions.append(-1)

        else:
            positions.append(0)

    weights = normalize_weights(weights=positions)

    return weights, settings
def myTradingSystem(DATE, OPEN, HIGH, LOW, CLOSE, VOL,
                    settings) -> Tuple[np.ndarray, dict]:
    """
    Trading system that uses the LightGBM to predict price changes.
    """
    current_date: pd.Timestamp = pd.to_datetime(DATE[-1], format="%Y%m%d")
    positions = []

    print(f"Testing: {current_date.strftime('%Y-%m-%d')}")

    for index, ticker in enumerate(settings["markets"]):
        if ticker == "CASH":
            positions.append(0)
            continue

        ohclv_data = build_ohclv_dataframe(DATE, OPEN, HIGH, LOW, CLOSE, VOL,
                                           index)
        predictors = DataProcessor(data=ohclv_data).build_predictors()

        # Model not yet trained
        if ticker not in settings["models"]:
            model = train(ticker)
            settings["models"][ticker] = model

        # Model has been trained in a previous period
        else:
            model = settings["models"][ticker]

        predictors_last = predictors.loc[current_date:]

        # On some days, data might not be available
        if len(predictors_last) == 0:
            positions.append(0)
            continue

        prediction = model.predict(predictors_last)
        predicted_labels = {0: -1, 1: 1, 2: 0}
        prediction = predicted_labels[np.argmax(prediction)]
        positions.append(prediction)

    weights = normalize_weights(weights=positions)

    return weights, settings