Skip to content

Conversation

@inhacho
Copy link
Collaborator

@inhacho inhacho commented Dec 28, 2025

Implements statistical arbitrage strategy for Elon Musk tweet count markets on Polymarket.

Strategy Logic

  • Calculate average daily tweets from historical data
  • Project final count: current + (avg_daily × days_remaining)
  • Identify profitable ranges around projection
  • Buy ranges with positive expected value (>70% probability coverage)

Based on analysis from @noovd trader strategy.
Source: https://x.com/0xMovez/status/2005002806722203657

Features

  • Auto-discovery of Elon tweets markets
  • Range parsing from outcome strings
  • Expected value calculation
  • Configurable probability targets and order sizes
  • Comprehensive CLI with usage examples

Files

  • examples/elon_tweets_strategy.py: Strategy implementation
  • examples/README.md: Updated with strategy documentation

Closes #40


Generated with Claude Code) | View job run | [Branch: claude/issue-40-20251228-1708](https://github.com/guzus/dr-manhattan/tree/claude/issue-40-20251228-1708

Implements statistical arbitrage strategy for Elon Musk tweet count markets on Polymarket.

Strategy logic:
- Calculate average daily tweets from historical data
- Project final count: current + (avg_daily × days_remaining)
- Identify profitable ranges around projection
- Buy ranges with positive expected value (>70% probability coverage)

Based on analysis from @noovd trader strategy.
Source: https://x.com/0xMovez/status/2005002806722203657

Features:
- Auto-discovery of Elon tweets markets
- Range parsing from outcome strings
- Expected value calculation
- Configurable probability targets and order sizes
- Comprehensive CLI with usage examples

Files:
- examples/elon_tweets_strategy.py: Strategy implementation
- examples/README.md: Updated with strategy documentation

Co-authored-by: inhacho <inhacho@users.noreply.github.com>
@claude
Copy link

claude bot commented Dec 28, 2025

PR Review: Elon Tweets Volume Betting Strategy

Overview

This PR implements a statistical arbitrage strategy for Elon Musk tweet count markets on Polymarket. The implementation follows the repository's architecture well and builds appropriately on the existing Strategy base class.


Code Quality & Best Practices

✅ Strengths

  1. Clean Architecture: Properly extends the Strategy base class and follows established patterns from spread_strategy.py
  2. Well-Documented: Comprehensive docstrings, inline comments, and README documentation
  3. Type Hints: Good use of type annotations throughout
  4. Error Handling: Appropriate try-catch blocks in critical sections
  5. CLI Design: Clear argument parsing with helpful examples in the epilog
  6. Logging: Consistent use of the logger with color coding for readability

🔧 Suggestions

1. CLAUDE.md Violations (Critical per project instructions)

The code violates instruction #1: "Avoid emojis and other non-essential characters"

  • Lines with emojis: Uses multiple emojis in logger output (+, etc.)
  • Recommendation: Remove all emoji characters or ensure they're only in user-facing documentation, not code output

2. Simplify Range Selection Logic (elon_tweets_strategy.py:131-158)

The range selection algorithm could be more explicit:

# Current: Relies on implicit sorting and break condition
# Suggested: Make the selection criteria clearer
for outcome, low, high, price in ranges:
    midpoint = (low + high) / 2
    distance_from_projection = abs(midpoint - projection)
    
    # Only consider ranges within ±50 of projection
    if distance_from_projection <= 50:
        selected.append((outcome, price))
        total_prob += price
        logger.info(...)
        
        if total_prob >= self.min_probability:
            break

3. Magic Numbers (elon_tweets_strategy.py:138)

The ±50 tweets threshold is hardcoded:

if low <= projection + 50 and high >= projection - 50:
  • Recommendation: Make this a configurable parameter (--range-window or similar)

4. Range Parsing Robustness (elon_tweets_strategy.py:173-195)

The _parse_range method could fail silently on malformed data:

  • Issue: Returns None without logging which outcomes were skipped
  • Recommendation: Add debug logging for unparsed outcomes to help troubleshoot market data issues

Potential Bugs & Issues

⚠️ Issue 1: Position Tracking (elon_tweets_strategy.py:209-242)

The _manage_range_position method has a logic issue:

if position < self.max_position:
    buy_orders, _ = self.get_orders_for_outcome(outcome)
    
    if not buy_orders and self.cash >= self.order_size:
        # Places order at best_ask (taking liquidity)
        self.create_order(outcome, OrderSide.BUY, best_ask, self.order_size, token_id)

Problems:

  1. Aggressive liquidity taking: Always buys at best_ask (market taker), which incurs higher fees
  2. No sell logic: The method only implements buying. What happens when you want to exit positions?
  3. Cash check timing: self.cash is only updated during refresh_state() in log_status(), so it may be stale

Recommendations:

  • Consider joining the bid instead of taking the ask to save on fees
  • Implement position exit logic for when the strategy parameters change
  • Document that this is a buy-and-hold strategy if that's intentional

⚠️ Issue 2: Market Discovery Pagination (elon_tweets_strategy.py:248-259)

The pagination logic silently catches all exceptions:

for page in range(1, 10):
    try:
        page_markets = exchange.fetch_markets({"page": page, "limit": 20})
        if not page_markets:
            break
        all_markets.extend(page_markets)
    except Exception:  # Too broad
        break

Issues:

  • Catches and ignores network errors, API errors, authentication failures
  • May return incomplete results without user awareness

Recommendation:

except Exception as e:
    logger.warning(f"Failed to fetch page {page}: {e}")
    break

⚠️ Issue 3: Expected Value Calculation (elon_tweets_strategy.py:163-170)

The EV calculation may mislead users:

cost = sum(price for _, price in selected)
expected_value = (total_prob - cost) * 100

Issue: This assumes:

  1. Current market prices equal the cost to acquire these positions
  2. The probabilities are accurate (they're just market prices)
  3. Doesn't account for fees

Recommendation: Add a disclaimer comment or adjust the calculation to be more conservative


Performance Considerations

1. Polling Interval (elon_tweets_strategy.py:344)

Default 5-minute interval seems appropriate for this strategy type, but:

  • Consider adding a note about the trade-off between responsiveness and API rate limits
  • The market discovery in find_elon_tweets_market could make up to 10 API calls, which may hit rate limits if run frequently

2. WebSocket Usage

The base Strategy class sets up WebSocket for orderbook (strategy.py:128), but this strategy doesn't appear to leverage it much since it's not doing market making. Consider:

  • Documenting that WS is available but not critical for this use case
  • Or disable it if not needed to save resources

Security Concerns

🔒 Low Risk, but Worth Noting:

  1. Real Money Warning: Good that warnings are included in README and docstrings
  2. No Input Validation: The CLI accepts any float/int values for --current, --avg-daily, --days-remaining
    • Recommendation: Add sanity checks (e.g., days_remaining > 0, avg_daily >= 0)
if args.days_remaining <= 0:
    logger.error("Days remaining must be positive")
    return 1
if args.avg_daily < 0:
    logger.error("Average daily tweets cannot be negative")
    return 1
  1. Market Discovery: The keyword-based search could theoretically match unintended markets
    • Current mitigation: Interactive selection is good
    • Enhancement: Add market question preview before trading starts

Test Coverage

❌ Missing Tests

Based on the repository's test structure (tests/test_*.py), this PR should include:

  1. Unit tests for ElonTweetsStrategy:

    • _parse_range() with various input formats
    • _identify_target_ranges() with mock market data
    • Projection calculation accuracy
  2. Integration test:

    • Mock exchange interaction
    • Full strategy setup and teardown

Example test structure:

# tests/test_elon_tweets_strategy.py
def test_parse_range_valid():
    strategy = ElonTweetsStrategy(...)
    assert strategy._parse_range("320-339") == (320, 339)
    assert strategy._parse_range("320 to 339") == (320, 339)
    
def test_parse_range_invalid():
    strategy = ElonTweetsStrategy(...)
    assert strategy._parse_range("invalid") is None
    assert strategy._parse_range("500") is None

def test_projection_calculation():
    # current=221, avg_daily=48, days=3 -> 365
    ...

Recommendation: Add tests before merging, following the pattern in tests/test_base.py


Documentation

✅ Excellent README Documentation

  • Clear usage examples
  • Strategy logic explained well
  • Parameter documentation is thorough
  • Warnings are prominent

📝 Minor Suggestions:

  1. Add a "Limitations" section to README:

    • Requires manual input of current tweet count
    • Probabilities are based on market prices (circular)
    • No automatic re-calibration as time passes
  2. Add example of how to get the input data:

    ## Getting Input Data
    1. Current tweets: Check @elonmusk Twitter/X profile or tracking services
    2. Average daily: Calculate from historical data (past 30 days recommended)
    3. Days remaining: Check market closing date

Summary & Recommendations

Must Fix Before Merge:

  1. ✅ Remove emojis from code (CLAUDE.md violation)
  2. ✅ Add basic unit tests for core logic
  3. ✅ Add input validation for CLI arguments
  4. ✅ Improve error logging in market discovery

Should Fix:

  1. Make the ±50 range threshold configurable
  2. Add sell/exit logic or document buy-and-hold intention
  3. Add logging for skipped outcomes in _parse_range
  4. Consider fee impact in EV calculation

Nice to Have:

  1. Add limitations section to README
  2. Add example data sources to documentation
  3. Consider maker orders instead of taker orders to reduce fees

Overall Assessment

This is a solid implementation that follows the codebase patterns well and provides a useful new strategy. The code quality is generally high with good documentation. Main concerns are:

  • Test coverage (required)
  • CLAUDE.md compliance (emojis)
  • Some edge case handling and user input validation

With the must-fix items addressed, this will be a great addition to the examples. Nice work on the statistical arbitrage implementation!

Suggested Action: Request changes for must-fix items, then approve after addressed.

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.

Elon tweets bet

2 participants