DEV Community

Dave Sng
Dave Sng

Posted on

Real-Time Energy Supply Risk Monitoring — How I Combined 4 Government Data Sources Into One API

Last year, a single tanker blockage in the Strait of Hormuz caused Brent crude to spike 8% in two hours. Traders who had real-time visibility into tanker positions, port congestion, and freight rates saw it coming. Everyone else was reading about it on Bloomberg 30 minutes later.

I built Energy Volatility — an API that combines four government and maritime data sources into a single risk assessment endpoint. Here's the architecture, the data sources, and how you can use it.


The Problem

Energy supply risk analysis requires monitoring multiple disconnected data sources:

  1. AIS (Automatic Identification System) — Real-time tanker positions from maritime transponders
  2. Baltic Dry Index (BDI) — Freight rate volatility indicator
  3. Port Authority Data — Berthing delays, congestion levels, vessel queues
  4. Geopolitical Intelligence — Conflict severity, sanctions, military activity

Each source has its own API format, authentication, rate limits, and data schemas. Building a composite risk view means writing integration code for all four, normalizing the data, running correlation analysis, and then building a scoring model on top.

That's months of engineering work before you get to your first risk score.

The Solution: Energy Volatility API

Energy Volatility aggregates all four data sources and exposes them through a clean REST API with four endpoints:

Endpoint What It Does
POST /v1/risk-assessment Full composite risk score with AI supply gap prediction
GET /v1/tanker-positions Real-time tanker positions by region
GET /v1/freight-index Current freight index data (BDI, BDTI, etc.)
GET /v1/port-status Port congestion and berthing data by region

Architecture

AIS WebSocket Feed ─────┐
Freight Index APIs ──────┤
Port Authority Data ─────┼─> Energy Volatility API ─> Risk Score
Geopolitical Events ─────┘         |
                              AI Analysis
                          (OpenRouter/LLM)
Enter fullscreen mode Exit fullscreen mode

The API maintains a persistent WebSocket connection to AIS data feeds, caching tanker positions in memory. When you hit the /v1/risk-assessment endpoint, it pulls the latest cached positions, fetches current freight indices and port status, and feeds everything to an AI model that generates a supply gap prediction.

Data Sources Deep Dive

1. AIS Tanker Tracking

Every commercial vessel over 300 gross tons is required to broadcast its position via AIS transponders. We tap into this data to track oil tankers in critical shipping lanes:

  • Strait of Hormuz — 20% of global oil supply passes through here
  • Persian Gulf — Major loading ports (Ras Tanura, Kharg Island, Fujairah)
  • Suez Canal — Europe's primary oil import route
  • Strait of Malacca — Asia's energy lifeline
import httpx

HEADERS = {
    "X-RapidAPI-Key": "YOUR_KEY",
    "X-RapidAPI-Host": "energy-volatility.p.rapidapi.com"
}

# Get current tanker positions in the Strait of Hormuz
async with httpx.AsyncClient() as client:
    response = await client.get(
        "https://energy-volatility.p.rapidapi.com/v1/tanker-positions",
        headers=HEADERS,
        params={"region": "strait_of_hormuz"}
    )
    data = response.json()
    print(f"Region: {data['region']}")
    print(f"Active tankers: {data['count']}")
    for tanker in data["positions"]:
        print(f"  {tanker['vessel_name']} - {tanker['status']} "
              f"at ({tanker['lat']}, {tanker['lon']})")
Enter fullscreen mode Exit fullscreen mode

2. Freight Index Monitoring

The Baltic Dry Index (BDI) and Baltic Dirty Tanker Index (BDTI) are leading indicators of global trade activity and shipping costs:

response = await client.get(
    "https://energy-volatility.p.rapidapi.com/v1/freight-index",
    headers=HEADERS,
    params={"index_type": "BDI"}
)
indices = response.json()
for idx in indices["indices"]:
    print(f"{idx['date']}: {idx['value']} "
          f"(change: {idx['change_pct']}%)")
Enter fullscreen mode Exit fullscreen mode

A sudden spike in BDTI often precedes oil price movements by 24-48 hours — shipping costs rise before the commodity price catches up.

3. Port Congestion Data

Port berthing delays signal supply chain bottlenecks before they hit the news:

response = await client.get(
    "https://energy-volatility.p.rapidapi.com/v1/port-status",
    headers=HEADERS,
    params={"region": "persian_gulf"}
)
ports = response.json()
for port in ports["ports"]:
    print(f"{port['name']}: {port['vessels_waiting']} waiting, "
          f"avg wait {port['avg_wait_hours']}h")
Enter fullscreen mode Exit fullscreen mode

4. AI-Powered Risk Assessment

The /v1/risk-assessment endpoint combines all three data sources and adds AI analysis:

response = await client.post(
    "https://energy-volatility.p.rapidapi.com/v1/risk-assessment",
    headers=HEADERS,
    json={
        "region": "strait_of_hormuz",
        "conflict_type": "military_escalation",
        "severity": 7  # 1-10 scale
    }
)
risk = response.json()
print(f"Overall Risk Score: {risk['risk_score']}/100")
print(f"Supply Gap Prediction: {risk['supply_gap_barrels']} barrels/day")
print(f"Price Impact Estimate: {risk['price_impact_pct']}%")
print(f"AI Analysis: {risk['analysis']}")
Enter fullscreen mode Exit fullscreen mode

The AI model considers:

  • Current tanker density and flow patterns
  • Historical disruption precedents
  • Freight rate trends
  • Port congestion levels
  • Conflict type and severity

Available Regions

Region Strategic Importance
strait_of_hormuz 20% of global oil; Iran-Oman chokepoint
persian_gulf Major loading terminals (Saudi, UAE, Kuwait)
suez_canal Europe-Asia trade route; 12% of global trade
strait_of_malacca China/Japan/Korea energy imports
gulf_of_aden Red Sea approach; Houthi disruption zone

Use Cases

Commodity Traders: Get early warning signals before price moves. The composite risk score correlates with oil price volatility within a 24-hour window.

Insurance/Reinsurance: Assess real-time exposure for marine cargo policies. Port congestion data feeds directly into delay liability calculations.

Supply Chain Managers: Monitor shipping lane disruptions affecting your energy supply contracts. Automatic alerts when risk scores exceed thresholds.

Journalists & Analysts: Access structured data for energy market reporting. No more manually correlating AIS data with freight indices.

Technical Implementation

The API is built with FastAPI and deployed on Railway:

  • AIS Data: Persistent WebSocket connection with in-memory cache, refreshed every 60 seconds
  • Freight Indices: Polled from government sources every 15 minutes
  • Port Data: Aggregated from port authority APIs with 30-minute cache
  • AI Analysis: OpenRouter API (Gemini model) for natural language risk assessment
  • Auth: RapidAPI proxy authentication with per-plan rate limiting

Response times are typically under 200ms for data endpoints, and under 3 seconds for AI-powered risk assessments.

Pricing

Plan Requests/Month Price
Basic 100 Free
Pro 5,000 $9.99/mo
Ultra 50,000 $49.99/mo
Mega 500,000 $199.99/mo

The free tier gives you enough to build dashboards and test integrations. Pro covers most analytics use cases.

Get started: Energy Volatility on RapidAPI

What's Next

Upcoming features on the roadmap:

  • Historical data endpoints for backtesting risk models
  • Webhook alerts when risk scores exceed configurable thresholds
  • Additional regions (Baltic Sea, South China Sea, Gulf of Mexico)
  • Sanctions list cross-referencing for vessel screening

Working on energy market analysis or maritime logistics? I'd love to hear what data you need — drop a comment or reach out.

Top comments (0)