API Documentation

Historical Predictions API

Welcome to the Historical Predictions API! This documentation covers how to access all our agent's past predictions and market analysis data from the pricing engine.

Base URL:https://prediction-market-agent47-fork.vercel.app/api/predictions/history

Authentication

Currently, the API does not require authentication. All endpoints are publicly accessible.

Endpoints

1. Get Prediction History

Fetch historical prediction data from the pricing engine with filtering, sorting, and pagination options. Returns both grouped data by market and market summaries.

GET /api/predictions/history

Query Parameters

ParameterTypeDefaultDescription
market_idstring-Filter by specific market ID
slugstring-Filter by market slug
recommendationstring-Filter by recommendation (STRONG_SIGNAL,MODERATE_SIGNAL,WEAK_SIGNAL,NO_TRADE)
regimestring-Filter by market regime (liquid_active,pre_catalyst_event,illiquid_tail_risk,approaching_expiry)
min_edgenumber-Minimum edge in basis points
max_edgenumber-Maximum edge in basis points
sortBystringcreated_atField to sort by (created_at, market_id, slug, etc.)
sortOrdernumber11 for ascending, -1 for descending
pagenumber-Page number for pagination
limitnumber-Number of items per page

Example Requests

bash
# Get all prediction history
curl "https://prediction-market-agent47-fork.vercel.app/api/predictions/history"

# Get predictions for a specific market
curl "https://prediction-market-agent47-fork.vercel.app/api/predictions/history?market_id=589648"

# Get only STRONG_SIGNAL recommendations with high edge
curl "https://prediction-market-agent47-fork.vercel.app/api/predictions/history?recommendation=STRONG_SIGNAL&min_edge=1000"

# Get predictions sorted by latest first with pagination
curl "https://prediction-market-agent47-fork.vercel.app/api/predictions/history?sortBy=created_at&sortOrder=-1&page=1&limit=20"

Example Response

json
{
  "success": true,
  "data": {
    "grouped": {
      "589648": [
        {
          "_id": "694d504ad6c267c9d3c5574e",
          "slug": "will-the-us-invade-venezuela-in-2025",
          "market_id": "589648",
          "question": "Will the U.S. invade Venezuela by December 31, 2025?",
          "current_prices": {
            "Yes": 0.0225,
            "No": 0.9775
          },
          "analysis": {
            "prediction": "No",
            "confidence": "Low",
            "key_factors": [...]
          },
          "pricing": {
            "regime": "pre_catalyst_event",
            "fair_price_yes": 0.21,
            "edge_bps": 1870.7,
            "recommendation": "STRONG_SIGNAL",
            "kelly_fraction": 0.005
          },
          "created_at": "2025-12-25T09:55:06.919287"
        }
      ]
    },
    "markets": [
      {
        "market_id": "589648",
        "slug": "will-the-us-invade-venezuela-in-2025",
        "question": "Will the U.S. invade Venezuela by December 31, 2025?",
        "prediction_count": 5,
        "latest_fair_price": 0.21,
        "latest_market_price": 0.0225,
        "latest_edge_bps": 1870.7,
        "latest_recommendation": "STRONG_SIGNAL"
      }
    ]
  },
  "count": 45,
  "pagination": {
    "page": 1,
    "limit": 20,
    "total": 45,
    "total_pages": 3
  }
}

2. Response Schema

Understanding the data structure returned by the API.

Main Response Fields

FieldTypeDescription
successbooleanWhether the request succeeded
data.groupedobjectPredictions grouped by market_id
data.marketsarraySummary of each market with latest values
countnumberTotal number of predictions returned
paginationobjectPagination info (when page/limit provided)

Prediction Document Fields

FieldTypeDescription
market_idstringPolymarket market identifier
questionstringThe market question
current_pricesobjectCurrent market prices for Yes/No
analysisobjectAI analysis with prediction and confidence
pricingobjectPricing model output (fair price, edge, regime)
created_atstringTimestamp when prediction was made

Code Examples

TypeScript/JavaScript (Fetch API)

typescript
// Fetch all predictions
const response = await fetch('https://prediction-market-agent47-fork.vercel.app/api/predictions/history')
const result = await response.json()

if (result.success) {
  const { grouped, markets } = result.data
  console.log(`Found ${markets.length} markets`)
  console.log(`Total predictions: ${result.count}`)
}

// Fetch with filters
const params = new URLSearchParams({
  recommendation: 'STRONG_SIGNAL',
  min_edge: '1000',
  sortBy: 'created_at',
  sortOrder: '-1',
  limit: '20'
})

const baseURL = 'https://prediction-market-agent47-fork.vercel.app/api/predictions/history'
const filtered = await fetch(`${baseURL}?${params}`)
const data = await filtered.json()

React Component

typescript
import { useState, useEffect } from 'react'

const API_URL = 'https://prediction-market-agent47-fork.vercel.app/api/predictions/history'

export function PredictionHistory() {
  const [data, setData] = useState(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    async function fetchData() {
      const res = await fetch(`${API_URL}?recommendation=STRONG_SIGNAL`)
      const json = await res.json()
      if (json.success) {
        setData(json.data)
      }
      setLoading(false)
    }
    fetchData()
  }, [])

  if (loading) return <div>Loading...</div>

  return (
    <div>
      <h2>Markets: {data.markets.length}</h2>
      {data.markets.map(market => (
        <div key={market.market_id}>
          <h3>{market.question}</h3>
          <p>Edge: {market.latest_edge_bps} bps</p>
          <p>Predictions: {market.prediction_count}</p>
        </div>
      ))}
    </div>
  )
}

Python

python
import requests

API_URL = 'https://prediction-market-agent47-fork.vercel.app/api/predictions/history'

# Get all predictions
response = requests.get(API_URL)
data = response.json()

if data['success']:
    markets = data['data']['markets']
    print(f"Found {len(markets)} markets")
    
    for market in markets:
        print(f"\n{market['question']}")
        print(f"  Market ID: {market['market_id']}")
        print(f"  Fair Price: {market['latest_fair_price']}")
        print(f"  Market Price: {market['latest_market_price']}")
        print(f"  Edge: {market['latest_edge_bps']} bps")
        print(f"  Recommendation: {market['latest_recommendation']}")

# Filter by strong signals with high edge
params = {
    'recommendation': 'STRONG_SIGNAL',
    'min_edge': 1000,
    'sortBy': 'created_at',
    'sortOrder': -1
}

response = requests.get(API_URL, params=params)
print(f"Strong signals: {response.json()['count']}")

Status Codes

CodeMeaning
200Success
400Bad Request
404Not Found
500Server Error

Common Use Cases

📊 Track model performance: Use market_id to see how predictions evolved over time

🎯 Find trading opportunities: Filter by recommendation=STRONG_SIGNAL and min_edge=1000

📈 Analyze market regimes: Use regime filter to study different market conditions

🔄 Monitor updates: Sort by created_at descending to see latest predictions

Best Practices

✓ Use pagination: For large result sets, use page and limit parameters to avoid timeouts

✓ Filter strategically: Combine filters to narrow down results (e.g., recommendation + min_edge)

✓ Implement caching: Cache results on the client to reduce server load

✓ Always check success: Verify the success field before accessing data to handle errors gracefully

✓ Use grouped data: The grouped object makes it easy to display time-series data per market