Skip to main content
Premium API Feature

Analytics API

Complete analytics suite for commodity prices. Get z-scores, percentiles, volatility, correlations, trend analysis, moving averages, RSI, and support/resistance levels. Make data-driven trading decisions. Available for Starter and Professional subscribers.

StarterProfessional

Starter: $49/mo • Professional: $99/mo

Quick Start - Get Statistics

1. Request Statistics for a Commodity

curl -X GET "https://api.oilpriceapi.com/v1/analytics/statistics?code=WTI_USD&period=30" \
  -H "Authorization: Token YOUR_API_KEY" \
  -H "Content-Type: application/json"

2. Response Example

{
  "code": "WTI_USD",
  "period": 30,
  "statistics": {
    "z_score": 1.23,
    "z_score_interpretation": "Moderately above average (1.2 standard deviations)",
    "percentile": 67.5,
    "percentile_interpretation": "Above average - higher than 68% of recent prices",
    "volatility": 24.5,
    "volatility_interpretation": "Moderate volatility",
    "calculated_at": "2025-12-26T15:30:00Z"
  },
  "tier": "starter"
}

API Endpoint

GET/v1/analytics/statisticsPremium

Returns statistical analytics for a commodity including z-score, percentile ranking, and volatility metrics.

Request Parameters

ParameterTypeRequiredDescription
codestringYesCommodity code (e.g., WTI_USD, BRENT_USD, NATURAL_GAS_USD)
periodintegerNoNumber of days for analysis (default: 30, range: 7-365)

Response Fields

FieldTypeDescription
z_scorenumberStandard deviations from mean (-3 to +3 typical)
z_score_interpretationstringHuman-readable interpretation of z-score
percentilenumberPercentile ranking (0-100)
percentile_interpretationstringHuman-readable interpretation of percentile
volatilitynumberAnnualized volatility percentage
volatility_interpretationstringVolatility classification (Low/Moderate/High/Extreme)
calculated_atstringISO 8601 timestamp of calculation
GET/v1/analytics/correlationPremiumNEW

Calculate correlation between two commodities. Understand how price movements relate - useful for hedging, portfolio diversification, and arbitrage opportunities.

Request Parameters

ParameterTypeRequiredDescription
code1stringYesFirst commodity code (e.g., WTI_USD)
code2stringYesSecond commodity code (e.g., BRENT_USD)
periodintegerNoDays of data to analyze (default: 30)
typestringNo"analysis" (default), "rolling", or "matrix"
windowintegerNoRolling window size (default: 7, for type=rolling)
codesstringNoComma-separated codes for matrix (type=matrix)

Response Fields (Analysis)

FieldTypeDescription
correlationnumberPearson correlation coefficient (-1 to +1)
correlation_interpretationstringHuman-readable explanation of the correlation
strengthstringvery_weak, weak, moderate, strong, very_strong
directionstringpositive or negative
stabilitynumberStd dev of rolling correlation (lower = more stable)
rolling_correlationarrayRecent rolling correlation values (preview)

Example Request

curl -X GET "https://api.oilpriceapi.com/v1/analytics/correlation?code1=WTI_USD&code2=BRENT_USD&period=30" \
  -H "Authorization: Token YOUR_API_KEY"

Example Response

{
  "type": "analysis",
  "code1": "WTI_USD",
  "code2": "BRENT_USD",
  "correlation": 0.94,
  "correlation_interpretation": "Very strong positive correlation - prices highly together",
  "strength": "very_strong",
  "direction": "positive",
  "stability": 0.08,
  "stability_interpretation": "Stable - correlation remains consistent over time",
  "period_days": 30,
  "data_points": 24,
  "rolling_correlation": [
    { "date": "2025-12-20", "correlation": 0.92 },
    { "date": "2025-12-21", "correlation": 0.93 },
    { "date": "2025-12-22", "correlation": 0.94 }
  ],
  "calculated_at": "2025-12-26T15:30:00Z",
  "tier": "starter"
}
GET/v1/analytics/trendPremiumNEW

Get trend and momentum analysis for a commodity. Includes moving averages, RSI, trend direction, support/resistance levels, and trading signals.

Request Parameters

ParameterTypeRequiredDescription
codestringYesCommodity code (e.g., WTI_USD)
periodintegerNoDays of data (default: 30)
typestringNo"analysis" (default), "sma", "ema", "rsi", or "levels"
windowintegerNoMoving average window (default: 20 for SMA/EMA, 14 for RSI)

Response Fields (Analysis)

FieldTypeDescription
trend.directionstringbullish, bearish, or sideways
trend.strengthnumberTrend strength 0-100 (R-squared)
momentum.rsinumberRSI value 0-100
moving_averages.sma_20number20-day simple moving average
levels.supportarrayKey support price levels
levels.resistancearrayKey resistance price levels
signalobjectCombined signal with value, interpretation, and confidence

Example Request

curl -X GET "https://api.oilpriceapi.com/v1/analytics/trend?code=WTI_USD&period=30" \
  -H "Authorization: Token YOUR_API_KEY"

Example Response

{
  "type": "analysis",
  "code": "WTI_USD",
  "trend": {
    "direction": "bullish",
    "strength": 72.5,
    "strength_interpretation": "strong",
    "slope_per_day": 0.15,
    "price_change_pct": 4.5,
    "short_term_change_pct": 1.2,
    "momentum": "steady"
  },
  "momentum": {
    "rsi": 58.5,
    "rsi_interpretation": "neutral"
  },
  "moving_averages": {
    "sma_20": 70.25,
    "price_vs_sma": "above"
  },
  "levels": {
    "support": [68.50, 67.20, 65.80],
    "resistance": [72.80, 74.50, 76.00],
    "pivot_point": 70.10
  },
  "signal": {
    "value": 0.67,
    "interpretation": "bullish",
    "confidence": "moderate"
  },
  "calculated_at": "2025-12-27T12:00:00Z",
  "tier": "starter"
}
GET/v1/analytics/spreadPremiumNEW

Calculate commodity spread analysis including basis spreads (WTI-Brent), crack spreads (refinery margins), and energy ratios (gas-oil). Essential for arbitrage, hedging, and margin analysis.

Available Spreads

SpreadTypeDescription
wti_brentBasisWTI minus Brent crude differential
321Crack3-2-1 crack spread (2 gasoline + 1 heating oil)
gasoline_crackCrackSimple gasoline crack spread
heating_oil_crackCrackSimple heating oil crack spread
gas_oil_ratioRatioNatural gas to oil thermal equivalent ratio

Request Parameters

ParameterTypeRequiredDescription
spreadstringNo*Spread name (omit to list available spreads)
periodintegerNoDays for historical context (default: 30)
typestringNo"current" (default) or "historical" for time series

Response Fields

FieldTypeDescription
current_spreadnumberCurrent spread value in USD/barrel or ratio
historical.meannumberAverage spread over the period
historical.percentilenumberWhere current spread ranks in recent history
historical.z_scorenumberStd deviations from mean
interpretationstringHuman-readable analysis of the spread

Example Request (WTI-Brent Basis)

curl -X GET "https://api.oilpriceapi.com/v1/analytics/spread?spread=wti_brent&period=30" \
  -H "Authorization: Token YOUR_API_KEY"

Example Response

{
  "type": "current",
  "spread_name": "WTI-Brent crude oil basis spread",
  "code1": "WTI_USD",
  "code2": "BRENT_CRUDE_USD",
  "price1": 70.25,
  "price2": 73.70,
  "current_spread": -3.45,
  "unit": "USD/barrel",
  "historical": {
    "mean": -2.50,
    "std_dev": 1.85,
    "min": -8.20,
    "max": 1.50,
    "percentile": 35.2,
    "z_score": -0.51,
    "data_points": 30
  },
  "interpretation": "Normal range: WTI at 3.45 discount to benchmark",
  "calculated_at": "2025-12-27T12:00:00Z",
  "tier": "starter"
}

Example Request (3-2-1 Crack Spread)

curl -X GET "https://api.oilpriceapi.com/v1/analytics/spread?spread=321&period=30" \
  -H "Authorization: Token YOUR_API_KEY"

Example Response (Crack Spread)

{
  "type": "current",
  "spread_name": "3-2-1 crack spread (2 gasoline + 1 heating oil)",
  "crude": "WTI_USD",
  "crude_price": 70.25,
  "products": [
    { "code": "GASOLINE_RBOB_USD", "price": 2.15, "weight": 2 },
    { "code": "HEATING_OIL_USD", "price": 2.45, "weight": 1 }
  ],
  "current_spread": 19.85,
  "unit": "USD/barrel",
  "historical": {
    "mean": 18.50,
    "std_dev": 4.20,
    "min": 8.30,
    "max": 28.60,
    "percentile": 58.0,
    "z_score": 0.32,
    "data_points": 30
  },
  "interpretation": "Normal range: Refining margins within typical historical range",
  "calculated_at": "2025-12-27T12:00:00Z",
  "tier": "starter"
}

Error Responses

401Unauthorized
{ "error": "Unauthorized" }
403Forbidden (Tier Required)
{
  "error": "Analytics requires Starter or Professional subscription",
  "upgrade_url": "https://oilpriceapi.com/pricing",
  "upgrade_required": true,
  "sample_data": { ... }
}
400Bad Request
{ "error": "code parameter is required" }
404Not Found
{ "error": "No price data available for FAKE_CODE", "code": "FAKE_CODE", "period": 30 }

Understanding Correlation

Pearson correlation measures how two commodity prices move together. Values range from -1 (perfect inverse) to +1 (perfect positive), with 0 indicating no relationship.

Positive Correlation (+0.6 to +1.0)

Prices move together. When one rises, the other tends to rise.

WTI ↔ Brent~0.95 (very strong)
Brent ↔ Diesel~0.85 (strong)
Use case: Hedging - high correlation means one can substitute for another

Negative Correlation (-1.0 to -0.6)

Prices move opposite. When one rises, the other tends to fall.

Oil ↔ USD Index~-0.40 (moderate)
Natural Gas ↔ Warm Weather~-0.30 (weak)
Use case: Diversification - negative correlation reduces portfolio risk

Correlation Strength Guide

0.0 - 0.2
Very Weak
0.2 - 0.4
Weak
0.4 - 0.6
Moderate
0.6 - 0.8
Strong
0.8 - 1.0
Very Strong

Understanding the Metrics

Z-Score

Measures how many standard deviations the current price is from the historical mean.

< -2.0Significantly undervalued
-1.0 to 1.0Normal range
> 2.0Significantly overvalued

Percentile

Shows where the current price ranks compared to historical prices in the period.

0-25%Low (buying opportunity)
25-75%Average range
75-100%High (expensive)

Volatility

Annualized volatility measuring price fluctuation intensity over the period.

< 20%Low (stable market)
20-40%Moderate
> 40%High (turbulent)

Integration Examples

Python Example

import requests

api_key = "YOUR_API_KEY"
url = "https://api.oilpriceapi.com/v1/analytics/statistics"

# Get WTI statistics for the past 30 days
response = requests.get(url,
    params={"code": "WTI_USD", "period": 30},
    headers={"Authorization": f"Token {api_key}"}
)

stats = response.json()["statistics"]

print(f"Z-Score: {stats['z_score']:.2f} ({stats['z_score_interpretation']})")
print(f"Percentile: {stats['percentile']:.1f}% ({stats['percentile_interpretation']})")
print(f"Volatility: {stats['volatility']:.1f}% ({stats['volatility_interpretation']})")

# Make trading decisions based on z-score
if stats['z_score'] < -2:
    print("Signal: Potential buying opportunity (significantly undervalued)")
elif stats['z_score'] > 2:
    print("Signal: Consider taking profits (significantly overvalued)")

JavaScript / Node.js Example

const apiKey = "YOUR_API_KEY";

async function getAnalytics(code, period = 30) {
  const response = await fetch(
    `https://api.oilpriceapi.com/v1/analytics/statistics?code=${code}&period=${period}`,
    {
      headers: { "Authorization": `Token ${apiKey}` }
    }
  );

  return response.json();
}

// Fetch analytics for multiple commodities
const commodities = ["WTI_USD", "BRENT_USD", "NATURAL_GAS_USD"];

Promise.all(commodities.map(code => getAnalytics(code)))
  .then(results => {
    results.forEach((data, i) => {
      const { statistics: stats } = data;
      console.log(`\n${commodities[i]}:`);
      console.log(`  Z-Score: ${stats.z_score.toFixed(2)} - ${stats.z_score_interpretation}`);
      console.log(`  Percentile: ${stats.percentile.toFixed(1)}%`);
      console.log(`  Volatility: ${stats.volatility.toFixed(1)}%`);
    });
  });

Use Cases

Trading & Investment

  • • Mean reversion trading strategies
  • • Entry/exit point identification
  • • Portfolio rebalancing triggers
  • • Risk-adjusted position sizing
  • • Automated trading signals

Risk Management

  • • Volatility monitoring dashboards
  • • Hedging decision support
  • • Exposure limit calculations
  • • Stress testing scenarios
  • • VaR model inputs

Procurement & Operations

  • • Optimal fuel purchase timing
  • • Budget forecasting models
  • • Contract negotiation support
  • • Supply chain cost optimization
  • • Price benchmarking analysis

Research & Reporting

  • • Market analysis reports
  • • Price anomaly detection
  • • Historical trend studies
  • • Client advisory dashboards
  • • Regulatory compliance reports

Supported Commodities

Analytics are available for all commodities in the OilPriceAPI catalog. Some popular codes:

Crude Oil

  • WTI_USD - WTI Crude Oil
  • BRENT_USD - Brent Crude
  • DUBAI_CRUDE_USD - Dubai Crude
  • MURBAN_CRUDE_USD - Murban Crude

Natural Gas

  • NATURAL_GAS_USD - Henry Hub
  • NATURAL_GAS_EUR - TTF Europe
  • NATURAL_GAS_GBP - UK NBP
  • LNG_ASIA_USD - JKM LNG

Refined Products

  • GASOLINE_USD - RBOB Gasoline
  • HEATING_OIL_USD - Heating Oil
  • DIESEL_USD - ULSD Diesel
  • JET_FUEL_USD - Jet Fuel

View the complete list of commodity codes in the full API documentation.

Unlock Statistical Analytics

Upgrade to Starter or Professional to access powerful statistical analytics and make data-driven commodity trading decisions.