Skip to content

About

Experimental prediction-market quant research and dry-run execution workbench (Kalshi weather markets first). Research-first, local, no-account by default.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

ย 

History

46 Commits

Folders and files

Repository files navigation

๐ŸŒฆ๏ธ Market Edge

A local-first prediction-market quant workbench

MIT License Python 3.12+ SQLite Status

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


What is this?

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.


๐Ÿ“ฆ Install

Pick the one-shot path that matches your setup. No Python knowledge required for Homebrew or Docker.

Option 1 โ€” Homebrew (macOS)

brew tap ericgrill/tap
brew install --HEAD marketedge

This installs the marketedge CLI globally. Upgrades are brew reinstall --HEAD marketedge.

Option 2 โ€” Docker Compose

git clone https://github.com/EricGrill/marketedge.git
cd marketedge
docker compose up web

Then open http://localhost:4173 for the web dashboard. Run CLI commands with:

docker compose run --rm marketedge doctor
docker compose run --rm marketedge --help

Option 3 โ€” uvx (any OS with Python/uv)

uvx --from git+https://github.com/EricGrill/marketedge.git marketedge --help

uvx 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.

Option 4 โ€” Python 3.12

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

โœจ What It Does

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.

๐Ÿš€ Quick Start

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 .env

Keep KALSHI_SANDBOX=true unless you are intentionally working against a live environment.

Initialize local state and run a readiness check:

marketedge db init
marketedge doctor

Launch the TUI dashboard:

marketedge dashboard

Or start the static web dashboard:

python -m http.server 4173 -d web
# open http://localhost:4173

๐Ÿ–ฅ๏ธ CLI

The Click CLI is the main operator interface:

marketedge --help

If 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.


๐ŸŒ Web Dashboard

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 web

Then 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 by backtest --json-out.
  • web/data/dashboard.json โ€” generated by dashboard-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.


๐Ÿ“Š TUI

Launch the Textual dashboard from the CLI:

marketedge dashboard

It 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.


๐Ÿ—๏ธ Architecture

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

๐Ÿ”ง Core Workflows

Initialize Local State

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.db

The 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.12

Check Local Readiness

marketedge doctor
marketedge doctor --strict

doctor 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.

Generate Dashboard Data

marketedge dashboard-data \
  --out web/data/dashboard.json \
  --paper-ledger data/paper-ledger.jsonl \
  --backtest-summary web/data/backtest-summary.json

The web dashboard will use web/data/dashboard.json when present and fall back to built-in sample data when it is missing.

Analyze One Market

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:00Z

analyze 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.

Collect Market Snapshots

marketedge collect-snapshots \
  --ticker HIGHNY-26JUN18-B88.5 \
  --iterations 1

marketedge collect-snapshots --weather-scan --limit 50 --iterations 3 --interval 30

Snapshots 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.

Rank Opportunity Candidates

marketedge opportunities path/to/candidates.csv \
  --bankroll 10000 \
  --json-out web/data/opportunities.json

Candidate CSV/JSON/JSONL rows require:

  • ticker
  • model_probability
  • yes_bid
  • yes_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.

Run An Offline Backtest

marketedge backtest path/to/trades.csv --bankroll 10000

marketedge backtest path/to/trades.csv \
  --bankroll 10000 \
  --json-out web/data/backtest-summary.json

Required trade CSV columns:

  • timestamp
  • ticker
  • side
  • entry_price
  • exit_price
  • quantity
  • model_probability

Optional columns include confidence, entry_fee, and exit_fee.

Load Settlements And Score Calibration

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.json

Apply Execution Realism

from 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.

Track And Compare Experiments

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.json

Experiment 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.

Manage Strategies

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.json

Built-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.

Record Paper Trades

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 yes

Paper 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.

Fetch Weather Data

marketedge weather \
  --lat 40.71 \
  --lon -74.01 \
  --event-type rain \
  --threshold 1.0

The weather implementation currently blends NWS-style, Open-Meteo-style, analog, microclimate, and NWS delta inputs.


๐Ÿงฎ Quant And Risk Features

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.


๐Ÿ›ก๏ธ Safety First

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.


โš™๏ธ Configuration

.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.db

Local generated state is intentionally not committed:

  • data/*.db, data/*.sqlite, data/*.sqlite3
  • data/*.jsonl
  • web/data/dashboard.json
  • .env, .env.local, *.env

โœ… Verification

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.js

Current local proof on this branch:

  • Black passes for src and tests.
  • flake8 passes for src and tests.
  • pytest passes with CLI, dashboard, doctor, opportunities, paper ledger, formula, settlement, calibration, execution, experiment, backtesting, and SQLite state coverage.
  • node --check web/app.js passes.

Known warning noise currently comes from existing datetime.utcnow() usage and SQLAlchemy legacy APIs. Warnings are not currently fatal.


๐Ÿค Development Workflow

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-description

Before 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.

Refresh And Audit Dependencies

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.txt

Audit installed dependencies for known vulnerabilities (also run weekly in CI):

uvx pip-audit --strict

๐Ÿ“„ License

Market Edge is released under the MIT License.


๐Ÿ” Security And Open-Source Readiness

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

Repository And Docs

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.

About

Experimental prediction-market quant research and dry-run execution workbench (Kalshi weather markets first). Research-first, local, no-account by default.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

⌂ Proxy