Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion .github/workflows/docs-enhanced.yml
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,6 @@ jobs:
uses: actions/setup-node@v4
with:
node-version: ${{ env.NODE_VERSION }}
cache: 'npm'

- name: Cache Python dependencies
id: cache
Expand Down
8 changes: 4 additions & 4 deletions .github/workflows/pr-docs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,10 @@ jobs:
run: |
python scripts/check_docstring_coverage.py

- name: Validate example documentation
if: steps.changes.outputs.examples == 'true'
run: |
python scripts/validate_example_docs.py
- name: Validate example documentation
if: steps.changes.outputs.examples == 'true'
run: |
python scripts/validate_examples.py

- name: Check for API documentation updates
if: steps.changes.outputs.code == 'true'
Expand Down
38 changes: 38 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,44 @@ All notable changes to this project will be documented in this file.

The format is based on Keep a Changelog and this project adheres to Semantic Versioning.

## [0.3.1] - 2025-10-26

### Added
- **Risk Management System:** Complete real-time risk monitoring with stop-loss functionality
- `RiskManager` class for position monitoring and risk limit enforcement
- Multiple stop-loss types: percentage, absolute price, and trailing stops
- `StopLossEngine` with advanced strategies (volatility-adjusted, time-based)
- Configurable risk limits (max drawdown, position size, daily loss limits)
- **Automated Execution Layer:** `AutoExecutor` for automated risk response
- Real-time risk event detection and order generation
- Emergency stop functionality with circuit breakers
- Rate limiting and execution controls
- **WebSocket Risk Integration:** Enhanced `KalshiWebSocketClient` with risk monitoring
- Real-time position P&L updates via websocket price feeds
- Automatic risk evaluation on market data changes
- **Trading Client Enhancements:** Risk-aware order placement
- `place_order_with_risk()` method with stop-loss configuration
- Automatic position registration with risk manager
- **Portfolio Risk Integration:** Enhanced paper trading with risk controls
- Real-time risk monitoring in `PaperPortfolio`
- Risk metrics dashboard and position management
- **Backtesting Risk Simulation:** Risk management in historical testing
- Stop-loss simulation in backtesting engine
- Risk-adjusted performance metrics
- **Comprehensive Testing:** Full test suite for risk management components
- Unit tests for all risk classes and methods
- Integration tests for websocket and execution layers
- Mock-based testing for reliability

### Changed
- **Analysis Module Structure:** Updated `neural/analysis/risk/` to include risk management beyond position sizing
- **Execution Module:** Enhanced `neural/analysis/execution/` with automated risk execution
- **Trading Integration:** Added risk management parameters to trading clients and portfolios

### Fixed
- **Import Dependencies:** Resolved circular import issues in risk management modules
- **Type Annotations:** Improved type safety across risk management components

## [0.3.0] - 2025-10-24

### Added
Expand Down
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,11 +88,11 @@ print(f"Collected {len(trades_data)} trades")

```python
from neural.analysis.strategies import MeanReversionStrategy
from neural.analysis.backtesting import BacktestEngine
from neural.analysis import Backtester

strategy = MeanReversionStrategy(lookback_period=20, z_score_threshold=2.0)
engine = BacktestEngine(strategy, initial_capital=10000)
results = engine.run(historical_data)
engine = Backtester(initial_capital=10000)
results = engine.backtest(strategy, start_date="2024-01-01", end_date="2024-12-31")

print(f"Total Return: {results['total_return']:.2%}")
print(f"Sharpe Ratio: {results['sharpe_ratio']:.2f}")
Expand Down
4 changes: 2 additions & 2 deletions docs/analysis/overview.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ Translate raw market data into executable decisions. The analysis stack manages
|--------|----------------|------|
| `neural.analysis.strategies` | Base class + prebuilt strategies (mean reversion, momentum, arbitrage, sentiment) | `analysis/strategy-foundations`, `analysis/strategy-library` |
| `neural.analysis.backtesting` | Event-driven backtester with fee/slippage modelling and optional ESPN integration | `analysis/backtesting` |
| `neural.analysis.risk.position_sizing` | Kelly, fixed-percentage, edge-proportional, martingale helpers | `analysis/risk-sizing` |
| `neural.analysis.execution.order_manager` | Bridges strategy signals to trading clients (live or paper) | `analysis/order-management` |
| `neural.analysis.risk` | Position sizing + real-time risk management, stop-loss, and automated execution | `analysis/risk-sizing`, `analysis/risk-management` |
| `neural.analysis.execution` | Order management + automated risk execution layer | `analysis/order-management` |
| `neural.analysis.sentiment` | Twitter/ESPN sentiment engines and trackers | `analysis/sentiment` |

## Inputs
Expand Down
295 changes: 295 additions & 0 deletions docs/analysis/risk-management.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,295 @@
---
title: 'Risk Management & Stop-Loss'
description: 'Real-time risk monitoring, automated stop-loss execution, and position management for live trading.'
---

## Overview

Neural's risk management system provides comprehensive protection for your trading operations through real-time monitoring, automated stop-loss execution, and configurable risk limits. Designed specifically for websocket-based trading flows, it ensures positions are managed and exited quickly when risk thresholds are breached.

## Key Features

- **Multiple Stop-Loss Types**: Percentage, absolute price, and trailing stops
- **Real-Time Monitoring**: Continuous position evaluation via websocket updates
- **Automated Execution**: Immediate order placement when risk events trigger
- **Risk Limits**: Configurable drawdown, position size, and daily loss limits
- **Emergency Controls**: Circuit breakers and emergency stop functionality

## Quick Start

```python
from neural.analysis.risk import RiskManager, StopLossConfig, StopLossType, RiskLimits
from neural.analysis.execution import AutoExecutor, ExecutionConfig
from neural.trading import TradingClient, KalshiWebSocketClient

# Create risk manager with conservative limits
risk_manager = RiskManager(
limits=RiskLimits(
max_drawdown_pct=0.10, # 10% max drawdown
max_position_size_pct=0.05, # 5% of portfolio per position
daily_loss_limit_pct=0.05 # 5% daily loss limit
)
)

# Create automated executor
executor = AutoExecutor(trading_client=TradingClient())

# Connect executor to risk manager for event handling
risk_manager.event_handler = executor

# Connect risk manager to websocket for real-time monitoring
ws_client = KalshiWebSocketClient(risk_manager=risk_manager)
ws_client.connect()

# Trading client with risk integration
client = TradingClient(risk_manager=risk_manager)

# Place order with stop-loss protection
client.place_order_with_risk(
market_id="market_123",
side="yes",
quantity=100,
stop_loss_config=StopLossConfig(type=StopLossType.PERCENTAGE, value=0.05)
)
```

## Stop-Loss Types

### Percentage Stop-Loss

Exits position when loss exceeds a percentage of entry value.

```python
stop_config = StopLossConfig(
type=StopLossType.PERCENTAGE,
value=0.05 # 5% stop-loss
)
```

### Absolute Price Stop-Loss

Exits at a specific price level.

```python
stop_config = StopLossConfig(
type=StopLossType.ABSOLUTE,
value=0.45 # Exit if price drops to 0.45
)
```

### Trailing Stop-Loss

Follows favorable price movement, locking in profits.

```python
stop_config = StopLossConfig(
type=StopLossType.TRAILING,
value=0.03 # 3% trail behind highest price
)
```

## Advanced Stop-Loss Strategies

The `StopLossEngine` provides sophisticated stop-loss calculations:

```python
from neural.analysis.risk import StopLossEngine

engine = StopLossEngine()

# Volatility-adjusted stop
stop_price = engine.calculate_stop_price(
entry_price=0.50,
current_price=0.55,
side="yes",
strategy="volatility",
volatility=0.02, # 2% volatility
multiplier=2.0 # 2x volatility for safety
)

# Time-based decaying stop
stop_price = engine.calculate_stop_price(
entry_price=0.50,
current_price=0.52,
side="yes",
strategy="time_based",
time_held=3600, # 1 hour held
max_time=86400, # 24 hours max
time_factor=0.1 # 10% max adjustment
)
```

## Risk Limits Configuration

```python
from neural.analysis.risk import RiskLimits

limits = RiskLimits(
max_drawdown_pct=0.15, # Stop trading if portfolio drops 15%
max_position_size_pct=0.10, # No position larger than 10% of portfolio
daily_loss_limit_pct=0.08, # Stop if daily loss exceeds 8%
max_positions=20 # Maximum 20 open positions
)

risk_manager = RiskManager(limits=limits)
```

## WebSocket Integration

Real-time risk monitoring through websocket price updates:

```python
# WebSocket automatically monitors positions
ws_client = KalshiWebSocketClient(risk_manager=risk_manager)
ws_client.connect()

# As prices update, risk manager evaluates positions
# Stop-loss orders are triggered automatically when conditions met
```

## Automated Execution

The `AutoExecutor` handles risk events automatically:

```python
from neural.analysis.execution import AutoExecutor, ExecutionConfig

executor = AutoExecutor(
trading_client=client,
config=ExecutionConfig(
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

logic: ExecutionConfig is imported/defined nowhere in the codebase – this code will fail at runtime

Prompt To Fix With AI
This is a comment left during a code review.
Path: docs/analysis/risk-management.mdx
Line: 156:156

Comment:
**logic:** `ExecutionConfig` is imported/defined nowhere in the codebase – this code will fail at runtime

How can I resolve this? If you propose a fix, please make it concise.

enable_auto_execution=True,
max_orders_per_minute=10,
dry_run=False # Set to True for testing
)
)

# Connect to risk manager
risk_manager.event_handler = executor

# Now risk events trigger automatic orders
```

## Paper Trading Integration

Test risk management in paper trading environment:

```python
from neural.trading import PaperPortfolio

portfolio = PaperPortfolio(
initial_capital=10000,
risk_manager=risk_manager
)

# Risk monitoring works in paper trading
# Stop-loss orders become paper orders
```

## Backtesting with Risk Management

Include risk management in backtesting:

```python
from neural.analysis.backtesting import Backtester

backtester = Backtester(risk_manager=risk_manager)

# Backtest includes stop-loss simulation
result = backtester.backtest(strategy, start_date, end_date)
```

## Risk Metrics Dashboard

Monitor current risk exposure:

```python
metrics = risk_manager.get_risk_metrics()
print(f"Portfolio Value: ${metrics['portfolio_value']:.2f}")
print(f"Drawdown: {metrics['drawdown_pct']:.2%}")
print(f"Daily P&L: ${metrics['daily_pnl']:.2f}")
print(f"Open Positions: {metrics['open_positions']}")
```

## Emergency Controls

```python
# Manual emergency stop
executor.emergency_stop({"reason": "manual_override"})

# Check system status
status = executor.get_execution_summary()
print(f"Auto-execution: {status['auto_execution_enabled']}")
print(f"Active orders: {status['active_orders']}")
```

## Configuration Best Practices

### Conservative Settings (Recommended for beginners)
```python
limits = RiskLimits(
max_drawdown_pct=0.05, # 5% max drawdown
max_position_size_pct=0.02, # 2% per position
daily_loss_limit_pct=0.03 # 3% daily limit
)
```

### Aggressive Settings (Experienced traders)
```python
limits = RiskLimits(
max_drawdown_pct=0.20, # 20% max drawdown
max_position_size_pct=0.10, # 10% per position
daily_loss_limit_pct=0.10 # 10% daily limit
)
```

## Monitoring and Alerts

The system provides comprehensive logging:

```
INFO: Added position monitoring: market_123, quantity: 100
WARNING: Stop-loss triggered for market_123: 0.047 <= -0.05
INFO: Executing stop-loss for position in market_123
INFO: Stop-loss order executed for market_123
```

## Integration with Existing Code

Risk management is designed to be non-intrusive:

- Add `risk_manager` parameter to existing classes
- Existing code continues to work unchanged
- Risk features activate only when configured

## Performance Considerations

- Risk calculations are optimized for real-time use
- Minimal latency impact on websocket processing
- Configurable rate limiting for order execution
- Efficient position tracking with O(1) updates

## Troubleshooting

### Stop-loss not triggering
- Check `stop_loss.enabled` is `True`
- Verify position is registered with risk manager
- Ensure websocket is connected and receiving price updates

### Orders not executing
- Check trading client configuration
- Verify API credentials
- Review rate limiting settings

### High latency
- Reduce number of monitored positions
- Adjust websocket ping intervals
- Consider server-side deployment

## Next Steps

1. Start with paper trading to test risk settings
2. Gradually reduce stop-loss percentages as confidence grows
3. Monitor execution logs for optimization opportunities
4. Consider integrating with external alerting systems

The risk management system provides essential protection for algorithmic trading while maintaining the flexibility to customize risk parameters for different strategies and market conditions.
Loading
Loading