Skip to content

Add Avellaneda-Stoikov market making strategy example#76

Open
guzus wants to merge 1 commit intomainfrom
claude/add-avellaneda-stoikov-example-N31EK
Open

Add Avellaneda-Stoikov market making strategy example#76
guzus wants to merge 1 commit intomainfrom
claude/add-avellaneda-stoikov-example-N31EK

Conversation

@guzus
Copy link
Owner

@guzus guzus commented Jan 28, 2026

Summary

Adds a complete implementation of the Avellaneda-Stoikov optimal market making strategy as an example strategy. This strategy uses inventory-adjusted pricing and optimal spread calculation to balance profit capture against inventory risk in prediction markets.

Key Changes

  • New strategy class: AvellanedaStoikovStrategy that extends the base Strategy class

    • Computes reservation prices adjusted for current inventory position
    • Calculates optimal spreads based on risk aversion and order arrival sensitivity parameters
    • Implements time-decay of inventory penalties as the trading session progresses
    • Includes volatility estimation from recent price history
  • Core algorithm implementation:

    • Reservation price formula: r = s - q * gamma * sigma^2 * (T - t)
    • Optimal spread formula: spread = (2 / gamma) * ln(1 + gamma / k)
    • Bid/ask quotes derived from reservation price ± spread/2
  • Configuration parameters:

    • gamma: Risk aversion (0.1-1.0 range for prediction markets)
    • k: Order arrival sensitivity (10-100 range)
    • time_horizon_hours: Trading session length
    • volatility_window: Ticks used for volatility estimation
    • Additional controls: min_spread, max_position, order_size, etc.
  • Market discovery utilities:

    • find_market_id(): Search markets by slug with optional index selection
    • prompt_market_selection(): Interactive market selection when multiple matches found
  • Command-line interface: Full argument parsing for all strategy parameters with environment variable fallbacks

Implementation Details

  • Price volatility is estimated from recent tick-level changes and scaled to the full trading session
  • Inventory penalty decays to zero as remaining time approaches zero, allowing tighter quotes near session end
  • Orders are continuously updated based on computed bid/ask prices with stale order cancellation
  • Position limits and cash constraints are enforced before placing orders
  • Prices are clamped to valid prediction market range [tick_size, 1.0 - tick_size]

https://claude.ai/code/session_01Wvgt2qrSTA2VvaQyHTrtJT

Implements the optimal market making model from "High-frequency trading
in a limit order book" (Avellaneda & Stoikov, 2008) adapted for
prediction markets.

The strategy computes a reservation price adjusted for inventory risk
and quotes bid/ask at optimal distances. Key features:
- Reservation price shifts proportionally to inventory, encouraging
  mean-reversion toward zero position
- Optimal spread derived from risk aversion (gamma) and order arrival
  sensitivity (k) parameters
- Volatility estimated from rolling window of absolute price changes
- Time-decaying inventory penalty (shrinks as session ends)
- Prices clamped to valid [0, 1] prediction market range

Reference: https://github.com/fedecaccia/avellaneda-stoikov

https://claude.ai/code/session_01Wvgt2qrSTA2VvaQyHTrtJT
@netlify
Copy link

netlify bot commented Jan 28, 2026

Deploy Preview for dr-manhattan-oss canceled.

Name Link
🔨 Latest commit a63cd9f
🔍 Latest deploy log https://app.netlify.com/projects/dr-manhattan-oss/deploys/6979a7bd7bfa820008a592c4

@netlify
Copy link

netlify bot commented Jan 28, 2026

👷 Deploy Preview for dr-manhattan-oss processing.

Name Link
🔨 Latest commit a63cd9f
🔍 Latest deploy log https://app.netlify.com/projects/dr-manhattan-oss/deploys/6979a7bd7bfa820008a592c4

@claude
Copy link

claude bot commented Jan 28, 2026

Pull Request Review: Avellaneda-Stoikov Market Making Strategy

SUMMARY
This PR adds a well-implemented Avellaneda-Stoikov optimal market making strategy as an example. The implementation is mathematically sound and follows the codebase conventions.

STRENGTHS

  1. Code Quality & Best Practices
  • Clean architecture: Properly extends the Strategy base class and follows established patterns
  • Excellent documentation: Comprehensive docstrings explaining the algorithm, formulas, and parameters
  • Consistent style: Follows the codebase conventions for logging, color usage, and error handling
  • Good type hints throughout
  • Mathematically correct: Formulas match the Avellaneda-Stoikov paper correctly

CRITICAL ISSUES

  1. Division by Zero Risk (line 196)
    If check_interval is 0, division by zero occurs in:
    ticks_per_period = self.time_horizon / self.check_interval
    FIX: Add validation in init to ensure check_interval > 0

  2. Volatility Estimation Edge Case (lines 173-196)
    When len(history) < 2, returns None and strategy skips quoting entirely
    SUGGESTION: Add fallback minimum volatility or document warmup period

  3. Parameter Validation Missing
    No validation for: gamma > 0, k > 0, time_horizon > 0, volatility_window >= 2
    These can cause math errors (division by zero, log of negative numbers)
    FIX: Add parameter validation in init

HIGH PRIORITY ISSUES

  1. Code Duplication: find_market_id() Function
    This exact function appears in:

    • examples/avellaneda_stoikov_strategy.py (lines 236-275)
    • examples/spread_strategy.py (lines 37-87)
    • examples/spike_strategy.py (lines 271-313)
      VIOLATION: CLAUDE.md Rule 2 states "Purge unnecessary code and files"
      FIX: Extract to dr_manhattan/utils/market_search.py
  2. Environment Variable Overuse
    Per CLAUDE.md Rule 4: "DO NOT place many variables in .env file. Place them in the code instead"
    Strategy parameters (MAX_POSITION, ORDER_SIZE, MAX_DELTA, CHECK_INTERVAL) should have defaults in code
    Only credentials and exchange config should be in .env
    FIX: Remove env var fallbacks for strategy params

MEDIUM PRIORITY ISSUES

  1. Invalid Spread Scenario (line 162)
    Silently skips when bid_price >= ask_price
    SUGGESTION: Log warning at DEBUG level for debugging

  2. Time Decay Logic (line 147)
    If strategy runs beyond time_horizon, remaining stays at 0 and disables inventory penalties
    SUGGESTION: Document this behavior

  3. Missing Volatility Logging
    Current volatility estimates not shown in status logs
    SUGGESTION: Add to log_status for monitoring

PERFORMANCE CONSIDERATIONS

Positive:

  • Efficient use of deque with maxlen (no memory leak)
  • WebSocket orderbook integration
  • Minimal computational overhead

Improvements:

  • Volatility calculation is O(n) every tick, consider incremental variance for large windows
  • Redundant refresh_state() calls in some scenarios

SECURITY CONCERNS

Good practices:
✅ Prices clamped to valid range [tick_size, 1.0 - tick_size]
✅ Position limits enforced
✅ Cash balance checked
✅ Exception handling around orders

Concerns:

  • No order size validation (should check order_size > 0 and meets exchange minimums)
  • Heavy quoting could trigger rate limits (document or handle)

TEST COVERAGE

Missing: 396 lines of new code with 0 test coverage

Recommendations:

  1. Unit tests for _estimate_volatility(), _optimal_spread(), parameter validation, edge cases
  2. Integration tests for mocked exchange interactions, tick cycles, cleanup
  3. Property-based tests for bid < ask invariant, positive spread, valid price range

RECOMMENDATIONS

High Priority:

  1. Extract find_market_id() to shared utility
  2. Add parameter validation in init
  3. Fix division by zero risk with check_interval
  4. Reduce environment variable usage per CLAUDE.md
  5. Add tests (minimum: unit tests for core calculations)

Medium Priority:
6. Add volatility fallback for cold start
7. Log warnings for invalid spread scenarios
8. Document time decay behavior
9. Add volatility to status logging

VERDICT

Approve with changes

This is a high-quality implementation of a sophisticated market making strategy. The code is well-structured, mathematically sound, and follows codebase conventions. However, it requires:

  1. Parameter validation to prevent runtime errors
  2. Code deduplication per CLAUDE.md guidelines
  3. Test coverage for core algorithm components
  4. Minor fixes for edge cases

With the suggested fixes, this will be an excellent addition to the examples.

ADDITIONAL NOTES

  • The reference to the academic paper in comments is excellent
  • Parameter ranges in docstrings (0.1-1.0 for gamma, 10-100 for k) are helpful
  • Consider adding documentation to wiki if one exists per CLAUDE.md Rule 6

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.

2 participants