Cycles/docs/analysis.md
Ajasra a924328c90 Implement Market Regime Strategy and refactor Bollinger Bands and RSI classes
- Introduced a new Strategy class to encapsulate trading strategies, including the Market Regime Strategy that adapts to different market conditions.
- Refactored BollingerBands and RSI classes to accept configuration parameters for improved flexibility and maintainability.
- Updated test_bbrsi.py to utilize the new strategy implementation and adjusted date ranges for testing.
- Enhanced documentation to include details about the new Strategy class and its components.
2025-05-22 16:44:59 +08:00

6.2 KiB
Raw Blame History

Analysis Module

This document provides an overview of the Analysis module and its components, which are typically used for technical analysis of financial market data.

Modules

The Analysis module includes classes for calculating common technical indicators:

  • Relative Strength Index (RSI): Implemented in cycles/Analysis/rsi.py.
  • Bollinger Bands: Implemented in cycles/Analysis/boillinger_band.py.
  • Trading Strategies: Implemented in cycles/Analysis/strategies.py.

Class: RSI

Found in cycles/Analysis/rsi.py.

Calculates the Relative Strength Index.

Mathematical Model

  1. Average Gain (AvgU) and Average Loss (AvgD) over 14 periods:
    
    \text{AvgU} = \frac{\sum \text{Upward Price Changes}}{14}, \quad \text{AvgD} = \frac{\sum \text{Downward Price Changes}}{14}
    
  2. Relative Strength (RS):
    
    RS = \frac{\text{AvgU}}{\text{AvgD}}
    
  3. RSI:
    
    RSI = 100 - \frac{100}{1 + RS}
    

__init__(self, period: int = 14)

  • Description: Initializes the RSI calculator.
  • Parameters:
    • period (int, optional): The period for RSI calculation. Defaults to 14. Must be a positive integer.

calculate(self, data_df: pd.DataFrame, price_column: str = 'close') -> pd.DataFrame

  • Description: Calculates the RSI and adds it as an 'RSI' column to the input DataFrame. Handles cases where data length is less than the period by returning the original DataFrame with a warning.
  • Parameters:
    • data_df (pd.DataFrame): DataFrame with historical price data. Must contain the price_column.
    • price_column (str, optional): The name of the column containing price data. Defaults to 'close'.
  • Returns: pd.DataFrame - The input DataFrame with an added 'RSI' column (containing np.nan for initial periods where RSI cannot be calculated). Returns a copy of the original DataFrame if the period is larger than the number of data points.

Class: BollingerBands

Found in cycles/Analysis/boillinger_band.py.

Bollinger Bands

Mathematical Model

  1. Middle Band: 20-day Simple Moving Average (SMA)
    
    \text{Middle Band} = \frac{1}{20} \sum_{i=1}^{20} \text{Close}_{t-i}
    
  2. Upper Band: Middle Band + 2 × 20-day Standard Deviation (σ)
    
    \text{Upper Band} = \text{Middle Band} + 2 \times \sigma_{20}
    
  3. Lower Band: Middle Band 2 × 20-day Standard Deviation (σ)
    
    \text{Lower Band} = \text{Middle Band} - 2 \times \sigma_{20}
    

__init__(self, period: int = 20, std_dev_multiplier: float = 2.0)

  • Description: Initializes the BollingerBands calculator.
  • Parameters:
    • period (int, optional): The period for the moving average and standard deviation. Defaults to 20. Must be a positive integer.
    • std_dev_multiplier (float, optional): The number of standard deviations for the upper and lower bands. Defaults to 2.0. Must be positive.

calculate(self, data_df: pd.DataFrame, price_column: str = 'close') -> pd.DataFrame

  • Description: Calculates Bollinger Bands and adds 'SMA' (Simple Moving Average), 'UpperBand', and 'LowerBand' columns to the DataFrame.
  • Parameters:
    • data_df (pd.DataFrame): DataFrame with price data. Must include the price_column.
    • price_column (str, optional): The name of the column containing the price data (e.g., 'close'). Defaults to 'close'.
  • Returns: pd.DataFrame - The original DataFrame with added columns: 'SMA', 'UpperBand', 'LowerBand'.

Class: Strategy

Found in cycles/Analysis/strategies.py.

Implements various trading strategies using technical indicators.

__init__(self, config = None, logging = None)

  • Description: Initializes the Strategy class with configuration and logging.
  • Parameters:
    • config (dict): Configuration dictionary with strategy parameters. Must be provided.
    • logging (logging object, optional): Logger for output messages. Defaults to None.

run(self, data, strategy_name)

  • Description: Executes a specified strategy on the provided data.
  • Parameters:
    • data (pd.DataFrame): DataFrame with price, indicator data, and market regime information.
    • strategy_name (str): Name of the strategy to run. Currently supports "MarketRegimeStrategy".
  • Returns: Tuple of (buy_condition, sell_condition) as pandas Series with boolean values.

no_strategy(self, data)

  • Description: Returns empty buy/sell conditions (all False).
  • Parameters:
    • data (pd.DataFrame): Input data DataFrame.
  • Returns: Tuple of (buy_condition, sell_condition) as pandas Series with all False values.

rsi_bollinger_confirmation(self, rsi, window=14, std_mult=1.5)

  • Description: Calculates Bollinger Bands on RSI values for signal confirmation.
  • Parameters:
    • rsi (pd.Series): Series containing RSI values.
    • window (int, optional): The period for the moving average. Defaults to 14.
    • std_mult (float, optional): Standard deviation multiplier for bands. Defaults to 1.5.
  • Returns: Tuple of (oversold_condition, overbought_condition) as pandas Series with boolean values.

MarketRegimeStrategy(self, data)

  • Description: Advanced strategy combining Bollinger Bands, RSI, volume analysis, and market regime detection.
  • Parameters:
    • data (pd.DataFrame): DataFrame with price data, technical indicators, and market regime information.
  • Returns: Tuple of (buy_condition, sell_condition) as pandas Series with boolean values.

Strategy Logic

This strategy adapts to different market conditions:

Trending Market (Breakout Mode):

  • Buy: Price < Lower Band ∧ RSI < 50 ∧ Volume Spike (≥1.5× 20D Avg)
  • Sell: Price > Upper Band ∧ RSI > 50 ∧ Volume Spike

Sideways Market (Mean Reversion):

  • Buy: Price ≤ Lower Band ∧ RSI ≤ 40
  • Sell: Price ≥ Upper Band ∧ RSI ≥ 60

When SqueezeStrategy is enabled, additional confirmation using RSI Bollinger Bands is required:

  • For buy signals: RSI must be below its lower Bollinger Band
  • For sell signals: RSI must be above its upper Bollinger Band

For sideways markets, volume contraction (< 0.7× 30D Avg) is also checked to avoid false signals.