Skip to content

Conversation

@konard
Copy link
Member

@konard konard commented Sep 11, 2025

🎯 Summary

This PR implements the Kelly Criterion algorithm to maximize long-term profit through optimal position sizing in the TraderBot. The Kelly Criterion is a mathematical formula developed by John Kelly at Bell Labs in 1956, widely used by professional traders and investors for optimal capital allocation.

🔢 Mathematical Foundation

Formula: f = (bp - q) / b

  • f = fraction of capital to invest
  • b = profit/loss ratio (odds)
  • p = probability of winning
  • q = probability of losing (1-p)

🚀 Key Features

✅ Optimal Position Sizing

  • Calculates optimal lot size based on Kelly Criterion formula
  • Prevents over-betting and under-betting
  • Maximizes long-term geometric growth rate

✅ Dynamic Learning

  • Automatically calculates win probability and profit/loss ratio from completed trades (10+ minimum)
  • Adapts position sizing based on actual performance
  • Falls back to configured values when insufficient historical data

✅ Risk Management

  • Configurable maximum fraction limit (default 25%) to prevent excessive risk
  • Returns 0% allocation for negative expected value strategies
  • Built-in safeguards against calculation errors

✅ Comprehensive Configuration

{
  "TradingSettings": {
    "UseKellyCriterion": true,
    "WinProbability": 0.55,
    "ProfitLossRatio": 1.2,
    "KellyFractionLimit": 0.25
  }
}

📊 Implementation Details

Core Components

  • KellyCriterion.cs: Static calculation methods and historical analysis
  • TradingSettings.cs: Added Kelly configuration parameters
  • TradingService.cs: Integrated Kelly sizing into existing trading logic

Real-World Examples

Scenario Win Rate P/L Ratio Max Risk Kelly Result
Conservative 52% 1.1:1 10% 8.4% of capital
Aggressive 65% 1.5:1 50% 41.7% of capital
High Win Rate 80% 0.8:1 25% 25.0% (capped)
Breakeven 50% 1.0:1 25% 0.0% (negative EV)

Behavior Changes

  • When Enabled: Uses Kelly formula for position sizing instead of "all available cash"
  • When Disabled: Falls back to original behavior with no changes
  • Learning Mode: Switches to historical metrics after 10+ completed trades

🧪 Testing

Created comprehensive test suite covering:

  • Mathematical accuracy verification
  • Edge case handling (negative probabilities, ratios)
  • Maximum fraction limiting
  • Historical metrics calculation
  • Real-world scenario simulations

All tests pass

📚 Documentation

Added detailed documentation in examples/KELLY_CRITERION_README.md including:

  • Mathematical foundation and formulas
  • Configuration parameters and examples
  • Risk considerations and best practices
  • Implementation details and testing instructions

⚠️ Risk Considerations

  1. Accurate Probabilities Required: Kelly requires accurate win rate and profit/loss estimates
  2. Volatility: Full Kelly can be volatile; fractional Kelly recommended (25% or less)
  3. Market Conditions: Assumes consistent conditions; may vary during regime changes
  4. Historical Data: Minimum 10 trades needed for dynamic learning

📈 Benefits

  • Optimal Capital Allocation: Mathematically proven to maximize long-term growth
  • Risk Management: Automatically reduces position size for poor-performing strategies
  • Adaptability: Learns from actual performance and adjusts over time
  • Professional Standard: Used by Warren Buffett and many hedge funds

🔗 References

  • Kelly, J. L. (1956). "A New Interpretation of Information Rate"
  • Thorp, E. O. (2006). "The Kelly Capital Growth Investment Criterion"
  • Video reference: https://youtu.be/_FuuYSM7yOo

🛠️ Test Instructions

  1. Build and run tests:
    cd examples
    dotnet build && dotnet run
  2. Configure Kelly parameters in appsettings files
  3. Enable with "UseKellyCriterion": true
  4. Monitor logs for Kelly calculation details

Closes #231

🤖 Generated with Claude Code

Adding CLAUDE.md with task information for AI processing.
This file will be removed when the task is complete.

Issue: #231
@konard konard self-assigned this Sep 11, 2025
konard and others added 2 commits September 11, 2025 11:22
This implementation adds the Kelly Criterion algorithm to maximize long-term profit while managing risk through optimal capital allocation.

## Key Features
- Kelly Criterion calculator with mathematical accuracy
- Dynamic learning from trade history (10+ trades minimum)
- Configurable risk limits and safety parameters
- Integration with existing trading strategy
- Comprehensive test suite with real-world scenarios

## Configuration
- UseKellyCriterion: Enable/disable Kelly position sizing
- WinProbability: Initial win rate estimate (0.0-1.0)
- ProfitLossRatio: Initial profit/loss ratio estimate
- KellyFractionLimit: Maximum risk fraction (default 0.25)

## Formula: f = (bp - q) / b
Where f = fraction of capital, b = profit/loss ratio, p = win probability, q = loss probability

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
@konard konard changed the title [WIP] Trader Bot: Use Kelly Creterion to maximize profit Trader Bot: Implement Kelly Criterion for optimal position sizing Sep 11, 2025
@konard konard marked this pull request as ready for review September 11, 2025 08:31
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Trader Bot: Use Kelly Creterion to maximize profit

2 participants