# prediction-market-context

Real-time prediction market context for AI agents and LLMs. One function call gives your agent calibrated world awareness from 30,000+ prediction markets.

[![npm](https://img.shields.io/npm/v/prediction-market-context)](https://www.npmjs.com/package/prediction-market-context)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)

```ts
import { world } from 'prediction-market-context'

const state = await world()
console.log(state.index.uncertainty)  // 35 (0-100, how much markets disagree)
console.log(state.regimeSummary)      // "Risk-off: geo elevated, momentum negative"
console.log(state.actionableEdges)    // Markets where model price != market price
console.log(state.movers)             // What moved in the last 24h
```

## Why

LLMs don't know what's happening today. Web search returns narratives and opinions. Prediction markets return **calibrated probabilities backed by real money**.

This package gives any AI agent instant world awareness:
- **Uncertainty Index** — four numbers summarizing global market sentiment
- **Actionable Edges** — markets where thesis-implied price diverges from market price
- **Market Movers** — what changed in the last 24h across all tracked markets
- **Contagion Signals** — when one market should move because another did
- **Regime Summary** — one-line qualitative read on the current environment

All data sourced from Kalshi and Polymarket via [SimpleFunctions](https://simplefunctions.dev).

## Install

```bash
npm install prediction-market-context
```

## Quick Start

### Zero-config functions

```ts
import { world, index, edges, delta, market } from 'prediction-market-context'

// Full world state (~800 tokens, refreshes every 15 min)
const state = await world()

// Just the uncertainty index (4 numbers)
const { uncertainty, geopolitical, momentum, activity } = await index()

// Actionable edges (thesis price != market price)
const { edges: list } = await edges()

// What changed in the last hour (~30-50 tokens)
const changes = await delta('1h')

// Specific market detail with orderbook
const m = await market('KXFEDDECISION', { depth: true })
```

### Client class (for custom config)

```ts
import { PredictionMarketClient } from 'prediction-market-context'

const client = new PredictionMarketClient({
  apiKey: process.env.SF_API_KEY,  // optional, enables portfolio overlay
  timeout: 10_000,                  // default 15s
})

const state = await client.world()
const idx = await client.index({ history: true })
```

### Markdown output (for LLM system prompts)

```ts
const markdown = await world({ format: 'markdown' })
// Returns ~800 tokens of structured markdown, ready to inject into a system prompt
```

## CLI

```bash
# World state
npx prediction-market-context world
npx prediction-market-context world --json

# What changed
npx prediction-market-context delta 1h

# Uncertainty index
npx prediction-market-context index
npx prediction-market-context index --history

# Edges
npx prediction-market-context edges

# Specific market
npx prediction-market-context market KXFEDDECISION

# Search
npx prediction-market-context search "oil prices"
```

## Use with AI Frameworks

### OpenAI

```ts
import OpenAI from 'openai'
import { world } from 'prediction-market-context'

const state = await world({ format: 'markdown' })

const response = await new OpenAI().chat.completions.create({
  model: 'gpt-4o',
  messages: [
    { role: 'system', content: `You are a market analyst.\n\n${state}` },
    { role: 'user', content: 'What are the key risks right now?' },
  ],
})
```

### Anthropic (Claude)

```ts
import Anthropic from '@anthropic-ai/sdk'
import { world } from 'prediction-market-context'

const state = await world({ format: 'markdown' })

const response = await new Anthropic().messages.create({
  model: 'claude-sonnet-4-20250514',
  max_tokens: 1024,
  system: `You are a geopolitical analyst.\n\n${state}`,
  messages: [{ role: 'user', content: 'Summarize the current risk environment.' }],
})
```

### LangChain

```ts
import { tool } from '@langchain/core/tools'
import { world, index } from 'prediction-market-context'

const worldTool = tool(async () => {
  return JSON.stringify(await world())
}, {
  name: 'get_world_state',
  description: 'Get real-time prediction market world state with uncertainty index, edges, and movers',
})

const indexTool = tool(async () => {
  return JSON.stringify(await index())
}, {
  name: 'get_uncertainty_index',
  description: 'Get the prediction market uncertainty index (0-100) with geopolitical risk and momentum',
})
```

### As an MCP Tool

For full MCP server integration, use the [SimpleFunctions MCP Server](https://www.npmjs.com/package/@spfunctions/cli):

```bash
npx @spfunctions/cli --mcp
```

## API Reference

| Function | Returns | Description |
|----------|---------|-------------|
| `world(options?)` | `WorldState \| string` | Full world state. `{ format: 'markdown' }` for LLM injection. |
| `index(options?)` | `UncertaintyIndex` | Four-signal uncertainty index. `{ history: true }` for 24h data. |
| `edges()` | `EdgesResponse` | Actionable edges with reasoning, causal path, absorption. |
| `delta(since?)` | `WorldDelta` | Incremental changes. `"1h"`, `"6h"`, `"24h"`, or ISO timestamp. |
| `market(ticker, options?)` | `MarketDetail` | Single market detail. `{ depth: true }` for orderbook. |
| `markets(tickers, options?)` | `MarketDetail[]` | Batch query up to 20 markets. |
| `search(query)` | `SearchResult` | Search markets by topic. |

## Data

- **30,000+** prediction markets tracked across Kalshi and Polymarket
- **548** tickers with live orderbook snapshots
- **10,000+** market changes detected daily
- Refreshes every **15 minutes**
- Data available since **2026-03-19**

## Related

- [SimpleFunctions CLI](https://github.com/spfunctions/simplefunctions-cli) — full prediction market intelligence CLI
- [SimpleFunctions Python](https://github.com/spfunctions/simplefunctions-python) — Python client (`pip install simplefunctions-ai`)
- [Awesome Prediction Markets](https://github.com/spfunctions/awesome-prediction-markets) — curated developer resources
- [MCP Server](https://simplefunctions.dev/api/mcp/mcp) — connect any LLM to prediction markets

## License

MIT — [SimpleFunctions](https://simplefunctions.dev)
