Implement multi-timeframe support for indicators
- Enhanced the `UserIndicator` class to include an optional `timeframe` attribute for custom indicator timeframes. - Updated the `get_indicator_data` method in `MarketDataIntegrator` to fetch and calculate indicators based on the specified timeframe, ensuring proper data alignment and handling. - Modified the `ChartBuilder` to pass the correct DataFrame for plotting indicators with different timeframes. - Added UI elements in the indicator modal for selecting timeframes, improving user experience. - Updated relevant JSON templates to include the new `timeframe` field for all indicators. - Refactored the `prepare_chart_data` function to ensure it returns a DataFrame with a `DatetimeIndex` for consistent calculations. This commit enhances the flexibility and usability of the indicator system, allowing users to analyze data across various timeframes.
This commit is contained in:
@@ -1,175 +1,123 @@
|
||||
# Technical Indicators Module
|
||||
|
||||
The Technical Indicators module provides comprehensive technical analysis capabilities for the TCP Trading Platform. It's designed to handle sparse OHLCV data efficiently and integrates seamlessly with the platform's aggregation strategy.
|
||||
The Technical Indicators module provides a suite of common technical analysis tools. It is designed to work efficiently with pandas DataFrames, which is the standard data structure for time-series analysis in the TCP Trading Platform.
|
||||
|
||||
## Overview
|
||||
|
||||
The module implements five core technical indicators commonly used in trading:
|
||||
The module has been refactored to be **DataFrame-centric**. All calculation methods now expect a pandas DataFrame with a `DatetimeIndex` and the required OHLCV columns (`open`, `high`, `low`, `close`, `volume`). This change simplifies the data pipeline, improves performance through vectorization, and ensures consistency across the platform.
|
||||
|
||||
- **Simple Moving Average (SMA)** - Average price over a specified period
|
||||
- **Exponential Moving Average (EMA)** - Weighted average giving more importance to recent prices
|
||||
- **Relative Strength Index (RSI)** - Momentum oscillator measuring speed and change of price movements
|
||||
- **Moving Average Convergence Divergence (MACD)** - Trend-following momentum indicator
|
||||
- **Bollinger Bands** - Volatility indicator with upper and lower bands around a moving average
|
||||
The module implements five core technical indicators:
|
||||
|
||||
- **Simple Moving Average (SMA)**
|
||||
- **Exponential Moving Average (EMA)**
|
||||
- **Relative Strength Index (RSI)**
|
||||
- **Moving Average Convergence Divergence (MACD)**
|
||||
- **Bollinger Bands**
|
||||
|
||||
## Key Features
|
||||
|
||||
### Sparse Data Handling
|
||||
- **No Interpolation**: Preserves gaps in timestamp data without artificial interpolation
|
||||
- **Efficient Processing**: Uses pandas for vectorized calculations
|
||||
- **Right-Aligned Timestamps**: Follows the platform's aggregation strategy convention
|
||||
- **Robust Error Handling**: Gracefully handles insufficient data and edge cases
|
||||
|
||||
### Performance Optimized
|
||||
- **Vectorized Calculations**: Leverages pandas and numpy for fast computation
|
||||
- **Batch Processing**: Calculate multiple indicators simultaneously
|
||||
- **Memory Efficient**: Processes data in chunks without excessive memory usage
|
||||
|
||||
### Flexible Configuration
|
||||
- **JSON Configuration**: Define indicator parameters via configuration files
|
||||
- **Multiple Price Columns**: Calculate indicators on open, high, low, or close prices
|
||||
- **Custom Parameters**: Adjust periods, standard deviations, and other parameters
|
||||
- **Validation**: Built-in configuration validation
|
||||
- **DataFrame-Centric Design**: Operates directly on pandas DataFrames for performance and simplicity.
|
||||
- **Vectorized Calculations**: Leverages pandas and numpy for high-speed computation.
|
||||
- **Flexible `calculate` Method**: A single entry point for calculating any supported indicator by name.
|
||||
- **Standardized Output**: All methods return a DataFrame containing the calculated indicator values, indexed by timestamp.
|
||||
|
||||
## Usage Examples
|
||||
|
||||
### Basic Usage
|
||||
### Preparing the DataFrame
|
||||
|
||||
Before you can calculate indicators, you need a properly formatted pandas DataFrame. The `prepare_chart_data` utility is the recommended way to create one from a list of candle dictionaries.
|
||||
|
||||
```python
|
||||
from components.charts.utils import prepare_chart_data
|
||||
from data.common.indicators import TechnicalIndicators
|
||||
from data.common.data_types import OHLCVCandle
|
||||
|
||||
# Initialize indicators calculator
|
||||
indicators = TechnicalIndicators()
|
||||
# Assume 'candles' is a list of OHLCV dictionaries from the database
|
||||
# candles = fetch_market_data(...)
|
||||
|
||||
# Calculate Simple Moving Average
|
||||
sma_results = indicators.sma(candles, period=20)
|
||||
# Prepare the DataFrame
|
||||
df = prepare_chart_data(candles)
|
||||
|
||||
# Calculate Exponential Moving Average
|
||||
ema_results = indicators.ema(candles, period=12)
|
||||
|
||||
# Calculate RSI
|
||||
rsi_results = indicators.rsi(candles, period=14)
|
||||
|
||||
# Calculate MACD
|
||||
macd_results = indicators.macd(candles, fast_period=12, slow_period=26, signal_period=9)
|
||||
|
||||
# Calculate Bollinger Bands
|
||||
bb_results = indicators.bollinger_bands(candles, period=20, std_dev=2.0)
|
||||
# df is now ready for indicator calculations
|
||||
# It has a DatetimeIndex and the necessary OHLCV columns.
|
||||
```
|
||||
|
||||
### Multiple Indicators
|
||||
### Basic Indicator Calculation
|
||||
|
||||
Once you have a prepared DataFrame, you can calculate indicators directly.
|
||||
|
||||
```python
|
||||
# Define configuration for multiple indicators
|
||||
config = {
|
||||
'sma_20': {'type': 'sma', 'period': 20},
|
||||
'sma_50': {'type': 'sma', 'period': 50},
|
||||
'ema_12': {'type': 'ema', 'period': 12},
|
||||
'rsi_14': {'type': 'rsi', 'period': 14},
|
||||
'macd': {'type': 'macd'},
|
||||
'bb_20': {'type': 'bollinger_bands', 'period': 20}
|
||||
}
|
||||
# Initialize the calculator
|
||||
indicators = TechnicalIndicators()
|
||||
|
||||
# Calculate all indicators at once
|
||||
results = indicators.calculate_multiple_indicators(candles, config)
|
||||
# Calculate a Simple Moving Average
|
||||
sma_df = indicators.sma(df, period=20)
|
||||
|
||||
# Access individual indicator results
|
||||
sma_20_values = results['sma_20']
|
||||
rsi_values = results['rsi_14']
|
||||
macd_values = results['macd']
|
||||
# Calculate an Exponential Moving Average
|
||||
ema_df = indicators.ema(df, period=12)
|
||||
|
||||
# sma_df and ema_df are pandas DataFrames containing the results.
|
||||
```
|
||||
|
||||
### Using the `calculate` Method
|
||||
|
||||
The most flexible way to compute an indicator is with the `calculate` method, which accepts the indicator type as a string.
|
||||
|
||||
```python
|
||||
# Calculate RSI using the generic method
|
||||
rsi_pkg = indicators.calculate('rsi', df, period=14)
|
||||
if rsi_pkg:
|
||||
rsi_df = rsi_pkg['data']
|
||||
|
||||
# Calculate MACD with custom parameters
|
||||
macd_pkg = indicators.calculate('macd', df, fast_period=10, slow_period=30, signal_period=8)
|
||||
if macd_pkg:
|
||||
macd_df = macd_pkg['data']
|
||||
```
|
||||
|
||||
### Using Different Price Columns
|
||||
|
||||
```python
|
||||
# Calculate SMA on high prices instead of close
|
||||
sma_high = indicators.sma(candles, period=20, price_column='high')
|
||||
|
||||
# Calculate EMA on low prices
|
||||
ema_low = indicators.ema(candles, period=12, price_column='low')
|
||||
|
||||
# Calculate RSI on open prices
|
||||
rsi_open = indicators.rsi(candles, period=14, price_column='open')
|
||||
```
|
||||
|
||||
### Default Configuration
|
||||
You can specify which price column (`open`, `high`, `low`, or `close`) to use for the calculation.
|
||||
|
||||
```python
|
||||
from data.common.indicators import create_default_indicators_config
|
||||
# Calculate SMA on the 'high' price
|
||||
sma_high_df = indicators.sma(df, period=20, price_column='high')
|
||||
|
||||
# Get default configuration
|
||||
default_config = create_default_indicators_config()
|
||||
|
||||
# Calculate using defaults
|
||||
results = indicators.calculate_multiple_indicators(candles, default_config)
|
||||
# Calculate RSI on the 'open' price
|
||||
rsi_open_pkg = indicators.calculate('rsi', df, period=14, price_column='open')
|
||||
```
|
||||
|
||||
## Indicator Details
|
||||
|
||||
The following details the parameters and the columns returned in the result DataFrame for each indicator.
|
||||
|
||||
### Simple Moving Average (SMA)
|
||||
|
||||
Calculates the arithmetic mean of prices over a specified period.
|
||||
|
||||
**Parameters:**
|
||||
- `period`: Number of periods (default: 20)
|
||||
- `price_column`: Price column to use (default: 'close')
|
||||
|
||||
**Returns:**
|
||||
- `sma`: Simple moving average value
|
||||
- **Parameters**: `period` (int), `price_column` (str, default: 'close')
|
||||
- **Returned Columns**: `sma`
|
||||
|
||||
### Exponential Moving Average (EMA)
|
||||
|
||||
Calculates exponentially weighted moving average, giving more weight to recent prices.
|
||||
|
||||
**Parameters:**
|
||||
- `period`: Number of periods (default: 20)
|
||||
- `price_column`: Price column to use (default: 'close')
|
||||
|
||||
**Returns:**
|
||||
- `ema`: Exponential moving average value
|
||||
- **Parameters**: `period` (int), `price_column` (str, default: 'close')
|
||||
- **Returned Columns**: `ema`
|
||||
|
||||
### Relative Strength Index (RSI)
|
||||
|
||||
Momentum oscillator that measures the speed and change of price movements.
|
||||
|
||||
**Parameters:**
|
||||
- `period`: Number of periods (default: 14)
|
||||
- `price_column`: Price column to use (default: 'close')
|
||||
|
||||
**Returns:**
|
||||
- `rsi`: RSI value (0-100 range)
|
||||
- **Parameters**: `period` (int), `price_column` (str, default: 'close')
|
||||
- **Returned Columns**: `rsi`
|
||||
|
||||
### MACD (Moving Average Convergence Divergence)
|
||||
|
||||
Trend-following momentum indicator showing the relationship between two moving averages.
|
||||
|
||||
**Parameters:**
|
||||
- `fast_period`: Fast EMA period (default: 12)
|
||||
- `slow_period`: Slow EMA period (default: 26)
|
||||
- `signal_period`: Signal line EMA period (default: 9)
|
||||
- `price_column`: Price column to use (default: 'close')
|
||||
|
||||
**Returns:**
|
||||
- `macd`: MACD line (fast EMA - slow EMA)
|
||||
- `signal`: Signal line (EMA of MACD)
|
||||
- `histogram`: MACD histogram (MACD - Signal)
|
||||
- **Parameters**: `fast_period` (int), `slow_period` (int), `signal_period` (int), `price_column` (str, default: 'close')
|
||||
- **Returned Columns**: `macd`, `signal`, `histogram`
|
||||
|
||||
### Bollinger Bands
|
||||
|
||||
Volatility indicator consisting of a moving average and two standard deviation bands.
|
||||
- **Parameters**: `period` (int), `std_dev` (float), `price_column` (str, default: 'close')
|
||||
- **Returned Columns**: `upper_band`, `middle_band`, `lower_band`
|
||||
|
||||
**Parameters:**
|
||||
- `period`: Number of periods for moving average (default: 20)
|
||||
- `std_dev`: Number of standard deviations (default: 2.0)
|
||||
- `price_column`: Price column to use (default: 'close')
|
||||
## Integration with the TCP Platform
|
||||
|
||||
**Returns:**
|
||||
- `upper_band`: Upper Bollinger Band
|
||||
- `middle_band`: Middle band (SMA)
|
||||
- `lower_band`: Lower Bollinger Band
|
||||
- `bandwidth`: Band width relative to middle band
|
||||
- `percent_b`: %B indicator (position within bands)
|
||||
The refactored `TechnicalIndicators` module is now tightly integrated with the `ChartBuilder`, which handles all data preparation and calculation automatically when indicators are added to a chart. For custom analysis or strategy development, you can use the class directly as shown in the examples above. The key is to always start with a properly prepared DataFrame using `prepare_chart_data`.
|
||||
|
||||
## Data Structures
|
||||
|
||||
|
||||
Reference in New Issue
Block a user