Skip to content

Resources

Prices

oilpriceapi.resources.prices.PricesResource

Resource for current price operations.

get(commodity)

Get current price for a single commodity.

Parameters:

Name Type Description Default
commodity str

Commodity code (e.g., "BRENT_CRUDE_USD")

required

Returns:

Type Description
Price

Price object with current data

Example

price = client.prices.get("BRENT_CRUDE_USD") print(f"Brent: ${price.value:.2f}")

get_multiple(commodities, raise_on_error=False, return_failures=False)

Get prices for multiple commodities.

Parameters:

Name Type Description Default
commodities List[str]

List of commodity codes

required
raise_on_error bool

If True, raise exception on first failure. If False, skip failed commodities.

False
return_failures bool

If True, return tuple of (prices, failures). Failures is list of (commodity, error_message).

False

Returns:

Type Description
Union[List[Price], tuple[List[Price], List[tuple[str, str]]]]

List of Price objects, or tuple of (prices, failures) if return_failures=True

Raises:

Type Description
OilPriceAPIError

If raise_on_error=True and any commodity fails

Example

prices = client.prices.get_multiple([ ... "BRENT_CRUDE_USD", ... "WTI_USD", ... "NATURAL_GAS_USD" ... ]) for price in prices: ... print(f"{price.commodity}: ${price.value:.2f}")

With failure tracking

prices, failures = client.prices.get_multiple( ... ["BRENT_CRUDE_USD", "INVALID_CODE"], ... return_failures=True ... ) if failures: ... print(f"Failed to fetch: {failures}")

get_all(per_page=100)

Get current prices for all available commodities.

Auto-paginates using X-Has-Next response headers until all records are retrieved.

Parameters:

Name Type Description Default
per_page int

Number of records per page (default 100, matches API default)

100

Returns:

Type Description
List[Price]

List of Price objects for all commodities

Example

all_prices = client.prices.get_all() oil_prices = [p for p in all_prices if 'CRUDE' in p.commodity]

to_dataframe(commodity=None, commodities=None, start=None, end=None, interval='daily', per_page=100)

Get price data as a pandas DataFrame.

Note: Requires pandas to be installed.

Parameters:

Name Type Description Default
commodity Optional[str]

Single commodity code

None
commodities Optional[List[str]]

Multiple commodity codes

None
start Optional[Union[str, datetime]]

Start date for historical data

None
end Optional[Union[str, datetime]]

End date for historical data

None
interval str

Data interval (minute, hourly, daily, weekly, monthly)

'daily'
per_page int

Records per page when fetching all current prices. Default 100 (matches API default). Only used when neither commodity nor commodities is specified and no date range is given. Auto-pagination fetches all pages.

100

Returns:

Type Description

pandas DataFrame with price data

Example

df = client.prices.to_dataframe( ... commodity="BRENT_CRUDE_USD", ... start="2024-01-01", ... interval="daily" ... ) df.plot(y="value", title="Brent Crude Oil Prices")

Historical

oilpriceapi.resources.historical.HistoricalResource

Resource for historical price data.

get(commodity, start_date=None, end_date=None, interval='daily', page=1, per_page=100, type_name='spot_price', timeout=None)

Get historical price data.

Parameters:

Name Type Description Default
commodity str

Commodity code (e.g., "BRENT_CRUDE_USD")

required
start_date Optional[Union[str, date, datetime]]

Start date for data range

None
end_date Optional[Union[str, date, datetime]]

End date for data range

None
interval str

Data interval (minute, hourly, daily, weekly, monthly)

'daily'
page int

Page number for pagination

1
per_page int

Items per page (max 1000)

100
type_name str

Price type (spot_price, futures, etc.)

'spot_price'
timeout Optional[float]

Request timeout in seconds. If None, automatically determined by date range. - 1 week range: 30s - 1 month range: 60s - 1 year range: 120s

None

Returns:

Type Description
HistoricalResponse

HistoricalResponse with price data and pagination info

Example

history = client.historical.get( ... commodity="BRENT_CRUDE_USD", ... start_date="2024-01-01", ... end_date="2024-12-31", ... interval="daily" ... ) for price in history.data: ... print(f"{price.date}: ${price.value:.2f}")

Custom timeout for very large queries

history = client.historical.get( ... commodity="WTI_USD", ... start_date="2020-01-01", ... end_date="2024-12-31", ... timeout=180 # 3 minutes ... )

get_all(commodity, start_date=None, end_date=None, interval='daily', type_name='spot_price')

Get all historical data (handles pagination automatically).

Parameters:

Name Type Description Default
commodity str

Commodity code

required
start_date Optional[Union[str, date, datetime]]

Start date for data range

None
end_date Optional[Union[str, date, datetime]]

End date for data range

None
interval str

Data interval

'daily'
type_name str

Price type

'spot_price'

Returns:

Type Description
List[HistoricalPrice]

List of all HistoricalPrice objects

Example

all_data = client.historical.get_all( ... commodity="WTI_USD", ... start_date="2024-01-01", ... interval="daily" ... ) print(f"Total records: {len(all_data)}")

iter_pages(commodity, start_date=None, end_date=None, interval='daily', per_page=100, type_name='spot_price')

Iterate through pages of historical data.

Memory efficient iterator for large datasets.

Parameters:

Name Type Description Default
commodity str

Commodity code

required
start_date Optional[Union[str, date, datetime]]

Start date for data range

None
end_date Optional[Union[str, date, datetime]]

End date for data range

None
interval str

Data interval

'daily'
per_page int

Items per page

100
type_name str

Price type

'spot_price'

Yields:

Type Description
List[HistoricalPrice]

List of HistoricalPrice objects for each page

Example

for page_data in client.historical.iter_pages("NATURAL_GAS_USD"): ... process_batch(page_data) ... print(f"Processed {len(page_data)} records")

to_dataframe(commodity, start=None, end=None, interval='daily', type_name='spot_price')

Get historical data as a pandas DataFrame.

Note: Requires pandas to be installed.

Parameters:

Name Type Description Default
commodity str

Commodity code

required
start Optional[Union[str, date, datetime]]

Start date

None
end Optional[Union[str, date, datetime]]

End date

None
interval str

Data interval

'daily'
type_name str

Price type

'spot_price'

Returns:

Type Description

pandas DataFrame with historical prices

Example

df = client.historical.to_dataframe( ... commodity="BRENT_CRUDE_USD", ... start="2024-01-01", ... end="2024-12-31", ... interval="daily" ... ) df.describe()

Diesel

oilpriceapi.resources.diesel.DieselResource

Resource for diesel price operations.

Provides access to state-level diesel price averages and station-level pricing.

Example

Get state average (free tier)

price = client.diesel.get_price("CA") print(f"California diesel: ${price.price:.2f}/gallon")

Get nearby stations (paid tiers)

result = client.diesel.get_stations(lat=37.7749, lng=-122.4194) print(f"Found {len(result.stations)} stations")

__init__(client)

Initialize diesel resource.

Parameters:

Name Type Description Default
client

OilPriceAPI client instance

required

get_price(state)

Get average diesel price for a US state.

Returns EIA state-level average diesel price. This endpoint is free and included in all tiers.

Parameters:

Name Type Description Default
state str

Two-letter US state code (e.g., "CA", "TX", "NY")

required

Returns:

Type Description
DieselPrice

DieselPrice object with state average price

Raises:

Type Description
ValidationError

If state code is invalid

DataNotFoundError

If state not found

AuthenticationError

If API key is invalid

RateLimitError

If rate limit exceeded

Example

price = client.diesel.get_price("CA") print(f"California: ${price.price:.2f}/gallon") print(f"Source: {price.source}") print(f"Updated: {price.updated_at}")

Access all fields

print(f"State: {price.state}") print(f"Currency: {price.currency}") print(f"Unit: {price.unit}") print(f"Granularity: {price.granularity}")

get_stations(lat, lng, radius=8047)

Get nearby diesel stations with current pricing.

Returns station-level diesel prices within specified radius using Google Maps data.

Tier Requirements: Available on paid tiers (Exploration and above)

Pricing Tiers: - Exploration: 100 station queries/month - Starter: 500 station queries/month - Professional: 2,000 station queries/month - Business: 5,000 station queries/month

Caching: Results are cached for 24 hours to minimize costs.

Parameters:

Name Type Description Default
lat float

Latitude (-90 to 90)

required
lng float

Longitude (-180 to 180)

required
radius Optional[float]

Search radius in meters (default: 8047 = 5 miles, max: 50000)

8047

Returns:

Type Description
DieselStationsResponse

DieselStationsResponse with nearby stations and regional average

Raises:

Type Description
ValidationError

If coordinates or radius are invalid

AuthenticationError

If API key is invalid

RateLimitError

If monthly station query limit exceeded (429)

OilPriceAPIError

If tier doesn't support station queries (403)

Example

Get stations near San Francisco

result = client.diesel.get_stations( ... lat=37.7749, ... lng=-122.4194, ... radius=8047 # 5 miles ... )

print(f"Regional avg: ${result.regional_average.price:.2f}/gal") print(f"Found {len(result.stations)} stations")

Find cheapest station

cheapest = min(result.stations, key=lambda s: s.diesel_price) print(f"Cheapest: {cheapest.name} at {cheapest.formatted_price}")

Print all stations

for station in result.stations: ... print(f"{station.name}: {station.formatted_price}") ... print(f" {station.address}") ... print(f" {station.price_vs_average}")

to_dataframe(state=None, states=None, lat=None, lng=None, radius=8047)

Get diesel price data as a pandas DataFrame.

Note: Requires pandas to be installed.

Parameters:

Name Type Description Default
state Optional[str]

Single state code for state averages

None
states Optional[List[str]]

Multiple state codes for state averages

None
lat Optional[float]

Latitude for station-level data

None
lng Optional[float]

Longitude for station-level data

None
radius Optional[float]

Search radius in meters (for station-level data)

8047

Returns:

Type Description

pandas DataFrame with diesel price data

Example

State averages DataFrame

df = client.diesel.to_dataframe( ... states=["CA", "TX", "NY", "FL"] ... ) print(df[["state", "price", "updated_at"]])

Station-level DataFrame

df = client.diesel.to_dataframe( ... lat=37.7749, ... lng=-122.4194, ... radius=8047 ... ) print(df[["name", "diesel_price", "price_delta"]])

Plot state averages

df.plot(x="state", y="price", kind="bar", title="Diesel Prices by State")

Alerts

oilpriceapi.resources.alerts.AlertsResource

Price Alerts Resource

Manage automated price alert configurations with webhook notifications.

Features: - Create alerts with customizable conditions - Monitor commodity prices automatically - Webhook notifications when conditions are met - Cooldown periods to prevent spam - 100 alerts per user soft limit

Example:

from oilpriceapi import OilPriceAPI

client = OilPriceAPI()

# Create a price alert
alert = client.alerts.create(
    name='Brent High Price Alert',
    commodity_code='BRENT_CRUDE_USD',
    condition_operator='greater_than',
    condition_value=85.00,
    webhook_url='https://your-app.com/webhooks/price-alert',
    enabled=True,
    cooldown_minutes=60
)

print(f"Alert created: {alert.name} (ID: {alert.id})")

# List all alerts
alerts = client.alerts.list()
print(f"You have {len(alerts)} active alerts")

# Update an alert
updated = client.alerts.update(
    alert.id,
    condition_value=90.00,
    enabled=False
)

# Delete an alert
client.alerts.delete(alert.id)

__init__(client)

Initialize the alerts resource.

Parameters:

Name Type Description Default
client

The OilPriceAPI client instance

required

list()

List all price alerts for the authenticated user.

Returns all configured price alerts, including disabled ones. Alerts are sorted by creation date (newest first).

Returns:

Type Description
List[PriceAlert]

List[PriceAlert]: Array of all price alerts

Raises:

Type Description
OilPriceAPIError

If API request fails

AuthenticationError

If API key is invalid

RateLimitError

If rate limit exceeded

Example

alerts = client.alerts.list() for alert in alerts: ... print(f"{alert.name}: {alert.commodity_code} {alert.condition_operator} {alert.condition_value}") ... print(f" Status: {'Active' if alert.enabled else 'Disabled'}") ... print(f" Triggers: {alert.trigger_count}")

get(alert_id)

Get a specific price alert by ID.

Parameters:

Name Type Description Default
alert_id str

The alert ID to retrieve

required

Returns:

Name Type Description
PriceAlert PriceAlert

The price alert details

Raises:

Type Description
ValidationError

If alert_id is invalid

DataNotFoundError

If alert ID not found

OilPriceAPIError

If API request fails

Example

alert = client.alerts.get('550e8400-e29b-41d4-a716-446655440000') print(f"Alert: {alert.name}") print(f"Condition: {alert.commodity_code} {alert.condition_operator} {alert.condition_value}") print(f"Last triggered: {alert.last_triggered_at or 'Never'}")

create(name, commodity_code, condition_operator, condition_value, webhook_url=None, enabled=True, cooldown_minutes=60, metadata=None)

Create a new price alert.

Creates a price alert that monitors a commodity and triggers when the price meets the specified condition. Optionally sends webhook notifications when triggered.

Validation: - name: 1-100 characters - commodity_code: Must be a valid commodity code - condition_value: Must be > 0 and <= 1,000,000 - cooldown_minutes: Must be 0-1440 (24 hours) - webhook_url: Must be valid HTTPS URL if provided

Soft Limit: 100 alerts per user

Parameters:

Name Type Description Default
name str

Alert name (1-100 characters)

required
commodity_code str

Commodity to monitor (e.g., "BRENT_CRUDE_USD")

required
condition_operator str

Comparison operator (greater_than, less_than, equals, greater_than_or_equal, less_than_or_equal)

required
condition_value float

Price threshold (must be > 0 and <= 1,000,000)

required
webhook_url Optional[str]

Optional HTTPS webhook URL for notifications

None
enabled bool

Whether to enable the alert immediately (default: True)

True
cooldown_minutes int

Minutes between triggers (0-1440, default: 60)

60
metadata Optional[Dict[str, Any]]

Optional custom metadata dictionary

None

Returns:

Name Type Description
PriceAlert PriceAlert

The created price alert

Raises:

Type Description
ValidationError

If parameters are invalid

OilPriceAPIError

If API request fails

Example

Alert when Brent crude exceeds $85

alert = client.alerts.create( ... name='Brent $85 Alert', ... commodity_code='BRENT_CRUDE_USD', ... condition_operator='greater_than', ... condition_value=85.00, ... webhook_url='https://myapp.com/webhook', ... enabled=True, ... cooldown_minutes=120 # 2 hours between triggers ... )

update(alert_id, name=None, commodity_code=None, condition_operator=None, condition_value=None, webhook_url=None, enabled=None, cooldown_minutes=None, metadata=None)

Update an existing price alert.

Updates one or more fields of an existing alert. Only provided fields will be updated; others remain unchanged.

Parameters:

Name Type Description Default
alert_id str

The alert ID to update

required
name Optional[str]

Alert name (1-100 characters)

None
commodity_code Optional[str]

Commodity code to monitor

None
condition_operator Optional[str]

Comparison operator

None
condition_value Optional[float]

Price threshold

None
webhook_url Optional[str]

Webhook URL (or None to remove)

None
enabled Optional[bool]

Whether the alert is active

None
cooldown_minutes Optional[int]

Minutes between triggers (0-1440)

None
metadata Optional[Dict[str, Any]]

Custom metadata dictionary

None

Returns:

Name Type Description
PriceAlert PriceAlert

The updated price alert

Raises:

Type Description
ValidationError

If parameters are invalid

DataNotFoundError

If alert ID not found

OilPriceAPIError

If API request fails

Example

Disable an alert

client.alerts.update(alert_id, enabled=False)

Change threshold and cooldown

client.alerts.update( ... alert_id, ... condition_value=90.00, ... cooldown_minutes=180 ... )

Update webhook URL

client.alerts.update( ... alert_id, ... webhook_url='https://newapp.com/webhook' ... )

delete(alert_id)

Delete a price alert.

Permanently deletes a price alert. This action cannot be undone.

Parameters:

Name Type Description Default
alert_id str

The alert ID to delete

required

Raises:

Type Description
ValidationError

If alert_id is invalid

DataNotFoundError

If alert ID not found

OilPriceAPIError

If API request fails

Example

client.alerts.delete(alert_id) print('Alert deleted successfully')

test(alert_id)

Test an alert by simulating a trigger.

Sends a test notification through the alert's webhook to verify it is configured correctly. Does not count toward trigger limits.

Parameters:

Name Type Description Default
alert_id str

The alert ID to test

required

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Test results including webhook response

Raises:

Type Description
ValidationError

If alert_id is invalid

DataNotFoundError

If alert ID not found

OilPriceAPIError

If API request fails

Example

result = client.alerts.test(alert_id) print(f"Test status: {result['status']}") print(f"Response: {result['webhook_response']}")

triggers(**params)

Get alert trigger history.

Returns a list of all alert triggers across all alerts.

Parameters:

Name Type Description Default
**params

Optional query parameters for filtering

{}

Returns:

Type Description
List[Dict[str, Any]]

List[Dict[str, Any]]: List of alert trigger records

Raises:

Type Description
OilPriceAPIError

If API request fails

Example

triggers = client.alerts.triggers() for trigger in triggers: ... print(f"{trigger['alert_name']}: {trigger['triggered_at']}") ... print(f" Price: ${trigger['price']} (threshold: ${trigger['threshold']})")

analytics_history(**params)

Get alert analytics history.

Returns analytics and statistics about alert performance, trigger frequency, and accuracy over time.

Parameters:

Name Type Description Default
**params

Optional query parameters for filtering

{}

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Analytics data with metrics and trends

Raises:

Type Description
OilPriceAPIError

If API request fails

Example

analytics = client.alerts.analytics_history() print(f"Total triggers: {analytics['total_triggers']}") print(f"Average response time: {analytics['avg_response_time']}ms") print(f"Success rate: {analytics['success_rate']}%")

to_dataframe()

Convert all price alerts to a pandas DataFrame.

Returns a DataFrame with all configured alerts, suitable for analysis and visualization.

Returns:

Type Description

pandas.DataFrame: DataFrame with alerts data

Raises:

Type Description
ImportError

If pandas is not installed

Example

df = client.alerts.to_dataframe() print(df[['name', 'commodity_code', 'enabled', 'trigger_count']])

Filter active alerts

active = df[df['enabled'] == True] print(f"Active alerts: {len(active)}")

Commodities

oilpriceapi.resources.commodities.CommoditiesResource

Resource for commodity catalog operations.

__init__(client)

Initialize commodities resource.

Parameters:

Name Type Description Default
client

OilPriceAPI client instance

required

list()

Get list of all available commodities.

Returns:

Type Description
List[Dict[str, Any]]

List of commodity objects with code, name, and metadata

Example

commodities = client.commodities.list() for commodity in commodities: ... print(f"{commodity['code']}: {commodity['name']}")

get(code)

Get details for a single commodity.

Parameters:

Name Type Description Default
code str

Commodity code (e.g., "BRENT_CRUDE_USD")

required

Returns:

Type Description
Dict[str, Any]

Commodity object with detailed information

Example

commodity = client.commodities.get("BRENT_CRUDE_USD") print(f"Name: {commodity['name']}") print(f"Category: {commodity['category']}") print(f"Unit: {commodity['unit']}")

categories()

Get commodities grouped by category.

Returns:

Type Description
Dict[str, List[Dict[str, Any]]]

Dictionary mapping category names to lists of commodities

Example

categories = client.commodities.categories() for category, commodities in categories.items(): ... print(f"{category}: {len(commodities)} commodities")

Access specific category

crude_oils = categories.get('Crude Oil', [])

Futures

oilpriceapi.resources.futures.FuturesResource

Resource for futures contract operations.

__init__(client)

Initialize futures resource.

Parameters:

Name Type Description Default
client

OilPriceAPI client instance

required

latest(contract)

Get latest futures price for a contract.

Parameters:

Name Type Description Default
contract str

Futures contract code (e.g., "CL.1", "BZ.1")

required

Returns:

Type Description
Dict[str, Any]

Latest futures price data

Example

price = client.futures.latest("CL.1") print(f"WTI Front Month: ${price['price']:.2f}")

historical(contract, start_date=None, end_date=None)

Get historical futures prices for a contract.

Parameters:

Name Type Description Default
contract str

Futures contract code

required
start_date Optional[Union[str, date, datetime]]

Start date for historical data

None
end_date Optional[Union[str, date, datetime]]

End date for historical data

None

Returns:

Type Description
List[Dict[str, Any]]

List of historical price records

Example

history = client.futures.historical( ... contract="CL.1", ... start_date="2024-01-01", ... end_date="2024-12-31" ... ) for record in history: ... print(f"{record['date']}: ${record['price']:.2f}")

ohlc(contract, date=None)

Get OHLC (Open, High, Low, Close) data for a contract.

Parameters:

Name Type Description Default
contract str

Futures contract code

required
date Optional[str]

Specific date for OHLC data (defaults to latest)

None

Returns:

Type Description
Dict[str, Any]

OHLC data with open, high, low, close, and volume

Example

ohlc = client.futures.ohlc("CL.1") print(f"Open: ${ohlc['open']:.2f}") print(f"High: ${ohlc['high']:.2f}") print(f"Low: ${ohlc['low']:.2f}") print(f"Close: ${ohlc['close']:.2f}")

intraday(contract)

Get intraday futures prices for a contract.

Parameters:

Name Type Description Default
contract str

Futures contract code

required

Returns:

Type Description
List[Dict[str, Any]]

List of intraday price records

Example

intraday = client.futures.intraday("CL.1") for record in intraday: ... print(f"{record['time']}: ${record['price']:.2f}")

spreads(contract1, contract2)

Get spread analysis between two futures contracts.

Parameters:

Name Type Description Default
contract1 str

First futures contract code

required
contract2 str

Second futures contract code

required

Returns:

Type Description
Dict[str, Any]

Spread analysis with current spread and historical data

Example

spread = client.futures.spreads("CL.1", "CL.2") print(f"Front Month - Second Month: ${spread['current_spread']:.2f}")

curve(contract)

Get futures curve for a contract.

Parameters:

Name Type Description Default
contract str

Futures contract code

required

Returns:

Type Description
List[Dict[str, Any]]

List of futures curve data points

Example

curve = client.futures.curve("CL") for point in curve: ... print(f"{point['month']}: ${point['price']:.2f}")

continuous(contract, months=12)

Get continuous futures price history.

Parameters:

Name Type Description Default
contract str

Futures contract code

required
months int

Number of months of history (default: 12)

12

Returns:

Type Description
List[Dict[str, Any]]

List of continuous contract prices

Example

continuous = client.futures.continuous("CL", months=24) for record in continuous: ... print(f"{record['date']}: ${record['price']:.2f}")

Storage

oilpriceapi.resources.storage.StorageResource

Resource for oil storage and inventory data.

__init__(client)

Initialize storage resource.

Parameters:

Name Type Description Default
client

OilPriceAPI client instance

required

all()

Get all current storage data.

Returns:

Type Description
Dict[str, Any]

Dictionary with all storage data including Cushing, SPR, and regional

Example

storage = client.storage.all() print(f"Cushing: {storage['cushing']['value']} barrels") print(f"SPR: {storage['spr']['value']} barrels")

cushing()

Get Cushing, OK storage data.

Returns:

Type Description
Dict[str, Any]

Cushing inventory data

Example

cushing = client.storage.cushing() print(f"Cushing Inventory: {cushing['value']} barrels") print(f"Change: {cushing['change']} barrels")

spr()

Get Strategic Petroleum Reserve data.

Returns:

Type Description
Dict[str, Any]

SPR inventory data

Example

spr = client.storage.spr() print(f"SPR Inventory: {spr['value']} barrels") print(f"Updated: {spr['updated_at']}")

regional(region=None)

Get regional storage data.

Parameters:

Name Type Description Default
region Optional[str]

Optional region filter (e.g., "PADD1", "PADD2", "PADD3")

None

Returns:

Type Description
Dict[str, Any]

Regional storage data

Example

regional = client.storage.regional() for region, data in regional.items(): ... print(f"{region}: {data['value']} barrels")

Specific region

padd3 = client.storage.regional(region="PADD3")

history(code, start_date=None, end_date=None)

Get historical storage data for a specific location.

Parameters:

Name Type Description Default
code str

Storage location code (e.g., "cushing", "spr", "padd1")

required
start_date Optional[Union[str, date, datetime]]

Start date for historical data

None
end_date Optional[Union[str, date, datetime]]

End date for historical data

None

Returns:

Type Description
List[Dict[str, Any]]

List of historical storage records

Example

history = client.storage.history( ... code="cushing", ... start_date="2024-01-01", ... end_date="2024-12-31" ... ) for record in history: ... print(f"{record['date']}: {record['value']} barrels")

Rig Counts

oilpriceapi.resources.rig_counts.RigCountsResource

Resource for drilling rig count data.

__init__(client)

Initialize rig counts resource.

Parameters:

Name Type Description Default
client

OilPriceAPI client instance

required

latest()

Get latest rig count data.

Returns:

Type Description
Dict[str, Any]

Latest rig count with oil, gas, and total counts

Example

rig_counts = client.rig_counts.latest() print(f"Oil Rigs: {rig_counts['oil']}") print(f"Gas Rigs: {rig_counts['gas']}") print(f"Total: {rig_counts['total']}")

current()

Get current rig count data.

Alias for latest() for backward compatibility.

Returns:

Type Description
Dict[str, Any]

Current rig count data

Example

rig_counts = client.rig_counts.current() print(f"Total Rigs: {rig_counts['total']}")

historical(start_date=None, end_date=None)

Get historical rig count data.

Parameters:

Name Type Description Default
start_date Optional[Union[str, date, datetime]]

Start date for historical data

None
end_date Optional[Union[str, date, datetime]]

End date for historical data

None

Returns:

Type Description
List[Dict[str, Any]]

List of historical rig count records

Example

history = client.rig_counts.historical( ... start_date="2024-01-01", ... end_date="2024-12-31" ... ) for record in history: ... print(f"{record['date']}: {record['total']} rigs")

trends(period='monthly')

Get rig count trends.

Parameters:

Name Type Description Default
period str

Trend period ("daily", "weekly", "monthly", "yearly")

'monthly'

Returns:

Type Description
Dict[str, Any]

Trend analysis with growth rates and patterns

Example

trends = client.rig_counts.trends(period="monthly") print(f"Monthly Change: {trends['change']} rigs") print(f"Growth Rate: {trends['growth_rate']}%")

summary()

Get rig count summary statistics.

Returns:

Type Description
Dict[str, Any]

Summary with current counts, changes, and breakdowns

Example

summary = client.rig_counts.summary() print(f"Total: {summary['total']}") print(f"Week Change: {summary['week_change']}") print(f"Month Change: {summary['month_change']}") print(f"Year Change: {summary['year_change']}")

Bunker Fuels

oilpriceapi.resources.bunker_fuels.BunkerFuelsResource

Resource for marine bunker fuel prices.

__init__(client)

Initialize bunker fuels resource.

Parameters:

Name Type Description Default
client

OilPriceAPI client instance

required

all()

Get all bunker fuel prices.

Returns:

Type Description
List[Dict[str, Any]]

List of bunker fuel prices across all ports

Example

bunker_prices = client.bunker_fuels.all() for price in bunker_prices: ... print(f"{price['port']}: ${price['price']}/{price['unit']}")

port(code)

Get bunker fuel prices for a specific port.

Parameters:

Name Type Description Default
code str

Port code (e.g., "SINGAPORE", "ROTTERDAM", "HOUSTON")

required

Returns:

Type Description
Dict[str, Any]

Port bunker fuel prices with VLSFO, MGO, IFO380

Example

singapore = client.bunker_fuels.port("SINGAPORE") print(f"VLSFO: ${singapore['vlsfo']['price']}") print(f"MGO: ${singapore['mgo']['price']}") print(f"IFO380: ${singapore['ifo380']['price']}")

compare(ports)

Compare bunker fuel prices across multiple ports.

Parameters:

Name Type Description Default
ports List[str]

List of port codes to compare

required

Returns:

Type Description
Dict[str, Any]

Comparison data with prices and differentials

Example

comparison = client.bunker_fuels.compare([ ... "SINGAPORE", ... "ROTTERDAM", ... "HOUSTON" ... ]) for port, data in comparison.items(): ... print(f"{port}: ${data['vlsfo']['price']}")

spreads()

Get bunker fuel spreads analysis.

Returns:

Type Description
Dict[str, Any]

Spread analysis between fuel types and ports

Example

spreads = client.bunker_fuels.spreads() print(f"VLSFO-MGO Spread: ${spreads['vlsfo_mgo']:.2f}") print(f"VLSFO-IFO380 Spread: ${spreads['vlsfo_ifo380']:.2f}")

historical(port, fuel_type, start_date=None, end_date=None)

Get historical bunker fuel prices.

Parameters:

Name Type Description Default
port str

Port code

required
fuel_type str

Fuel type (e.g., "vlsfo", "mgo", "ifo380")

required
start_date Optional[Union[str, date, datetime]]

Start date for historical data

None
end_date Optional[Union[str, date, datetime]]

End date for historical data

None

Returns:

Type Description
List[Dict[str, Any]]

List of historical price records

Example

history = client.bunker_fuels.historical( ... port="SINGAPORE", ... fuel_type="vlsfo", ... start_date="2024-01-01", ... end_date="2024-12-31" ... ) for record in history: ... print(f"{record['date']}: ${record['price']:.2f}")

export(format='json')

Export bunker fuel data.

Parameters:

Name Type Description Default
format str

Export format ("json", "csv", "xlsx")

'json'

Returns:

Type Description
Any

Exported data in requested format

Example

JSON export

data = client.bunker_fuels.export(format="json")

CSV export

csv_data = client.bunker_fuels.export(format="csv")

Analytics

oilpriceapi.resources.analytics.AnalyticsResource

Resource for price analytics and statistics.

__init__(client)

Initialize analytics resource.

Parameters:

Name Type Description Default
client

OilPriceAPI client instance

required

performance(commodity=None, days=30)

Get price performance analysis.

Parameters:

Name Type Description Default
commodity Optional[str]

Commodity code (if None, returns all commodities)

None
days int

Number of days for performance calculation

30

Returns:

Type Description
Dict[str, Any]

Performance metrics with returns, volatility, and trends

Example

perf = client.analytics.performance("BRENT_CRUDE_USD", days=30) print(f"30-day Return: {perf['return_pct']}%") print(f"Volatility: {perf['volatility']}") print(f"Trend: {perf['trend']}")

statistics(commodity, days=30)

Get statistical analysis for a commodity.

Parameters:

Name Type Description Default
commodity str

Commodity code

required
days int

Number of days for statistical analysis

30

Returns:

Type Description
Dict[str, Any]

Statistical metrics (mean, median, std dev, min, max, etc.)

Example

stats = client.analytics.statistics("WTI_USD", days=90) print(f"Mean: ${stats['mean']:.2f}") print(f"Std Dev: ${stats['std_dev']:.2f}") print(f"Min: ${stats['min']:.2f}") print(f"Max: ${stats['max']:.2f}")

correlation(commodity1, commodity2, days=90)

Get correlation analysis between two commodities.

Parameters:

Name Type Description Default
commodity1 str

First commodity code

required
commodity2 str

Second commodity code

required
days int

Number of days for correlation calculation

90

Returns:

Type Description
Dict[str, Any]

Correlation metrics and analysis

Example

corr = client.analytics.correlation( ... "BRENT_CRUDE_USD", ... "WTI_USD", ... days=90 ... ) print(f"Correlation: {corr['correlation']:.3f}") print(f"P-value: {corr['p_value']:.4f}")

trend(commodity, days=30)

Get trend analysis for a commodity.

Parameters:

Name Type Description Default
commodity str

Commodity code

required
days int

Number of days for trend analysis

30

Returns:

Type Description
Dict[str, Any]

Trend metrics with direction, strength, and momentum

Example

trend = client.analytics.trend("NATURAL_GAS_USD", days=30) print(f"Direction: {trend['direction']}") print(f"Strength: {trend['strength']}") print(f"Momentum: {trend['momentum']}")

spread(commodity1, commodity2)

Get spread analysis between two commodities.

Parameters:

Name Type Description Default
commodity1 str

First commodity code

required
commodity2 str

Second commodity code

required

Returns:

Type Description
Dict[str, Any]

Spread analysis with current spread and historical statistics

Example

spread = client.analytics.spread("BRENT_CRUDE_USD", "WTI_USD") print(f"Current Spread: ${spread['current']:.2f}") print(f"Average Spread: ${spread['average']:.2f}") print(f"Spread Percentile: {spread['percentile']}")

forecast(commodity)

Get price forecast for a commodity.

Parameters:

Name Type Description Default
commodity str

Commodity code

required

Returns:

Type Description
Dict[str, Any]

Forecast with predicted prices and confidence intervals

Example

forecast = client.analytics.forecast("BRENT_CRUDE_USD") print(f"7-day Forecast: ${forecast['7_day']['price']:.2f}") print(f"30-day Forecast: ${forecast['30_day']['price']:.2f}") print(f"Confidence: {forecast['confidence']}")

Forecasts

oilpriceapi.resources.forecasts.ForecastsResource

Resource for official price forecasts from EIA and other agencies.

__init__(client)

Initialize forecasts resource.

Parameters:

Name Type Description Default
client

OilPriceAPI client instance

required

monthly(commodity=None)

Get monthly price forecasts.

Parameters:

Name Type Description Default
commodity Optional[str]

Optional commodity code filter

None

Returns:

Type Description
Dict[str, Any]

Monthly forecasts from EIA and other agencies

Example

forecasts = client.forecasts.monthly() for forecast in forecasts: ... print(f"{forecast['period']}: ${forecast['price']:.2f}")

Specific commodity

wti_forecasts = client.forecasts.monthly(commodity="WTI_USD")

accuracy()

Get forecast accuracy metrics.

Returns:

Type Description
Dict[str, Any]

Historical accuracy analysis of forecasts vs actual prices

Example

accuracy = client.forecasts.accuracy() print(f"30-day Accuracy: {accuracy['30_day']['accuracy']}%") print(f"90-day Accuracy: {accuracy['90_day']['accuracy']}%") print(f"Mean Absolute Error: {accuracy['mae']}")

archive(year=None)

Get archived forecasts.

Parameters:

Name Type Description Default
year Optional[int]

Optional year filter for archived forecasts

None

Returns:

Type Description
List[Dict[str, Any]]

List of historical forecasts

Example

archive = client.forecasts.archive(year=2024) for forecast in archive: ... print(f"{forecast['date']}: {forecast['commodity']} = ${forecast['price']:.2f}")

get(period, commodity=None)

Get forecast for a specific period.

Parameters:

Name Type Description Default
period str

Forecast period (e.g., "2025-01", "2025-Q1")

required
commodity Optional[str]

Optional commodity code filter

None

Returns:

Type Description
Dict[str, Any]

Forecast data for the specified period

Example

forecast = client.forecasts.get("2025-03", commodity="BRENT_CRUDE_USD") print(f"March 2025 Brent Forecast: ${forecast['price']:.2f}") print(f"Range: ${forecast['low']:.2f} - ${forecast['high']:.2f}")

Data Quality

oilpriceapi.resources.data_quality.DataQualityResource

Resource for data quality monitoring.

__init__(client)

Initialize data quality resource.

Parameters:

Name Type Description Default
client

OilPriceAPI client instance

required

summary()

Get data quality summary.

Returns:

Type Description
Dict[str, Any]

Summary of data quality metrics across all commodities

Example

summary = client.data_quality.summary() print(f"Overall Quality Score: {summary['score']}") print(f"Commodities: {summary['total_commodities']}") print(f"Issues: {summary['total_issues']}")

reports()

Get all data quality reports.

Returns:

Type Description
List[Dict[str, Any]]

List of data quality reports for all commodities

Example

reports = client.data_quality.reports() for report in reports: ... print(f"{report['commodity']}: {report['quality_score']}%") ... if report['issues']: ... print(f" Issues: {', '.join(report['issues'])}")

report(code)

Get data quality report for a specific commodity.

Parameters:

Name Type Description Default
code str

Commodity code

required

Returns:

Type Description
Dict[str, Any]

Detailed data quality report

Example

report = client.data_quality.report("BRENT_CRUDE_USD") print(f"Quality Score: {report['quality_score']}%") print(f"Last Update: {report['last_update']}") print(f"Update Frequency: {report['update_frequency']}") print(f"Data Completeness: {report['completeness']}%") print(f"Data Accuracy: {report['accuracy']}%") if report['issues']: ... print(f"Issues: {report['issues']}")

Drilling Intelligence

oilpriceapi.resources.drilling.DrillingIntelligenceResource

Resource for drilling intelligence data.

__init__(client)

Initialize drilling intelligence resource.

Parameters:

Name Type Description Default
client

OilPriceAPI client instance

required

list(**params)

Get all drilling intelligence data.

Parameters:

Name Type Description Default
**params

Optional query parameters for filtering

{}

Returns:

Type Description
List[Dict[str, Any]]

List of drilling intelligence records

Example

data = client.drilling.list() for record in data: ... print(f"{record['basin']}: {record['rig_count']} rigs")

latest()

Get latest drilling intelligence data.

Returns:

Type Description
Dict[str, Any]

Latest drilling intelligence summary

Example

latest = client.drilling.latest() print(f"Total rigs: {latest['total_rigs']}") print(f"Frac spreads: {latest['frac_spreads']}")

summary()

Get drilling intelligence summary.

Returns:

Type Description
Dict[str, Any]

Summary statistics for drilling activity

Example

summary = client.drilling.summary() print(f"Active rigs: {summary['active_rigs']}") print(f"Total wells: {summary['total_wells']}")

trends(**params)

Get drilling activity trends.

Parameters:

Name Type Description Default
**params

Optional query parameters for filtering

{}

Returns:

Type Description
List[Dict[str, Any]]

List of trend data points

Example

trends = client.drilling.trends() for point in trends: ... print(f"{point['date']}: {point['rig_count']} rigs")

frac_spreads(**params)

Get frac spread data.

Parameters:

Name Type Description Default
**params

Optional query parameters for filtering

{}

Returns:

Type Description
List[Dict[str, Any]]

List of frac spread records

Example

spreads = client.drilling.frac_spreads() for spread in spreads: ... print(f"{spread['basin']}: {spread['count']} spreads")

well_permits(**params)

Get well permit data.

Parameters:

Name Type Description Default
**params

Optional query parameters for filtering

{}

Returns:

Type Description
List[Dict[str, Any]]

List of well permit records

Example

permits = client.drilling.well_permits() for permit in permits: ... print(f"{permit['operator']}: {permit['count']} permits")

duc_wells(**params)

Get DUC (Drilled but Uncompleted) wells data.

Parameters:

Name Type Description Default
**params

Optional query parameters for filtering

{}

Returns:

Type Description
List[Dict[str, Any]]

List of DUC well records

Example

ducs = client.drilling.duc_wells() for duc in ducs: ... print(f"{duc['basin']}: {duc['count']} DUCs")

completions(**params)

Get well completion data.

Parameters:

Name Type Description Default
**params

Optional query parameters for filtering

{}

Returns:

Type Description
List[Dict[str, Any]]

List of completion records

Example

completions = client.drilling.completions() for completion in completions: ... print(f"{completion['basin']}: {completion['count']} completions")

wells_drilled(**params)

Get wells drilled data.

Parameters:

Name Type Description Default
**params

Optional query parameters for filtering

{}

Returns:

Type Description
List[Dict[str, Any]]

List of wells drilled records

Example

wells = client.drilling.wells_drilled() for well in wells: ... print(f"{well['basin']}: {well['count']} wells")

basin(name)

Get drilling data for a specific basin.

Parameters:

Name Type Description Default
name str

Basin name

required

Returns:

Type Description
Dict[str, Any]

Basin-specific drilling data

Example

permian = client.drilling.basin("permian") print(f"Permian rigs: {permian['rig_count']}") print(f"DUCs: {permian['duc_count']}")

Webhooks

oilpriceapi.resources.webhooks.WebhooksResource

Resource for webhook management.

__init__(client)

Initialize webhooks resource.

Parameters:

Name Type Description Default
client

OilPriceAPI client instance

required

list(**params)

Get all webhooks.

Parameters:

Name Type Description Default
**params

Optional query parameters for filtering

{}

Returns:

Type Description
List[Dict[str, Any]]

List of webhook records

Example

webhooks = client.webhooks.list() for webhook in webhooks: ... print(f"{webhook['url']}: {webhook['events']}")

get(webhook_id)

Get a specific webhook by ID.

Parameters:

Name Type Description Default
webhook_id str

Webhook ID

required

Returns:

Type Description
Dict[str, Any]

Webhook details

Example

webhook = client.webhooks.get("123") print(f"URL: {webhook['url']}") print(f"Events: {webhook['events']}")

create(url, events, description=None, secret=None, enabled=True, **kwargs)

Create a new webhook.

Parameters:

Name Type Description Default
url str

Webhook endpoint URL (must be HTTPS)

required
events List[str]

List of event types to subscribe to

required
description Optional[str]

Optional description

None
secret Optional[str]

Optional webhook secret for signature verification

None
enabled bool

Whether the webhook is active (default: True)

True
**kwargs

Additional webhook configuration

{}

Returns:

Type Description
Dict[str, Any]

Created webhook details

Example

webhook = client.webhooks.create( ... url="https://myapp.com/webhook", ... events=["price.updated", "alert.triggered"], ... description="Price alerts webhook", ... enabled=True ... ) print(f"Webhook created: {webhook['id']}")

update(webhook_id, url=None, events=None, description=None, secret=None, enabled=None, **kwargs)

Update an existing webhook.

Parameters:

Name Type Description Default
webhook_id str

Webhook ID to update

required
url Optional[str]

Webhook endpoint URL

None
events Optional[List[str]]

List of event types to subscribe to

None
description Optional[str]

Description

None
secret Optional[str]

Webhook secret for signature verification

None
enabled Optional[bool]

Whether the webhook is active

None
**kwargs

Additional webhook configuration

{}

Returns:

Type Description
Dict[str, Any]

Updated webhook details

Example

webhook = client.webhooks.update( ... webhook_id="123", ... events=["price.updated"], ... enabled=False ... ) print(f"Webhook updated: {webhook['id']}")

delete(webhook_id)

Delete a webhook.

Parameters:

Name Type Description Default
webhook_id str

Webhook ID to delete

required
Example

client.webhooks.delete("123") print("Webhook deleted")

test(webhook_id)

Test a webhook by sending a test event.

Parameters:

Name Type Description Default
webhook_id str

Webhook ID to test

required

Returns:

Type Description
Dict[str, Any]

Test result details

Example

result = client.webhooks.test("123") print(f"Test status: {result['status']}") print(f"Response: {result['response']}")

events(webhook_id, **params)

Get webhook event history.

Parameters:

Name Type Description Default
webhook_id str

Webhook ID

required
**params

Optional query parameters for filtering

{}

Returns:

Type Description
List[Dict[str, Any]]

List of webhook event records

Example

events = client.webhooks.events("123") for event in events: ... print(f"{event['created_at']}: {event['type']} - {event['status']}")

verify_signature(payload, signature, secret) staticmethod

Verify a webhook signature.

Validates that a webhook payload was sent by OilPriceAPI by checking the HMAC-SHA256 signature. Uses constant-time comparison to prevent timing attacks.

Parameters:

Name Type Description Default
payload bytes

Raw request body as bytes

required
signature str

Value of the X-OilPriceAPI-Signature header (e.g., "sha256=abc123...")

required
secret str

Your webhook signing secret

required

Returns:

Type Description
bool

True if signature is valid

Example

Flask example

@app.route('/webhook', methods=['POST']) def handle_webhook(): ... sig = request.headers.get('X-OilPriceAPI-Signature', '') ... if not client.webhooks.verify_signature(request.data, sig, 'secret'): ... abort(401) ... return '', 200

Data Sources

oilpriceapi.resources.data_sources.DataSourcesResource

Resource for data source connector management.

__init__(client)

Initialize data sources resource.

Parameters:

Name Type Description Default
client

OilPriceAPI client instance

required

list(**params)

Get all data sources.

Parameters:

Name Type Description Default
**params

Optional query parameters for filtering

{}

Returns:

Type Description
List[Dict[str, Any]]

List of data source records

Example

sources = client.data_sources.list() for source in sources: ... print(f"{source['name']}: {source['type']}")

get(source_id)

Get a specific data source by ID.

Parameters:

Name Type Description Default
source_id str

Data source ID

required

Returns:

Type Description
Dict[str, Any]

Data source details

Example

source = client.data_sources.get("123") print(f"Name: {source['name']}") print(f"Type: {source['type']}") print(f"Status: {source['status']}")

create(name, source_type, credentials, config=None, enabled=True, **kwargs)

Create a new data source.

Parameters:

Name Type Description Default
name str

Data source name

required
source_type str

Type of data source (e.g., "platts", "argus", "opis")

required
credentials Dict[str, Any]

Credentials for the data source

required
config Optional[Dict[str, Any]]

Optional configuration settings

None
enabled bool

Whether the data source is active (default: True)

True
**kwargs

Additional data source configuration

{}

Returns:

Type Description
Dict[str, Any]

Created data source details

Example

source = client.data_sources.create( ... name="Platts API", ... source_type="platts", ... credentials={ ... "api_key": "your-api-key", ... "api_secret": "your-secret" ... }, ... config={ ... "fetch_interval": 300 ... }, ... enabled=True ... ) print(f"Data source created: {source['id']}")

update(source_id, name=None, credentials=None, config=None, enabled=None, **kwargs)

Update an existing data source.

Parameters:

Name Type Description Default
source_id str

Data source ID to update

required
name Optional[str]

Data source name

None
credentials Optional[Dict[str, Any]]

Credentials for the data source

None
config Optional[Dict[str, Any]]

Configuration settings

None
enabled Optional[bool]

Whether the data source is active

None
**kwargs

Additional data source configuration

{}

Returns:

Type Description
Dict[str, Any]

Updated data source details

Example

source = client.data_sources.update( ... source_id="123", ... config={"fetch_interval": 600}, ... enabled=False ... ) print(f"Data source updated: {source['id']}")

delete(source_id)

Delete a data source.

Parameters:

Name Type Description Default
source_id str

Data source ID to delete

required
Example

client.data_sources.delete("123") print("Data source deleted")

test(source_id)

Test a data source connection.

Parameters:

Name Type Description Default
source_id str

Data source ID to test

required

Returns:

Type Description
Dict[str, Any]

Test result details

Example

result = client.data_sources.test("123") print(f"Test status: {result['status']}") print(f"Message: {result['message']}")

logs(source_id, **params)

Get data source logs.

Parameters:

Name Type Description Default
source_id str

Data source ID

required
**params

Optional query parameters for filtering

{}

Returns:

Type Description
List[Dict[str, Any]]

List of log entries

Example

logs = client.data_sources.logs("123", limit=100) for log in logs: ... print(f"{log['timestamp']}: {log['level']} - {log['message']}")

health(source_id)

Get data source health status.

Parameters:

Name Type Description Default
source_id str

Data source ID

required

Returns:

Type Description
Dict[str, Any]

Health status details

Example

health = client.data_sources.health("123") print(f"Status: {health['status']}") print(f"Last successful fetch: {health['last_success']}") print(f"Error count: {health['error_count']}")

rotate_credentials(source_id, new_credentials)

Rotate data source credentials.

Parameters:

Name Type Description Default
source_id str

Data source ID

required
new_credentials Dict[str, Any]

New credentials to set

required

Returns:

Type Description
Dict[str, Any]

Updated data source details

Example

source = client.data_sources.rotate_credentials( ... source_id="123", ... new_credentials={ ... "api_key": "new-api-key", ... "api_secret": "new-secret" ... } ... ) print(f"Credentials rotated for: {source['name']}")