Rank model-vs-market mispricings. Run offline backtests. Track paper trades. Score forecast calibration. Operate with dry-run safety gates first.
Install ยท Quick Start ยท Features ยท CLI ยท Dashboard ยท Safety ยท Contributing
Market Edge is an experimental, research-first workbench for prediction-market quant analysis. It helps you:
- Screen event markets for edge, liquidity, risk, and confidence.
- Size positions with Kelly and fractional-Kelly logic.
- Backtest trade ledgers offline and emit dashboard-ready metrics.
- Paper-trade locally with an append-only JSONL ledger.
- Calibrate forecast probabilities against settled outcomes.
- Blend multi-source weather inputs into model probabilities.
- Audit every decision, intent, and result in local SQLite.
The current implementation focuses on Kalshi weather markets. The math, state, execution, and research primitives are written so the system can expand to other event-market categories later.
Status: experimental and research-first. Live trading is gated behind multiple safety checks and is off by default. See Safety First before considering live use.
Pick the one-shot path that matches your setup. No Python knowledge required for Homebrew or Docker.
brew tap ericgrill/tap
brew install --HEAD marketedgeThis installs the marketedge CLI globally. Upgrades are brew reinstall --HEAD marketedge.
git clone https://github.com/EricGrill/marketedge.git
cd marketedge
docker compose up webThen open http://localhost:4173 for the web dashboard. Run CLI commands with:
docker compose run --rm marketedge doctor
docker compose run --rm marketedge --helpuvx --from git+https://github.com/EricGrill/marketedge.git marketedge --helpuvx downloads, builds, and runs the CLI in one shot without leaving a global install behind. Re-run the same command to get the latest main.
git clone https://github.com/EricGrill/marketedge.git
cd marketedge
python3.12 -m venv .venv
source .venv/bin/activate
python -m pip install --upgrade pip
pip install -r requirements.txt -c constraints.txt| Capability | What You Get |
|---|---|
| Opportunity Ranking | Batch-score candidate markets by fee-adjusted edge, EV, spread, liquidity, confidence, and Kelly sizing. |
| Offline Backtesting | Replay CSV trade ledgers with execution realism, drawdown, Sharpe-like score, and net P&L. |
| Paper Trading | Record no-account buy/sell/selltle events locally before risking capital. |
| Calibration Scoring | Compare forecast probabilities to actual outcomes and surface over/under-confidence. |
| Execution Modeling | Simulate order-book fills, partial fills, slippage, and effective average price. |
| Experiment Tracking | Create, compare, and attach artifacts to research experiment runs. |
| Local Dashboard | Static web dashboard + Textual TUI, no API credentials required. |
| Audit Trail | SQLite-backed audit events for decisions, intents, refusals, and results. |
After installing via Homebrew, Docker, uvx, or Python:
No API key is needed for local workflows. To use API-backed commands, copy the config template:
cp .env.example .envKeep
KALSHI_SANDBOX=trueunless you are intentionally working against a live environment.
Initialize local state and run a readiness check:
marketedge db init
marketedge doctorLaunch the TUI dashboard:
marketedge dashboardOr start the static web dashboard:
python -m http.server 4173 -d web
# open http://localhost:4173The Click CLI is the main operator interface:
marketedge --helpIf you installed from source without the marketedge entry point, use:
python -m src.cli --help| Command | Purpose |
|---|---|
doctor |
Local setup and readiness checks. |
db |
Initialize SQLite, inspect migrations, view/append audit events. |
dashboard |
Launch the Textual TUI. |
dashboard-data |
Export dashboard-ready JSON from local state. |
analyze |
Inspect one ticker/model-probability opportunity. |
collect-snapshots |
Persist market quotes/orderbook snapshots into local SQLite. |
opportunities |
Rank offline candidates by edge, liquidity, risk, and confidence. |
strategies |
List, inspect, enable/disable, and dry-run registered strategies. |
trade |
Run the weather strategy loop (dry-run by default). |
positions / portfolio |
Inspect local SQLite state. |
backtest |
Replay a CSV trade ledger and optionally write dashboard JSON. |
calibration-score |
Score forecast calibration from files or persisted forecasts. |
experiments |
Create, list, show, compare, and attach artifacts to experiment records. |
paper |
Record local no-account paper orders, positions, and settlements. |
weather |
Fetch and blend weather forecast inputs. |
formulas |
Display implemented quant formula references. |
If the virtual environment is not activated, use .venv/bin/marketedge instead of marketedge.
The web dashboard is a static, no-account UI under web/. It runs without Kalshi credentials or a backend:
python -m http.server 4173 -d webThen open http://localhost:4173.
The dashboard ships with built-in sample data and hydrates from local artifacts when present:
web/data/backtest-summary.jsonโ generated bybacktest --json-out.web/data/dashboard.jsonโ generated bydashboard-data.
web/data/dashboard.json can include market snapshots, portfolio state, open positions, paper-trading state, and backtest metrics. It is a generated local artifact and is ignored by git.
Launch the Textual dashboard from the CLI:
marketedge dashboardIt shows local portfolio state, open positions, recent signals, scanner controls, risk metrics, and settings. Scanner controls run a bounded local scan over collected SQLite market snapshots by default, settings are validated and staged at runtime, and no live orders are placed from the TUI.
marketedge/
โโโ CLAUDE.md # Agent/project handoff guidance
โโโ README.md # Operator and contributor documentation
โโโ requirements.txt # Python dependencies
โโโ .env.example # Local config template
โโโ src/
โ โโโ cli.py # Click CLI entry point
โ โโโ dashboard.py # Dashboard JSON payload builder
โ โโโ doctor.py # Local readiness checks
โ โโโ opportunities.py # Ranked opportunity scanner
โ โโโ paper.py # Append-only paper trading ledger
โ โโโ backtesting.py # Offline replay and backtest metrics
โ โโโ calibration.py # Forecast calibration scoring
โ โโโ config.py # Environment-driven configuration
โ โโโ execution.py # Fill/slippage/queue execution modeling
โ โโโ experiments.py # Local experiment registry and comparison
โ โโโ formulas.py # Quant engine and screening math
โ โโโ orders.py # Append-only order lifecycle ledger
โ โโโ safety.py # Live-trading safety gate (fails closed)
โ โโโ settlements.py # Offline settlement outcome resolver
โ โโโ state.py # SQLite state manager and SQLAlchemy models
โ โโโ logging_config.py # Central logging configuration
โ โโโ utils.py # Shared UTC datetime/timestamp helpers
โ โโโ api/client.py # Kalshi REST/WebSocket client and weather scanner
โ โโโ strategies/weather.py
โ โโโ tui/app.py # Textual dashboard
โ โโโ weather/data.py # Weather data fetchers and model blend inputs
โโโ tests/ # Regression tests for CLI, state, math, ledgers, and artifacts
โโโ web/
โโโ index.html
โโโ app.js
โโโ styles.css
โโโ data/backtest-summary.json
marketedge db init --db-path data/kalshi_quant.db
marketedge db migrations --db-path data/kalshi_quant.db
marketedge db audit --db-path data/kalshi_quant.dbThe default storage path is MARKETEDGE_DB_PATH when set, otherwise data/kalshi_quant.db. First-run initialization creates the SQLite schema, records the active schema version in schema_migrations, and ensures an empty portfolio row exists. The repository also includes an Alembic initial migration under migrations/ for reproducible schema setup outside the app startup path.
Manual audit events can be appended for research or dry-run decisions:
marketedge db audit-record \
--event-type decision \
--subject weather-screen \
--ticker RAIN-NYC-TEST \
--payload action=pass \
--payload edge=0.12marketedge doctor
marketedge doctor --strictdoctor checks Python/runtime modules, .env, Kalshi credential presence without printing secrets, sandbox mode, local SQLite storage, and dashboard artifact presence. --strict treats warnings as failures.
marketedge dashboard-data \
--out web/data/dashboard.json \
--paper-ledger data/paper-ledger.jsonl \
--backtest-summary web/data/backtest-summary.jsonThe web dashboard will use web/data/dashboard.json when present and fall back to built-in sample data when it is missing.
marketedge analyze \
--ticker RAIN-NYC-2026-05-15 \
--model-prob 0.65 \
--side yes \
--yes-bid 39 \
--yes-ask 41 \
--resolution-date 2026-06-18T20:00:00Zanalyze never uses placeholder quotes. Offline/no-account analysis requires explicit quote inputs (--yes-bid/--yes-ask, --no-bid/--no-ask, or generic --bid/--ask). API-backed users may pass --fetch to retrieve the current market and orderbook for a ticker when Kalshi credentials are configured.
marketedge collect-snapshots \
--ticker HIGHNY-26JUN18-B88.5 \
--iterations 1
marketedge collect-snapshots --weather-scan --limit 50 --iterations 3 --interval 30Snapshots capture ticker/title metadata, YES/NO quotes, last price, volume, open interest, timestamp, and source into SQLite. dashboard-data exports the latest collected snapshots for the web dashboard.
marketedge opportunities path/to/candidates.csv \
--bankroll 10000 \
--json-out web/data/opportunities.jsonCandidate CSV/JSON/JSONL rows require:
tickermodel_probabilityyes_bidyes_ask
Optional fields include title, no_bid, no_ask, confidence, volume, open_interest, and resolution_date.
Results include rank, YES/NO side, action, score, fee-adjusted edge, expected value, sizing hint, annualized yield, risk of ruin, confidence, and reason codes such as EDGE_OK, SPREAD_TOO_WIDE, and LOW_CONFIDENCE.
marketedge backtest path/to/trades.csv --bankroll 10000
marketedge backtest path/to/trades.csv \
--bankroll 10000 \
--json-out web/data/backtest-summary.jsonRequired trade CSV columns:
timestamptickersideentry_priceexit_pricequantitymodel_probability
Optional columns include confidence, entry_fee, and exit_fee.
Settlement CSV/JSONL rows require ticker, settled_at, and winning_side.
yes_settlement_price, settlement_value, or settlement_price may be
provided explicitly; otherwise the resolver derives 100 for YES winners and
0 for NO winners.
Forecast CSV/JSONL rows require timestamp, ticker, and model_probability.
Optional strategy, market_category, and event_type fields produce grouped
calibration summaries.
Use calibration-score to score file-based forecasts or, when --forecasts is
omitted, forecasts persisted by strategy runs:
marketedge calibration-score \
--settlements data/settlements.csv \
--json-out web/data/calibration-summary.jsonfrom src.execution import ExecutionModel, ExecutionOrder, OrderBookLevel, OrderBookSnapshot
book = OrderBookSnapshot(
asks=[OrderBookLevel(price=40, quantity=100), OrderBookLevel(price=41, quantity=100)]
)
execution = ExecutionModel().fill(
ExecutionOrder(action="buy", contract_side="yes", quantity=120),
book,
)
executed_trade = ExecutionModel().apply_to_backtest_trade(trade, execution)Execution metadata is carried into backtest trade results so summaries can show requested quantity, filled quantity, unfilled quantity, and effective average entry price.
marketedge experiments create \
--strategy wx-meanrev \
--param edge=0.04 \
--data-ref data/snapshots/wx.jsonl \
--artifact web/data/backtest-summary.json \
--model-version v1
marketedge experiments list
marketedge experiments show <run-id>
marketedge experiments compare <run-id-a> <run-id-b>
marketedge experiments add-artifact <run-id> path/to/artifact.jsonExperiment records are append-only JSONL in data/experiments.jsonl by default.
Comparison loads referenced JSON artifacts when present and reports metric deltas such as return, net P&L, Sharpe-like score, drawdown, and average edge.
marketedge strategies list
marketedge strategies inspect weather
marketedge strategies disable relative-value
marketedge strategies enable relative-value
marketedge strategies run weather --json-out web/data/weather-run.jsonBuilt-in strategies are registered by stable IDs: weather, relative-value,
catalyst-calendar, calibration-ensemble, and liquidity-overlay. Runs are
dry-run/local by default and persist a SQLite run record with status, warnings,
signal count, artifact paths, and explanation payload.
marketedge paper order \
--ticker HIGHNY-26JUN18-B88.5 \
--side yes \
--action buy \
--quantity 10 \
--price 40
marketedge paper positions
marketedge paper settle --ticker HIGHNY-26JUN18-B88.5 --winning-side yesPaper ledger events are append-only JSONL in data/paper-ledger.jsonl by default. They are local dry-run records and do not call the Kalshi API.
marketedge weather \
--lat 40.71 \
--lon -74.01 \
--event-type rain \
--threshold 1.0The weather implementation currently blends NWS-style, Open-Meteo-style, analog, microclimate, and NWS delta inputs.
src/formulas.py currently implements:
- Fee-adjusted edge.
- Kelly sizing with fractional Kelly.
- Annualized yield screening.
- Liquidity-adjusted spread analysis.
- Bayesian probability updates.
- Weather model probability blending.
- Risk of ruin estimation.
- Correlation exposure estimation.
- Full opportunity screening.
The codebase also includes max position percentage, max correlated exposure, spread-based size reduction, and auto-close concepts. These are research/risk primitives, not sufficient production live-trading controls by themselves.
Market Edge now includes local production-control primitives: explicit live-trading enablement, global kill switch, pre-order risk decisions, size/correlation/daily-loss/notional checks, strategy run records, and audit events for signals, refusals, intents, risk decisions, order attempts, fills, and rejections.
Local readiness controls also include remote CI, operator diagnostics, configurable SQLite storage, Alembic schema initialization, an application schema ledger, and an audit event table with CLI inspection/append commands.
The live-trading path fails closed by default. Running trade --live requires the global kill switch disengaged, MARKETEDGE_ALLOW_LIVE=true, both Kalshi credentials present, and an explicit --confirm-live confirmation; any missing gate exits before a live client is created. Dry run is always the default.
Use local, no-account, analysis, backtest, and dry-run workflows first. Do not treat this repository as production live-trading software without operator review of configured limits, audit storage, exchange credentials, and live gate settings.
Planned production-readiness and research enhancements are tracked publicly on the GitHub issues board.
.env.example documents supported local variables:
KALSHI_API_KEY=your_api_key_here
KALSHI_API_SECRET=your_api_secret_here
KALSHI_SANDBOX=true
# Optional URL overrides
KALSHI_BASE_URL=https://api.elections.kalshi.com
KALSHI_WS_URL=wss://api.elections.kalshi.com/ws/v2
# Optional local SQLite path
MARKETEDGE_DB_PATH=data/kalshi_quant.dbLocal generated state is intentionally not committed:
data/*.db,data/*.sqlite,data/*.sqlite3data/*.jsonlweb/data/dashboard.json.env,.env.local,*.env
Run the local verification gate before claiming completion:
.venv/bin/python -m black --check src tests && .venv/bin/python -m flake8 src/ tests/ --max-line-length=120 --ignore=E501,W503 && .venv/bin/python -m pytest tests/ -q && node --check web/app.jsCurrent local proof on this branch:
- Black passes for
srcandtests. - flake8 passes for
srcandtests. - pytest passes with CLI, dashboard, doctor, opportunities, paper ledger, formula, settlement, calibration, execution, experiment, backtesting, and SQLite state coverage.
node --check web/app.jspasses.
Known warning noise currently comes from existing datetime.utcnow() usage and SQLAlchemy legacy APIs. Warnings are not currently fatal.
See CONTRIBUTING.md for the full contributor guide. In short, use a clearly named feature branch off main:
git checkout main
git pull
git checkout -b feature/short-descriptionBefore opening a pull request, run the verification gate and include:
- A concise explanation of the change.
- Verification commands and results.
- Known gaps or follow-up work.
The pull request template includes a no-secrets / no-generated-data checklist โ please complete it.
Direct dependencies live in requirements.txt; constraints.txt pins the full resolved tree. To refresh after changing a dependency, recreate a clean environment, reinstall, run the gate, then regenerate the lock:
python -m pip freeze | grep -viE '^-e |marketedge' > constraints.txtAudit installed dependencies for known vulnerabilities (also run weekly in CI):
uvx pip-audit --strictMarket Edge is released under the MIT License.
Do not commit real API keys or trading credentials. Use .env for local secrets; it is git-ignored.
To report a vulnerability, follow the security policy and use a private channel โ do not open a public issue.
Before publishing or re-publishing, run the pre-public release checklist, which verifies that no secrets, databases, ledgers, .omx/ state, or generated dashboard payloads are tracked or present in git history. A scripted version is available:
./scripts/pre_public_audit.sh- GitHub: EricGrill/marketedge
- Primary branch:
main - License: MIT
- Security policy: SECURITY.md
- Contributor guide: CONTRIBUTING.md
- Agent handoff file: CLAUDE.md
- Main user/operator documentation: README.md
CLAUDE.md contains short project guidance for Claude and other coding agents: the product safety posture, common commands, generated-file rules, and verification gate. Keep it aligned with this README when changing the app surface.