This repository contains an end-to-end algorithmic trading system built for research, simulation, paper trading, and live execution through Alpaca.
The bot combines:
- Probabilistic forecasting (Bayesian regression, Gaussian Processes)
- Technical indicators (Bollinger Bands, RSI, momentum)
- Game-theoretic payoff analysis (market type inference, Nash equilibrium, Minimax strategies)
- Explicit position-aware decision logic before executing or rejecting trades
This project uniquely integrates signaling game theory into live trading:
- Market Type Inference: Real-time classification into Trend, Range, Manipulator, or Exhausted states
- Equilibrium Payoff Calculation: Nash equilibrium analysis for different trader types
- Intuitive Criterion Filtering: Peters-style elimination of dominated strategies
- Minimax Decision-Making: Risk-minimizing position sizing based on game-theoretic payoff matrices
- Rational Deviation Analysis: Detects when informed traders should deviate from equilibrium
- Real-time signal generation with confidence scoring
- Adaptive threshold tuning based on trade history
- Multi-mode execution (simulation, paper, live)
- Position-aware decision gates
- Risk management with stop-loss and take-profit
- SQLite persistence for full audit trail
- Monte Carlo strategy simulation
- Performance analytics with win/loss tracking
This project is split into two major parts:
- Production Trading Engine (
logic/folder): Full-featured algorithmic trading system with game theory - Learning & Research (
Exercises/folder): Educational notebooks and ML finance study material
If you only want to understand the trading bot, start with the files in logic/ and trading.ipynb.
This repository remains focused on the algorithmic trading engine (forecasting, stochastic modeling, game theory, execution, and analytics).
If you use local personal portfolio exports (for example, Fidelity account files) for withdrawal planning, keep that workflow private and local-only. Sensitive account exports should not be committed to git.
Use a separate private notebook workflow for personal withdrawal planning, and keep production algo-engine development in the tracked codebase.
At a high level, each cycle does this:
- Generate signals for each symbol in your universe.
- Read current portfolio state (flat/long/short).
- Decide action with clear logic gates.
- Build order plan (size + optional TP/SL).
- Execute in simulation, paper, or live mode.
- Persist decisions/trade attempts for auditing and analysis.
This system implements information-asymmetric signaling game theory from financial markets literature:
The bot classifies market regimes into four types based on recent price action and volatility:
- t_trend - Directionally persistent moves; traders follow fundamentals
- t_manipulator - High-volatility regime with possible informed manipulation
- t_exhausted - Overbought/oversold extremes; mean reversion likely
- t_range - Low-trending, bounded movements; mean-reverting behavior
Inference Method: Uses EMA-based trend strength, rolling volatility of volatility, and Bollinger Band width to compute Bayesian posterior probabilities over market types.
For each market type, computes Nash equilibrium payoffs x(t):
- Expected returns are discounted from one-step forecasts
- Persistence and damping are regime-dependent
- Reflects what equilibrium traders earn in each regime
Constructs posterior belief distribution β over market types:
- Prior: Regime probabilities (trend, range, volatility)
- Likelihood: Signal type (buy/sell/hold), RSI levels, Bollinger z-scores
- Posterior: Normalized beliefs βi = p(type | observables)
Used to weight payoffs when trader types have heterogeneous beliefs.
Computes off-equilibrium deviation payoffs m(t, A) for each market type:
- Signal price target: Expected move if signal is correct
- Hunting cost: Adverse selection from informed traders
- Liquidity profit: Execution benefits in responsive regimes
- Net manipulator payoff: Asymmetric payoff for informed traders
Deviation payoffs reflect: What do informed traders earn by deviating from equilibrium?
Implements Peters-style elimination of irrational beliefs:
Rule: Eliminate market type t if m(t, A) < x(t)
- If deviation payoff is worse than equilibrium, traders won't deviate
- Remaining types are survivor types under IC
Applied to every signal:
- Extract prior beliefs over types
- Compute equilibrium and deviation payoffs
- Eliminate dominated types
- Update posterior belief distribution
- Keep signal only if at least one rational type survives
Uses game-theoretic minimax criterion for position sizing:
Position Size = Base × minimax_multiplier(payoff_matrix)
Where minimax_multiplier reflects:
- Alignment of equilibrium and deviation payoffs across market types
- Robustness to regime uncertainty
- Confidence that signal is rational across all possible types
Range: 0.0 (no edge) to 1.0 (strong alignment across types)
The signal engine (logic/signal_engine.py) wraps forecast functions from logic/trading_functions.py:
unified_bayesian_gp_forecast(...)- Ensemble of Bayesian & Gaussian Process modelscalculate_bollinger_bands(...)- Price extremes and mean reversion signalsbayesian_rsi_signal(...)- Momentum with probabilistic interpretation
Game Theory Integration:
- Compute market regime (trend strength, volatility, range-bound behavior)
- Build expected return path over 5-step horizon
- Calculate equilibrium payoffs for each market type
- Infer trader type beliefs from RSI, Bollinger Bands, regime
- Compute deviation payoffs (what informed traders earn by trading)
- Apply Intuitive Criterion filter (eliminate irrational types)
- Compute minimax multiplier for position sizing
Signal Output: Normalized Signal objects with:
- Type:
buy,sell, orhold - Confidence score (0.0-1.0)
- Probability of profit
- Game-theoretic metadata:
- Market regime probabilities
- Equilibrium payoffs by type
- Deviation payoffs by type
- Type beliefs (posterior over market types)
- Minimax alignment score
logic/portfolio_state.py creates a unified position view for every symbol:
flat(no position)longshort
It supports both broker-backed states (paper/live) and in-memory simulation state.
logic/execution_engine.py is the core of the bot. It enforces explicit rules in decide_action(...):
- BUY + flat -> buy
- BUY + long -> hold
- SELL + long -> sell
- SELL + flat + shorting disabled -> rejected
- HOLD -> hold
This is where behavior is intentionally deterministic and auditable.
If action is actionable (buy or sell):
build_order_plan(...)computes size with risk rules and TP/SL levels.execute_order_plan(...)routes by mode:simulation: updates in-memory portfoliopaper/live: submits orders to Alpaca (marketorbracket)
The system supports two logging paths:
- CSV decision logs (
logic/trade_log.py, default:trade_logs/decisions.csv) - SQLite persistence (
logic/sqlite_store.py, default:trade_logs/trading.db)
run_trading_cycle(...) can write broker trade attempts and outcomes to SQLite when a db_path is provided.
-
logic/data_structures.py: Type-safe dataclassesSignal: buy/sell/hold with confidence, payoff metadataPositionState: flat/long/short trackingExecutionConfig: configuration parametersOrderPlan: size, TP, SL, order typeDecisionLogEntry: audit trail entryRLObservation: state features for learning
-
logic/signal_engine.py: Signal generation pipeline- Forecast ensemble (Bayesian + Gaussian Process)
- Bollinger Bands integration
- RSI momentum signals
- Game theory integration (regime → equilibrium → minimax)
-
logic/portfolio_state.py: Position state management- Unified interface for simulation/paper/live
- Handles long, short, and flat positions
- Integrates with Alpaca broker API
-
logic/execution_engine.py: Core trading orchestration- Decision logic gates (BUY+flat→buy, SELL+long→sell)
- Order plan building with risk limits
- Execution routing (simulation/paper/live)
- Full trading cycle runner:
run_trading_cycle(...)
-
logic/risk_management.py: Position sizing & riskcalculate_position_size(...): kelly-fraction based sizingcalculate_minimax_multiplier(...): game-theoretic position adjustmentmcmc_optimize_thresholds(...): Bayesian parameter tuning- Adaptive confidence threshold updates
-
logic/position_evaluator.py: Live position analytics- Compares current prices to original signal quality
- Tracks performance vs forecast accuracy
- Used for threshold auto-tuning
-
logic/game_utils.py: Signaling game theory core- Market regime inference: compute_market_regime(...)
- Equilibrium payoff calculation: calculate_equilibrium_payoffs(...)
- Type belief inference: infer_type_beliefs(...)
- Expected return path projection: build_expected_return_path(...)
- Risk-weighted deviation payoff: build_deviation_from_market_data(...)
-
logic/intuitive_criterion.py: Peters-style IC filteringsurvives_intuitive_criterion(...): Eliminate irrational types- Prior belief normalization
- Posterior belief updating
- Survivor type identification
-
logic/trading_functions.py: Forecast ensembleunified_bayesian_gp_forecast(...): Combined forecastsbayesian_linear_regression(...): Bayesian point forecastsgaussian_process_forecast(...): GP with uncertaintygbm(...): Geometric Brownian Motion simulator
-
logic/signal_engine.py: Signal generation & filteringgenerate_signals(...): Full pipelinefilter_signals_by_thresholds(...): Confidence filtering- Game theory context integration
-
logic/sqlite_store.py: SQLite database layer- Schema: decisions, accounts, positions, trades
- Durable audit trail
- Query interface for analytics
-
logic/trade_log.py: CSV logginglog_decision(...): Append to CSV decision log- Default:
trade_logs/decisions.csv
-
logic/alpaca_exercises.py: Alpaca broker integration- Account management:
get_account_summary(...) - Order execution:
place_bracket_order(...) - Position retrieval:
get_positions(...)
- Account management:
-
logic/trading_assistant.py: Recommendation enginetrading_assistant(...): Generate actionable recommendations- Evaluates strategy performance
- Suggests next actions (backtest, tune, simulate, etc.)
-
logic/math_logic/montecarlo_sims.py: Monte Carlo simulationmonte_carlo_strategy_simulation(...): Strategy P&L projection- Path simulation with draw-down tracking
- Returns distribution analysis
-
logic/math_logic/series_sequences.py: Mathematical sequences- Arithmetic and geometric progressions
- Series summation utilities
-
logic/math_logic/polar_coordinates_finance.py: Polar space analysisbayesian_polar_signal(...): Bayesian belief in polar coordinates- Visual representation of market state
Configure mode via ExecutionConfig:
simulation: no broker calls, fully local behaviorpaper: Alpaca paper account (safe real integration)live: real market execution
Important safety switches:
dry_run=True: never submit real ordersallow_short_selling=False: blocks opening shorts by default
- Real-time signal generation (buy/sell/hold)
- Multi-mode execution (simulation, paper, live)
- Position state tracking (flat, long, short)
- Deterministic decision gates
- Position-aware order planning
- Risk management with TP/SL
- Short selling support (optional)
- Bracket order execution
- Market and limit order types
- Bayesian linear regression
- Gaussian Process forecasting
- Ensemble forecast aggregation
- Bollinger Bands (price extremes)
- RSI momentum signals
- Bayesian RSI interpretation
- Confidence scoring
- Probability of profit calculation
- Multi-symbol batch processing
- Market regime inference (4 types)
- Equilibrium payoff calculation
- Type belief inference (Bayesian)
- Intuitive Criterion filtering
- Deviation payoff analysis
- Minimax position sizing
- Rational strategy elimination
- Kelly Criterion position sizing
- Minimax-adjusted sizing
- Stop-loss and take-profit levels
- Max positions limit
- Risk-per-trade percentage
- Adaptive threshold tuning
- Position evaluation analytics
- Win/loss tracking
- Profit factor analysis
- SQLite trade log with full schema
- CSV decision log
- Account state snapshots
- Position history
- Trade outcomes
- Decision audit trail
- Query interface for analytics
- Monte Carlo strategy simulation
- P&L distribution analysis
- Draw-down tracking
- Win rate calculation
- MCMC threshold optimization
- Performance statistics
- Trading assistant recommendations
- Position performance evaluation
- Alpaca API connection
- Paper trading account
- Live trading account
- Account balance retrieval
- Position listing
- Order submission (market & bracket)
- Order tracking
- Credential validation
- Reinforcement learning exercises
- ML-in-finance notebooks
- Bollinger Bands analysis
- RSI strategy notebooks
- Option pricing (QLBS model)
- Q-Learning wealth management
- Inverse RL models
- Chapter-based curriculum
- Define stock universe
- Configure execution mode (simulation/paper/live)
- Set risk parameters (TP%, SL%, risk per trade)
- Set threshold values (MIN_CONF, MIN_PROB_UP)
- Compute market regime for each stock
- Generate buy/sell/hold signals
- Calculate equilibrium & deviation payoffs
- Apply Intuitive Criterion filtering
- Compute minimax multipliers
- Evaluate open positions
- Compare to original predictions
- Calculate performance scores
- Recommend threshold adjustments
- Retrieve current positions
- Apply decision gates (BUY+flat, SELL+long, etc.)
- Build order plans with TP/SL
- Route to execution (simulation/paper/live)
- Log decisions to CSV
- Store trade outcomes to SQLite
- Update account snapshots
- Track performance metrics
- Run Monte Carlo simulation
- Generate strategy recommendations
- Tune thresholds via MCMC
- Export analytics
The orchestration function is run_trading_cycle(...) in logic/execution_engine.py.
Minimal flow:
signals = generate_signals(universe, config)position_states = get_position_states(universe, config, alpaca_client=trading_client, sim_portfolio=sim_portfolio)decision_log = run_trading_cycle(...)- Persist decisions with CSV and/or SQLite
- Python 3.10+
- Alpaca API credentials (for paper/live)
pip install -r requirements.txtThe primary workflow currently lives in trading.ipynb:
- Configure parameters and mode (
dry_runrecommended first). - Verify Alpaca connection (paper account first).
- Run forecasting and trading cycle cells.
- Review logs in
trade_logs/.
For implementation details, see TRADING_ENGINE_README.md and COMPLETE_WORKFLOW.md.
logic/: production trading modulestrade_logs/: runtime logs and databasetrading.ipynb: notebook-driven execution workflowExercises/: educational notebooks and ML finance study material
- This project is educational/research software and not financial advice.
- Always validate in
dry_runandpapermode before any live execution. - Live trading carries real financial risk.