Skip to content

Commit d77f7e9

Browse files
TexasCodingclaude
andcommitted
feat: add Lorenz Formula indicator applying chaos theory to market analysis
- Implement LORENZIndicator class with dynamic parameter calculation from OHLCV data - Add comprehensive test suite with 15 tests following TDD methodology - Create detailed documentation with trading strategies and examples - Add example script demonstrating usage with signal generation - Update version to v3.5.4 across all documentation - Update indicator count from 58+ to 59+ indicators The Lorenz Formula indicator adapts chaos theory equations to trading: - Calculates sigma (volatility), rho (trend), beta (dissipation) from market data - Uses Euler method for differential equation integration - Outputs x, y, z values for market regime detection - Supports multiple trading strategies including Z-value momentum and divergence 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <[email protected]>
1 parent 1b92b79 commit d77f7e9

File tree

12 files changed

+1450
-12
lines changed

12 files changed

+1450
-12
lines changed

.secrets.baseline

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -133,7 +133,7 @@
133133
"filename": "CHANGELOG.md",
134134
"hashed_secret": "89a6cfe2a229151e8055abee107d45ed087bbb4f",
135135
"is_verified": false,
136-
"line_number": 2073
136+
"line_number": 2107
137137
}
138138
],
139139
"README.md": [
@@ -325,5 +325,5 @@
325325
}
326326
]
327327
},
328-
"generated_at": "2025-08-31T14:52:37Z"
328+
"generated_at": "2025-08-31T20:27:03Z"
329329
}

CHANGELOG.md

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,40 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
1414
- Migration guides will be provided for all breaking changes
1515
- Semantic versioning (MAJOR.MINOR.PATCH) is strictly followed
1616

17+
## [3.5.4] - 2025-01-31
18+
19+
### 🚀 Added
20+
21+
**New Lorenz Formula Indicator**:
22+
- **Chaos Theory Trading**: Added Lorenz Formula indicator applying chaos theory to market analysis
23+
- **Dynamic Parameter Calculation**: Automatically adjusts sigma (volatility), rho (trend), and beta (volume) based on market conditions
24+
- **Three-Component Output**: Provides X (rate of change), Y (momentum), and Z (primary signal) components
25+
- **Market Regime Detection**: Identifies stable, transitional, and chaotic market conditions
26+
- **Full Integration**: TA-Lib style interface with both class-based and function-based APIs
27+
28+
### 📝 Documentation
29+
30+
**Lorenz Indicator Documentation**:
31+
- **Comprehensive Guide**: Created detailed documentation at `docs/indicators/lorenz.md` with mathematical foundation
32+
- **Trading Strategies**: Multiple signal generation strategies including Z-value momentum, crossovers, and divergence
33+
- **Parameter Tuning**: Complete guidelines for adjusting dt, window, and volatility_scale parameters
34+
- **Integration Examples**: Added to main indicators guide with practical usage examples
35+
- **Complete Trading System**: Full example with position sizing, stops, and multi-indicator confluence
36+
37+
### ✅ Testing
38+
39+
**Lorenz Indicator Tests**:
40+
- **15 Comprehensive Tests**: Full test coverage following TDD principles
41+
- **Parameter Validation**: Tests for custom parameters, window sizes, and time steps
42+
- **Chaos Properties**: Verification of chaotic behavior and sensitivity to initial conditions
43+
- **Edge Cases**: Handling of empty data, missing columns, and single-row inputs
44+
- **Integration**: Example script (`examples/33_lorenz_indicator.py`) demonstrating all features
45+
46+
### 🔧 Changed
47+
48+
- **Indicator Count**: Updated from 58+ to 59+ indicators across all documentation
49+
- **Pattern Recognition**: Enhanced with chaos theory-based market analysis
50+
1751
## [3.5.3] - 2025-01-31
1852

1953
### 🐛 Fixed

README.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -82,11 +82,11 @@ suite = await TradingSuite.create(\"MNQ\")
8282
- **Risk Management**: Portfolio analytics and risk metrics
8383

8484
### Advanced Features
85-
- **58+ Technical Indicators**: Full TA-Lib compatibility with Polars optimization including new pattern indicators
85+
- **59+ Technical Indicators**: Full TA-Lib compatibility with Polars optimization including new pattern indicators
8686
- **Level 2 OrderBook**: Depth analysis, iceberg detection, spoofing detection with 6 pattern types
8787
- **Real-time WebSockets**: Async streaming for quotes, trades, and account updates
8888
- **Performance Optimized**: Connection pooling, intelligent caching, memory management
89-
- **Pattern Recognition**: Fair Value Gaps, Order Blocks, and Waddah Attar Explosion indicators
89+
- **Pattern Recognition**: Fair Value Gaps, Order Blocks, Waddah Attar Explosion, and Lorenz Formula indicators
9090
- **Market Manipulation Detection**: Advanced spoofing detection with confidence scoring
9191
- **Financial Precision**: All calculations use Decimal type for exact precision
9292
- **Enterprise Error Handling**: Production-ready error handling with decorators and structured logging
@@ -588,7 +588,7 @@ if health_score < 70:
588588

589589
### Technical Indicators
590590

591-
All 58+ indicators work with async data pipelines:
591+
All 59+ indicators work with async data pipelines:
592592
```python
593593
import polars as pl
594594
from project_x_py.indicators import RSI, SMA, MACD, FVG, ORDERBLOCK, WAE

docs/guide/indicators.md

Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,7 @@ from project_x_py.indicators import (
6868
FVG, # Fair Value Gap
6969
ORDERBLOCK, # Order Block Detection
7070
WAE, # Waddah Attar Explosion
71+
LORENZ, # Lorenz Formula (Chaos Theory)
7172
)
7273
```
7374

@@ -867,6 +868,106 @@ async def wae_analysis():
867868
print(f"Recent bearish explosions - Avg: {avg_down:.1f}, Max: {max_down:.1f}")
868869
```
869870

871+
### Lorenz Formula (Chaos Theory)
872+
873+
The Lorenz Formula indicator applies chaos theory to market analysis, creating a dynamic attractor that responds to volatility, trend, and volume.
874+
875+
```python
876+
async def lorenz_analysis():
877+
suite = await TradingSuite.create("MNQ")
878+
data = await suite.data.get_data("15min", bars=200)
879+
880+
# Lorenz Formula with default parameters
881+
lorenz_data = data.pipe(LORENZ,
882+
window=14, # Rolling window for parameters
883+
dt=0.1, # Time step (smaller = more stable)
884+
volatility_scale=0.02 # Expected volatility
885+
)
886+
887+
# Lorenz provides three components:
888+
# - lorenz_x: Rate of change in the system
889+
# - lorenz_y: Momentum accumulation
890+
# - lorenz_z: Primary trading signal (height)
891+
892+
latest = lorenz_data.tail(1)
893+
z_value = latest['lorenz_z'][0]
894+
895+
# Basic signal interpretation
896+
if z_value > 0:
897+
print(f"Bullish bias (Z = {z_value:.2f})")
898+
elif z_value < 0:
899+
print(f"Bearish bias (Z = {z_value:.2f})")
900+
else:
901+
print("Neutral/Transitional")
902+
903+
# Calculate chaos magnitude for regime detection
904+
lorenz_data = lorenz_data.with_columns([
905+
(pl.col("lorenz_x")**2 +
906+
pl.col("lorenz_y")**2 +
907+
pl.col("lorenz_z")**2).sqrt().alias("chaos_magnitude")
908+
])
909+
910+
# Classify market regime
911+
lorenz_data = lorenz_data.with_columns([
912+
pl.when(pl.col("chaos_magnitude") < 10)
913+
.then(pl.lit("STABLE"))
914+
.when(pl.col("chaos_magnitude") < 50)
915+
.then(pl.lit("TRANSITIONAL"))
916+
.otherwise(pl.lit("CHAOTIC"))
917+
.alias("market_regime")
918+
])
919+
920+
latest_regime = lorenz_data.tail(1)
921+
regime = latest_regime['market_regime'][0]
922+
magnitude = latest_regime['chaos_magnitude'][0]
923+
924+
print(f"Market Regime: {regime} (Magnitude: {magnitude:.2f})")
925+
926+
# Z-value crossover strategy
927+
lorenz_data = lorenz_data.with_columns([
928+
pl.col("lorenz_z").rolling_mean(window_size=10).alias("z_ma")
929+
])
930+
931+
# Detect crossovers
932+
current = lorenz_data.tail(1)
933+
previous = lorenz_data.tail(2).head(1)
934+
935+
z_current = current['lorenz_z'][0]
936+
z_ma_current = current['z_ma'][0]
937+
z_previous = previous['lorenz_z'][0] if len(previous) > 0 else z_current
938+
z_ma_previous = previous['z_ma'][0] if len(previous) > 0 else z_ma_current
939+
940+
# Check for crossover signals
941+
if z_previous <= z_ma_previous and z_current > z_ma_current:
942+
print("🔺 Bullish Z crossover detected!")
943+
elif z_previous >= z_ma_previous and z_current < z_ma_current:
944+
print("🔻 Bearish Z crossover detected!")
945+
946+
# Advanced: Combine with other indicators
947+
from project_x_py.indicators import RSI
948+
949+
combined = lorenz_data.pipe(RSI, period=14)
950+
latest = combined.tail(1)
951+
952+
z = latest['lorenz_z'][0]
953+
rsi = latest['rsi_14'][0]
954+
955+
# Strong signals when both align
956+
if z > 0 and rsi < 35:
957+
print("💪 STRONG BUY: Bullish Lorenz + Oversold RSI")
958+
elif z < 0 and rsi > 65:
959+
print("💪 STRONG SELL: Bearish Lorenz + Overbought RSI")
960+
```
961+
962+
Key features of the Lorenz indicator:
963+
- **Chaos Theory Application**: Adapts atmospheric modeling to markets
964+
- **Three Components**: X (rate of change), Y (momentum), Z (signal)
965+
- **Dynamic Parameters**: Automatically adjusts to market conditions
966+
- **Regime Detection**: Identifies stable, transitional, and chaotic markets
967+
- **Early Warning System**: Detects instability before major moves
968+
969+
For detailed documentation and advanced strategies, see [Lorenz Indicator Documentation](../indicators/lorenz.md).
970+
870971
## Real-time Indicator Updates
871972

872973
### Streaming Indicator Calculations

docs/index.md

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,7 @@ asyncio.run(main())
9393
- Async historical OHLCV data with multiple timeframes
9494
- Real-time market data feeds via async WebSocket
9595
- **Level 2 orderbook analysis** with institutional-grade features
96-
- **58+ Technical Indicators** with TA-Lib compatibility (RSI, MACD, Bollinger Bands, Pattern Recognition, etc.)
96+
- **59+ Technical Indicators** with TA-Lib compatibility (RSI, MACD, Bollinger Bands, Pattern Recognition, Lorenz Formula, etc.)
9797
- **Advanced market microstructure** analysis (iceberg detection, order flow, volume profile)
9898
- **Market Manipulation Detection**: 6 spoofing pattern types with regulatory compliance features
9999
- **100% Async Statistics System**: Health monitoring, multi-format export, component tracking
@@ -161,8 +161,8 @@ mnq_context = suite["MNQ"] # Access specific instrument
161161
- **Event System**: Unified EventBus for cross-component communication
162162

163163
**Technical Analysis**
164-
- **58+ Indicators**: TA-Lib compatible with Polars DataFrames
165-
- **Pattern Recognition**: Fair Value Gaps, Order Blocks, Waddah Attar
164+
- **59+ Indicators**: TA-Lib compatible with Polars DataFrames
165+
- **Pattern Recognition**: Fair Value Gaps, Order Blocks, Waddah Attar, Lorenz Formula
166166
- **Advanced Patterns**: Iceberg detection, market manipulation
167167

168168
**Statistics & Monitoring (v3.3.0)**
@@ -184,7 +184,7 @@ mnq_context = suite["MNQ"] # Access specific instrument
184184
- [Order Management](guide/orders.md) - Placing and managing orders
185185
- [Position Tracking](guide/positions.md) - Portfolio management
186186
- [Real-time Data](guide/realtime.md) - WebSocket streaming
187-
- [Technical Indicators](guide/indicators.md) - 58+ analysis tools
187+
- [Technical Indicators](guide/indicators.md) - 59+ analysis tools
188188
- [Risk Management](guide/risk.md) - Position sizing and limits
189189
- [Order Book](guide/orderbook.md) - Level 2 market depth
190190

0 commit comments

Comments
 (0)