Cycles/docs/strategies.md

99 lines
7.0 KiB
Markdown
Raw Normal View History

# Trading Strategies (`cycles/Analysis/strategies.py`)
This document outlines the trading strategies implemented within the `Strategy` class. These strategies utilize technical indicators calculated by other classes in the `Analysis` module.
## Class: `Strategy`
Manages and executes different trading strategies.
### `__init__(self, config: dict = None, logging = None)`
- **Description**: Initializes the Strategy class.
- **Parameters**:
- `config` (dict, optional): Configuration dictionary containing parameters for various indicators and strategy settings. Must be provided if strategies requiring config are used.
- `logging` (logging.Logger, optional): Logger object for outputting messages. Defaults to `None`.
### `run(self, data: pd.DataFrame, strategy_name: str) -> pd.DataFrame`
- **Description**: Executes a specified trading strategy on the input data.
- **Parameters**:
- `data` (pd.DataFrame): Input DataFrame containing at least price data (e.g., 'close', 'volume'). Specific strategies might require other columns or will calculate them.
- `strategy_name` (str): The name of the strategy to run. Supported names include:
- `"MarketRegimeStrategy"`
- `"CryptoTradingStrategy"`
- `"no_strategy"` (or any other unrecognized name will default to this)
- **Returns**: `pd.DataFrame` - A DataFrame containing the original data augmented with indicator values, and `BuySignal` and `SellSignal` (boolean) columns specific to the executed strategy. The structure of the DataFrame (e.g., daily, 15-minute) depends on the strategy.
### `no_strategy(self, data: pd.DataFrame) -> pd.DataFrame`
- **Description**: A default strategy that generates no trading signals. It can serve as a baseline or placeholder.
- **Parameters**:
- `data` (pd.DataFrame): Input data DataFrame.
- **Returns**: `pd.DataFrame` - The input DataFrame with `BuySignal` and `SellSignal` columns added, both containing all `False` values.
---
## Implemented Strategies
### 1. `MarketRegimeStrategy`
- **Description**: An adaptive strategy that combines Bollinger Bands and RSI, adjusting its parameters based on detected market regimes (trending vs. sideways). It operates on daily aggregated data (aggregation is performed internally).
- **Core Logic**:
- Calculates Bollinger Bands (using `BollingerBands` class) with adaptive standard deviation multipliers based on `MarketRegime` (derived from `BBWidth`).
- Calculates RSI (using `RSI` class).
- **Trending Market (Breakout Mode)**:
- Buy: Price < Lower Band RSI < 50 Volume Spike.
- Sell: Price > Upper Band ∧ RSI > 50 ∧ Volume Spike.
- **Sideways Market (Mean Reversion)**:
- Buy: Price ≤ Lower Band ∧ RSI ≤ 40.
- Sell: Price ≥ Upper Band ∧ RSI ≥ 60.
- **Squeeze Confirmation** (if `config["SqueezeStrategy"]` is `True`):
- Requires additional confirmation from RSI Bollinger Bands (calculated by `rsi_bollinger_confirmation` helper method).
- Sideways markets also check for volume contraction.
- **Key Configuration Parameters (from `config` dict)**:
- `bb_period`, `bb_width`
- `trending['bb_std_dev_multiplier']`, `trending['rsi_threshold']`
- `sideways['bb_std_dev_multiplier']`, `sideways['rsi_threshold']`
- `rsi_period`
- `SqueezeStrategy` (boolean)
- **Output DataFrame Columns (Daily)**: Includes input columns plus `SMA`, `UpperBand`, `LowerBand`, `BBWidth`, `MarketRegime`, `RSI`, `BuySignal`, `SellSignal`.
#### `rsi_bollinger_confirmation(self, rsi: pd.Series, window: int = 14, std_mult: float = 1.5) -> tuple`
- **Description** (Helper for `MarketRegimeStrategy`): 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` - (oversold_condition, overbought_condition) as pandas Series (boolean).
### 2. `CryptoTradingStrategy`
- **Description**: A multi-timeframe strategy primarily designed for volatile assets like cryptocurrencies. It aggregates input data into 15-minute and 1-hour intervals for analysis.
- **Core Logic**:
- Aggregates data to 15-minute (`data_15m`) and 1-hour (`data_1h`) resolutions using `aggregate_to_minutes` and `aggregate_to_hourly` from `data_utils.py`.
- Calculates 15-minute Bollinger Bands (20-period, 2 std dev) and 15-minute EMA-smoothed RSI (14-period) using `BollingerBands.calculate_custom_bands` and `RSI.calculate_custom_rsi`.
- Calculates 1-hour Bollinger Bands (50-period, 1.8 std dev) using `BollingerBands.calculate_custom_bands`.
- **Signal Generation (on 15m timeframe)**:
- Buy Signal: Price ≤ Lower 15m Band ∧ Price ≤ Lower 1h Band ∧ RSI_15m < 35 Volume Confirmation.
- Sell Signal: Price ≥ Upper 15m Band ∧ Price ≥ Upper 1h Band ∧ RSI_15m > 65 ∧ Volume Confirmation.
- **Volume Confirmation**: Current 15m volume > 1.5 × 20-period MA of 15m volume.
- **Risk Management**: Calculates `StopLoss` and `TakeProfit` levels based on a simplified ATR (standard deviation of 15m close prices over the last 4 periods).
- Buy: SL = Price - 2 * ATR; TP = Price + 4 * ATR
- Sell: SL = Price + 2 * ATR; TP = Price - 4 * ATR
- **Key Configuration Parameters**: While this strategy uses fixed parameters for its core indicator calculations, the `config` object passed to the `Strategy` class might be used by helper functions or for future extensions (though not heavily used by the current `CryptoTradingStrategy` logic itself for primary indicator settings).
- **Output DataFrame Columns (15-minute)**: Includes resampled 15m OHLCV, plus `UpperBand_15m`, `SMA_15m`, `LowerBand_15m`, `RSI_15m`, `VolumeMA_15m`, `UpperBand_1h` (forward-filled), `LowerBand_1h` (forward-filled), `BuySignal`, `SellSignal`, `StopLoss`, `TakeProfit`.
---
## General Strategy Concepts (from previous high-level notes)
While the specific implementations above have their own detailed logic, some general concepts that often inspire trading strategies include:
- **Adaptive Parameters**: Adjusting indicator settings (like Bollinger Band width or RSI thresholds) based on market conditions (e.g., trending vs. sideways).
- **Multi-Timeframe Analysis**: Confirming signals on one timeframe with trends or levels on another (e.g., 15-minute signals confirmed by 1-hour context).
- **Volume Confirmation**: Using volume spikes or contractions to validate price-based signals.
- **Volatility-Adjusted Risk Management**: Using measures like ATR (Average True Range) to set stop-loss and take-profit levels, or to size positions dynamically.
These concepts are partially reflected in the implemented strategies, particularly in `MarketRegimeStrategy` (adaptive parameters) and `CryptoTradingStrategy` (multi-timeframe, volume confirmation, ATR-based risk levels).