Skip to content

turtle_quant_1.strategies.mean_reversion.bollinger_band

turtle_quant_1.strategies.mean_reversion.bollinger_band

Bollinger band strategy implementation.

BollingerBand

BollingerBand(lookback_candles: int = 180, n_std: int = 3)

Bases: BaseStrategy

A strategy that uses the Bollinger bands to generate buy and sell signals.

Leading / Lagging: Lagging in construction. Leading in interpretation. Lag period (in candles): (lookback_candles - 1) / 2 Effect: Delay in recognizing that price has deviated far enough from equilibrium.

Initialize the Bollinger band strategy.

Parameters:

Name Type Description Default
lookback_candles int

The number of periods to use for the Bollinger bands.

180
n_std int

The number of standard deviations to use for the Bollinger bands.

3
Source code in src/turtle_quant_1/strategies/mean_reversion/bollinger_band.py
def __init__(self, lookback_candles: int = 180, n_std: int = 3):
    """Initialize the Bollinger band strategy.

    Args:
        lookback_candles: The number of periods to use for the Bollinger bands.
        n_std: The number of standard deviations to use for the Bollinger bands.
    """
    super().__init__()
    self.lookback_candles = lookback_candles
    self.n_std = n_std

    if (
        lookback_candles
        > convert_units(BACKTESTING_MAX_LOOKBACK_DAYS, "1D", CANDLE_UNIT) * 0.5
    ):
        raise ValueError(
            f"This strategy relies on too many lookback candles ({lookback_candles}) for meaningful evaluation to be done. "
            f"Maximum lookback is {BACKTESTING_MAX_LOOKBACK_DAYS} days."
        )

generate_historical_scores

generate_historical_scores(
    data: DataFrame, symbol: str
) -> Series

Generate a historical score array for a symbol based on market data.

NOTE: Assume that the data is sorted by datetime.

Parameters:

Name Type Description Default
data DataFrame

The data to use for the strategy.

required
symbol str

The symbol to use for the strategy.

required

Returns:

Type Description
Series

Score array with each value between -1.0 and +1.0, indexed by the original data's index.

Source code in src/turtle_quant_1/strategies/mean_reversion/bollinger_band.py
def generate_historical_scores(self, data: pd.DataFrame, symbol: str) -> pd.Series:
    """Generate a historical score array for a symbol based on market data.

    NOTE: Assume that the data is sorted by datetime.

    Args:
        data: The data to use for the strategy.
        symbol: The symbol to use for the strategy.

    Returns:
        Score array with each value between -1.0 and +1.0, indexed by the original data's index.
    """
    self.validate_data(data)

    sma = data["Close"].rolling(self.lookback_candles).mean()
    std = data["Close"].rolling(self.lookback_candles).std()

    upper = sma + self.n_std * std
    lower = sma - self.n_std * std

    score = (data["Close"] - sma) / (upper - lower)
    if np.isnan(score.iloc[-1]):
        raise ValueError("Last score should not be NaN")

    return pd.Series(
        data=score.clip(-1, 1).fillna(0).values,
        index=data.index,
    )

generate_prediction_score

generate_prediction_score(
    data: DataFrame, symbol: str
) -> float

Generate a score for the strategy.

NOTE: Assume that the data is sorted by datetime.

Parameters:

Name Type Description Default
data DataFrame

The data to use for the strategy.

required
symbol str

The symbol to use for the strategy.

required
Source code in src/turtle_quant_1/strategies/mean_reversion/bollinger_band.py
def generate_prediction_score(self, data: pd.DataFrame, symbol: str) -> float:
    """Generate a score for the strategy.

    NOTE: Assume that the data is sorted by datetime.

    Args:
        data: The data to use for the strategy.
        symbol: The symbol to use for the strategy.
    """
    # Score near +1 -> BUY
    # Score near -1 -> SELL
    return self.generate_historical_scores(
        data.iloc[-(self.lookback_candles + 1) :], symbol
    ).iloc[-1]