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 price records available to the account.
Auto-paginates using X-Has-Next response headers until the API reports no additional records.
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 returned for the current account |
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 request, from 1 to 1000. Auto-pagination fetches every page for all-current and historical queries. |
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', per_page=DEFAULT_AUTO_PAGE_SIZE)
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'
|
per_page
|
int
|
Records per request, from 1 to 1000. Defaults to 500. |
DEFAULT_AUTO_PAGE_SIZE
|
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', per_page=DEFAULT_AUTO_PAGE_SIZE)
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'
|
per_page
|
int
|
Records per request, from 1 to 1000. All pages are fetched automatically; defaults to 500. |
DEFAULT_AUTO_PAGE_SIZE
|
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 the available state average
price = client.diesel.get_price("CA") print(f"California diesel: ${price.price:.2f}/gallon")
Get nearby stations when enabled for the current account
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 the available EIA state-level average diesel price. Access and request limits follow the account's current entitlement and API metadata.
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.
Station-level access and allowances depend on the account's current entitlement. Review https://www.oilpriceapi.com/pricing and the API's response metadata instead of relying on SDK-bundled limits.
Use the returned source timestamp to apply the application's freshness policy.
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 the API reports the request limit exceeded (429) |
OilPriceAPIError
|
If the account cannot access 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 commodities available to the current account.
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']}")
search(query, limit=10)
Search the API's current commodity catalog.
The catalog is fetched on every call so results do not depend on a stale code list bundled with the SDK. Network and API errors retain their normal typed exceptions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query
|
str
|
Words from a code, name, category, description, currency, unit, or source. |
required |
limit
|
int
|
Maximum results, from 1 to 100. |
10
|
Returns:
| Type | Description |
|---|---|
List[Dict[str, Any]]
|
Ranked commodity objects, or an empty list when nothing matches. |
Example
matches = client.commodities.search("brent crude") for item in matches: ... print(item["code"])
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 the latest futures curve for a contract family.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
contract
|
str
|
Futures slug (e.g. |
required |
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Latest futures curve data (front month + forward contracts) |
Example
curve = client.futures.latest("brent")
Friendly code form also works:
curve = client.futures.latest("BZ") print(curve["front_month"]["last_price"])
historical(contract, start_date=None, end_date=None)
Get historical futures prices for a contract.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
contract
|
str
|
Futures slug or friendly contract code (see |
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="wti", ... 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 slug or friendly contract code (see |
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("wti") 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 slug or friendly contract code (see |
required |
Returns:
| Type | Description |
|---|---|
List[Dict[str, Any]]
|
List of intraday price records |
Example
intraday = client.futures.intraday("wti") 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 the futures curve (contango/backwardation) for a contract.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
contract
|
str
|
Futures slug or friendly contract code (see |
required |
Returns:
| Type | Description |
|---|---|
List[Dict[str, Any]]
|
List of futures curve data points |
Example
curve = client.futures.curve("wti") for point in curve: ... print(f"{point['month']}: ${point['price']:.2f}")
continuous(contract, months=12)
Get continuous (auto-rolled) front-month futures history.
Continuous series are exposed at /v1/futures/continuous/{brent,wti}.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
contract
|
str
|
A continuous slug ( |
required |
months
|
int
|
Number of months of history (default: 12) |
12
|
Returns:
| Type | Description |
|---|---|
List[Dict[str, Any]]
|
List of continuous contract prices |
Example
history = client.futures.continuous("continuous/wti", months=24) for record in history: ... 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 the available bunker fuel price records.
Returns:
| Type | Description |
|---|---|
List[Dict[str, Any]]
|
List of bunker fuel price records returned by the API |
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
|
OilPriceAPI client instance |
required |
performance(commodity=None, days=30)
Get API usage performance analytics for the authenticated user.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
commodity
|
Optional[str]
|
Accepted for backwards compatibility; the controller does not filter performance by commodity. |
None
|
days
|
int
|
Number of days for the performance window. Mapped to the
controller's |
30
|
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Performance metrics for the user's API usage. |
Example
perf = client.analytics.performance(days=30)
statistics(commodity, days=30)
Get statistical analysis for a commodity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
commodity
|
str
|
Commodity code (sent to the API as |
required |
days
|
int
|
Number of days for statistical analysis (sent as |
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)
correlation(commodity1, commodity2, days=90)
Get correlation analysis between two commodities.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
commodity1
|
str
|
First commodity code (sent to the API as |
required |
commodity2
|
str
|
Second commodity code (sent to the API as |
required |
days
|
int
|
Number of days for correlation calculation (sent as |
90
|
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Correlation metrics and analysis |
Example
corr = client.analytics.correlation( ... "BRENT_CRUDE_USD", ... "WTI_USD", ... days=90, ... )
trend(commodity, days=30)
Get trend analysis for a commodity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
commodity
|
str
|
Commodity code (sent to the API as |
required |
days
|
int
|
Number of days for trend analysis (sent as |
30
|
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Trend metrics with direction, strength, and momentum |
Example
trend = client.analytics.trend("NATURAL_GAS_USD", days=30)
spread(spread, days=30)
Get spread analysis for a named commodity spread.
The spread endpoint operates on a named spread (e.g. "wti_brent"),
not an arbitrary pair of commodity codes. Call without spread set via
:meth:available_spreads to discover valid names.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spread
|
str
|
Spread name, e.g. |
required |
days
|
int
|
Number of days of history to analyze (sent as |
30
|
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Spread analysis with current spread and historical statistics |
Example
spread = client.analytics.spread("wti_brent")
available_spreads()
List the named spreads supported by the spread endpoint.
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Catalog of available spread names (the controller returns this when |
Dict[str, Any]
|
no |
Example
spreads = client.analytics.available_spreads()
forecast(commodity, method='ema', days=90)
Get price forecast for a commodity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
commodity
|
str
|
Commodity code (sent to the API as |
required |
method
|
str
|
Forecast method (sent as |
'ema'
|
days
|
int
|
Number of days of history to base the forecast on (sent as |
90
|
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Forecast with predicted prices and confidence intervals |
Example
forecast = client.analytics.forecast("BRENT_CRUDE_USD")
Spreads
oilpriceapi.resources.spreads.SpreadsResource
Resource for /v1/spreads/*.
__init__(client)
Initialize spreads resource.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
Any
|
OilPriceAPI client instance |
required |
crack(spread_type=None, crude=None)
Get the latest crack spread.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spread_type
|
Optional[str]
|
|
None
|
crude
|
Optional[str]
|
Crude benchmark code, e.g. |
None
|
Returns:
| Type | Description |
|---|---|
CrackSpread
|
CrackSpread with |
CrackSpread
|
|
Raises:
| Type | Description |
|---|---|
ValidationError
|
If an argument is blank (raised locally,
|
DataNotFoundError
|
Unknown spread type, or no data for an input. |
Example
crack = client.spreads.crack(spread_type="diesel", crude="WTI_USD") print(crack.value, crack.unit, crack.timestamp)
crack_historical(spread_type=None, crude=None, start_date=None, end_date=None)
Get daily crack spread history.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spread_type
|
Optional[str]
|
Spread type; server default |
None
|
crude
|
Optional[str]
|
Crude benchmark code; server default |
None
|
start_date
|
Optional[DateInput]
|
|
None
|
end_date
|
Optional[DateInput]
|
|
None
|
Returns:
| Type | Description |
|---|---|
CrackSpreadHistory
|
CrackSpreadHistory. |
CrackSpreadHistory
|
|
CrackSpreadHistory
|
before assuming the full window is present. |
CrackSpreadHistory
|
changes when the underlying inputs are restated. |
Raises:
| Type | Description |
|---|---|
ValidationError
|
Blank selector, invalid date, or start after end
(raised locally, |
crack_all(crude=None)
Get every crack spread type for one crude benchmark.
Types without data are omitted by the server rather than returned empty.
gasoil_crack()
Get the European gasoil crack (ICE Low Sulphur Gasoil vs ICE Brent).
The gasoil leg is quoted in USD/tonne; conversion states the
barrels-per-tonne factor used to express the spread in USD/bbl, and each
leg names its contract_month.
basis(pair)
Get the latest basis spread for a pair.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pair
|
str
|
Pair key, e.g. |
required |
Raises:
| Type | Description |
|---|---|
ValidationError
|
If |
DataNotFoundError
|
Unknown pair (the message lists valid pairs). |
Example
spread = client.spreads.basis("BRENT_WTI") spread.components {'BRENT_CRUDE_USD': 104.32, 'WTI_USD': 99.99}
basis_historical(pair, start_date=None, end_date=None)
Get daily basis spread history for a pair.
Note: the API answers an unknown pair on this route with an empty
200 rather than a 404, so count == 0 can mean a misspelled pair.
Use :meth:basis_all to list valid pairs.
basis_all()
Get the latest value for every basis pair with data.
curve_structure(commodity)
Get futures curve structure (backwardation/contango) for a market.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
commodity
|
str
|
|
required |
curve_structure_all()
Get curve structure for every market with a usable curve.
margin(index=None)
Get the latest refinery margin.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index
|
Optional[str]
|
|
None
|
margin_historical(index=None, start_date=None, end_date=None)
Get daily refinery margin history (unknown index returns empty).
margin_all()
Get the latest margin for every index with data.
physical_premium(commodity=None)
Get the latest physical (spot) vs futures premium.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
commodity
|
Optional[str]
|
|
None
|
physical_premium_historical(commodity=None, start_date=None, end_date=None)
Get daily physical premium history. An empty data list is a
valid result when the server has no overlapping spot/futures days.
physical_premium_all()
Get the latest premium for every commodity with data.
Indicators
oilpriceapi.resources.indicators.IndicatorsResource
Resource for /v1/indicators/*.
__init__(client)
Initialize indicators resource.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
Any
|
OilPriceAPI client instance |
required |
fuel_switching(gas=None, crude=None)
Get gas-to-oil parity (fuel-switching economics).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
gas
|
Optional[str]
|
|
None
|
crude
|
Optional[str]
|
|
None
|
Example
parity = client.indicators.fuel_switching() print(parity.oil_parity.ratio_pct, parity.oil_parity.signal)
fuel_switching_historical(gas=None, crude=None, start_date=None, end_date=None)
Get daily gas-to-oil parity history (server default: last 90 days).
price_context(code, related_spreads=False)
Get the latest price with historical context for a commodity code.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
code
|
str
|
Commodity code, e.g. |
required |
related_spreads
|
bool
|
Also return the spreads related to |
False
|
Returns:
| Type | Description |
|---|---|
PriceContext
|
PriceContext. Context metrics the server could not compute (not |
PriceContext
|
enough history) are |
Raises:
| Type | Description |
|---|---|
ValidationError
|
If |
DataNotFoundError
|
No data for |
storage_analytics(location=None)
Get storage analytics for "CUSHING" (server default) or "SPR".
storage_analytics_all()
Get storage analytics for every location with data.
annotations(code)
Get notable-condition annotations (anomaly, velocity, streak, 52-week record) for a commodity code.
annotations_batch(codes)
Get annotations for up to 20 commodity codes in one request.
The server leaves out codes it has no data for and codes with no
annotations. More than 20 codes raises ValidationError locally, because
the API silently annotates only the first 20.
cftc_positioning(commodity=None)
Get the latest CFTC Commitments of Traders positioning.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
commodity
|
Optional[str]
|
|
None
|
cftc_positioning_historical(commodity=None, start_date=None, end_date=None)
Get weekly CFTC speculative net positioning history.
cftc_positioning_all()
Get the latest positioning for every market with data.
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
|
Any
|
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 returned by the API |
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 the available data quality reports.
Returns:
| Type | Description |
|---|---|
List[Dict[str, Any]]
|
List of data quality reports returned by the API |
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
|
Any
|
OilPriceAPI client instance |
required |
list(**params)
Get all drilling intelligence data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**params
|
Any
|
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
|
Any
|
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
|
Any
|
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
|
Any
|
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
|
Any
|
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
|
Any
|
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
|
Any
|
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']}")
Fuel Surcharges
oilpriceapi.resources.fuel_surcharge.FuelSurchargeResource
Resource for LTL and parcel carrier fuel surcharges.
__init__(client)
Initialize fuel surcharge resource.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
Any
|
OilPriceAPI client instance |
required |
list()
Latest LTL surcharge for every carrier that has data.
Returns:
| Type | Description |
|---|---|
List[FuelSurchargeRate]
|
One |
List[FuelSurchargeRate]
|
data are absent, not zero. |
Example
for rate in client.fuel_surcharge.list(): ... print(rate.carrier, rate.surcharge_percent, rate.effective_date)
latest(carrier)
Latest LTL surcharge for one carrier.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
carrier
|
str
|
Public carrier slug, e.g. |
required |
Raises:
| Type | Description |
|---|---|
ValidationError
|
The slug is empty or not a slug (no request sent). |
DataNotFoundError
|
Unknown, not-yet-covered, or no data retrieved.
|
Example
rate = client.fuel_surcharge.latest("odfl") print(rate.surcharge_percent, rate.effective_date, rate.source)
history(carrier, page=None, per_page=None)
Weekly LTL surcharge history for one carrier, newest first.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
carrier
|
str
|
Public carrier slug. |
required |
page
|
Optional[int]
|
Page number, 1 or more. Server default is 1. |
None
|
per_page
|
Optional[int]
|
Rows per page, 1 to 100. Server default is 100. |
None
|
Returns:
| Type | Description |
|---|---|
FuelSurchargeHistoryPage
|
|
FuelSurchargeHistoryPage
|
|
Raises:
| Type | Description |
|---|---|
ValidationError
|
Bad slug or out-of-range pagination (no request sent). |
DataNotFoundError
|
Unknown carrier or no data retrieved. |
Example
page = client.fuel_surcharge.history("odfl", per_page=10) print(page.meta.total_count)
parcel_list()
Latest parcel surcharge per service level, for every parcel carrier.
Example
for carrier in client.fuel_surcharge.parcel_list(): ... for rate in carrier.service_levels: ... print(carrier.carrier, rate.service_level, rate.surcharge_percent)
parcel_latest(carrier)
Latest surcharge for every service level of one parcel carrier.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
carrier
|
str
|
Parcel carrier slug, e.g. |
required |
Example
ups = client.fuel_surcharge.parcel_latest("ups") [rate.service_level for rate in ups.service_levels]
parcel_latest_rate(carrier, service_level)
Latest surcharge for one parcel carrier and service level.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
carrier
|
str
|
Parcel carrier slug, e.g. |
required |
service_level
|
str
|
Service level, e.g. |
required |
Raises:
| Type | Description |
|---|---|
DataNotFoundError
|
No data for that carrier and service level. |
Example
rate = client.fuel_surcharge.parcel_latest_rate("ups", "ground")
parcel_history(carrier, service_level, page=None, per_page=None)
Weekly surcharge history for one parcel carrier and service level.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
carrier
|
str
|
Parcel carrier slug. |
required |
service_level
|
str
|
Required by the API, e.g. |
required |
page
|
Optional[int]
|
Page number, 1 or more. |
None
|
per_page
|
Optional[int]
|
Rows per page, 1 to 100. |
None
|
Example
page = client.fuel_surcharge.parcel_history("ups", "ground", per_page=4)
Well Production (Beta)
oilpriceapi.resources.well_production.WellProductionResource
Resource for US well production data (beta).
__init__(client)
Initialize well production resource.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
Any
|
OilPriceAPI client instance |
required |
summary()
Get the national production overview.
Returns the latest national rollup, top producing states, data sources, and coverage metadata.
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Summary dict with |
Dict[str, Any]
|
|
Example
overview = client.well_production.summary() for state in overview["top_states"]: ... print(f"{state['state']}: {state['oil_bbl']} bbl")
states(period=None, **params)
Get state-level production for a month.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
period
|
Optional[str]
|
Optional month in |
None
|
**params
|
Any
|
Additional query parameters. |
{}
|
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Dict with |
Dict[str, Any]
|
by oil production descending. |
Example
result = client.well_production.states(period="2026-04") for state in result["states"]: ... print(f"{state['state']}: {state['oil_bpd']} bpd")
state(code, start_date=None, end_date=None, **params)
Get production history for a specific state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
code
|
str
|
Two-letter state code, e.g. |
required |
start_date
|
Optional[str]
|
Optional |
None
|
end_date
|
Optional[str]
|
Optional |
None
|
**params
|
Any
|
Additional query parameters. |
{}
|
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Dict with |
Dict[str, Any]
|
|
Raises:
| Type | Description |
|---|---|
DataNotFoundError
|
If no production data exists for the state. |
Example
tx = client.well_production.state("TX", start_date="2026-01-01") for month in tx["data"]: ... print(f"{month['period']}: {month['oil_bbl']} bbl")
well(api_number)
Get production history for a specific well (beta).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
api_number
|
str
|
14-digit API well number. Separators such as dashes
are stripped automatically ( |
required |
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Dict with |
Dict[str, Any]
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the API number is not 14 digits after removing separators. |
DataNotFoundError
|
If no production data exists for the well. |
Example
well = client.well_production.well("42285343290000") print(f"{well['well_name']} ({well['operator']})")
top_producers(state_code='TX', limit=20, months=None, **params)
Get top producing wells for a state (beta).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state_code
|
str
|
Two-letter state code (default |
'TX'
|
limit
|
int
|
Maximum wells to return (server caps at 100). |
20
|
months
|
Optional[int]
|
Optional lookback window in months (default 12). |
None
|
**params
|
Any
|
Additional query parameters. |
{}
|
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Dict with |
Dict[str, Any]
|
list of wells with total oil/gas volumes. |
Example
top = client.well_production.top_producers("NM", limit=10) for well in top["producers"]: ... print(f"{well['well_name']}: {well['total_oil_bbl']} bbl")
cycle_time(state=None, start_date=None, end_date=None, operator=None, formation=None, lat=None, lng=None, radius_miles=None, **params)
Get permit-to-production cycle time analysis (beta).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
Optional[str]
|
Optional two-letter state code filter. |
None
|
start_date
|
Optional[str]
|
Optional |
None
|
end_date
|
Optional[str]
|
Optional |
None
|
operator
|
Optional[str]
|
Optional operator name filter. |
None
|
formation
|
Optional[str]
|
Optional formation name filter. |
None
|
lat
|
Optional[float]
|
Optional latitude for a geographic cohort. |
None
|
lng
|
Optional[float]
|
Optional longitude for a geographic cohort. |
None
|
radius_miles
|
Optional[float]
|
Optional radius (miles) around lat/lng. |
None
|
**params
|
Any
|
Additional query parameters. |
{}
|
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Dict with |
Dict[str, Any]
|
p90 days), |
Raises:
| Type | Description |
|---|---|
DataNotFoundError
|
If no wells match the filters. |
Example
ct = client.well_production.cycle_time(state="TX") print(f"Median: {ct['cycle_time_stats']['median_days']} days")
cycle_time_cohorts(state=None, start_date=None, end_date=None, lat=None, lng=None, radius_miles=None, group_by=None, **params)
Compare cycle times across cohorts (beta).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
Optional[str]
|
Optional two-letter state code filter. |
None
|
start_date
|
Optional[str]
|
Optional |
None
|
end_date
|
Optional[str]
|
Optional |
None
|
lat
|
Optional[float]
|
Optional latitude for a geographic cohort. |
None
|
lng
|
Optional[float]
|
Optional longitude for a geographic cohort. |
None
|
radius_miles
|
Optional[float]
|
Optional radius (miles) around lat/lng. |
None
|
group_by
|
Optional[str]
|
Cohort grouping field (default |
None
|
**params
|
Any
|
Additional query parameters. |
{}
|
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Dict with |
Dict[str, Any]
|
to well counts and cycle-time stats. |
Example
cohorts = client.well_production.cycle_time_cohorts(state="TX") for quarter, stats in cohorts["cohorts"].items(): ... print(f"{quarter}: {stats['stats']['median_days']} days")
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']}")
Subscriptions
Agent price watches: list, create, get, update, pause, resume,
delete, and the events poll. A subscription here is a watch on commodity
codes, not a billing subscription.
oilpriceapi.resources.subscriptions.SubscriptionsResource
Resource for agent-subscription CRUD and event polling.
__init__(client)
Initialize subscriptions resource.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
Any
|
OilPriceAPI client instance |
required |
list()
List all subscriptions for the authenticated user.
Returns:
| Type | Description |
|---|---|
List[Subscription]
|
List of Subscription models. Empty only when the API sent an empty |
List[Subscription]
|
list. |
Raises:
| Type | Description |
|---|---|
OilPriceAPIError
|
|
Example
for sub in client.subscriptions.list(): ... print(sub.name, sub.codes)
create(codes, interval, name=None, source=None, tool=None)
Create a new subscription (watch).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
codes
|
List[str]
|
Commodity codes to watch (e.g. ["BRENT_CRUDE_USD"]). |
required |
interval
|
Union[str, int]
|
Friendly interval ("5m", "1h", "daily") or seconds (int). |
required |
name
|
Optional[str]
|
Optional human-friendly name. |
None
|
source
|
Optional[str]
|
Attribution source header (defaults to "sdk-python"). |
None
|
tool
|
Optional[str]
|
Optional attribution tool name header. |
None
|
Returns:
| Type | Description |
|---|---|
Subscription
|
The created Subscription model. |
Example
sub = client.subscriptions.create( ... ["BRENT_CRUDE_USD"], interval="5m", name="Brent watch" ... )
get(subscription_id)
Fetch one subscription.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
subscription_id
|
str
|
The id returned by |
required |
Returns:
| Type | Description |
|---|---|
Subscription
|
The Subscription, with the server's timestamps and nulls as sent. |
Raises:
| Type | Description |
|---|---|
ValidationError
|
If the id is malformed ( |
DataNotFoundError
|
If no subscription with that id belongs to you. |
OilPriceAPIError
|
|
Example
sub = client.subscriptions.get("f72ceac2-8b9a-406a-a57e-90c625785444") sub.status 'active'
update(subscription_id, *, name=None, codes=None, interval=None, deliver_webhook=None, status=None)
Change a subscription. Only the arguments you pass are sent.
Sent once: a PATCH is not replayed after a timeout or 5xx. If one of
those is raised with ambiguous_write=True, call get() to see
whether the change landed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
subscription_id
|
str
|
The subscription to change. |
required |
name
|
Optional[str]
|
New name. |
None
|
codes
|
Optional[List[str]]
|
Replacement list of commodity codes. |
None
|
interval
|
Optional[Union[str, int]]
|
Friendly interval ("5m", "1h", "daily") or seconds. |
None
|
deliver_webhook
|
Optional[bool]
|
Whether events are delivered by webhook. |
None
|
status
|
Optional[str]
|
|
None
|
Returns:
| Type | Description |
|---|---|
Subscription
|
The updated Subscription as the server stored it. |
Raises:
| Type | Description |
|---|---|
ValidationError
|
|
DataNotFoundError
|
If the subscription does not exist. |
ValidationError
|
422 when the server refuses the change, for example an interval below your plan minimum or webhook delivery your plan does not include. |
Example
client.subscriptions.update(sub.id, name="Brent hourly", interval="1h")
pause(subscription_id)
Pause a subscription so it stops being evaluated.
Sent once, like every write in this SDK: after an ambiguous timeout or
5xx, call get() to check the status rather than retrying blind.
Returns:
| Type | Description |
|---|---|
Subscription
|
The Subscription, with |
Example
client.subscriptions.pause(sub.id).status 'paused'
resume(subscription_id)
Resume a paused subscription. The server schedules it to run now.
Returns:
| Type | Description |
|---|---|
Subscription
|
The Subscription, with |
Subscription
|
|
Example
client.subscriptions.resume(sub.id).status 'active'
delete(subscription_id)
Delete a subscription.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
subscription_id
|
str
|
The subscription id to delete. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True on success. |
Raises:
| Type | Description |
|---|---|
ValidationError
|
If the id is malformed ( |
Example
client.subscriptions.delete(sub.id)
events(since=None, limit=None, watch_id=None)
Poll for subscription events newer than a cursor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
since
|
Optional[int]
|
|
None
|
limit
|
Optional[int]
|
Max events to return (server clamps to its own max). |
None
|
watch_id
|
Optional[str]
|
Restrict to a single subscription. |
None
|
Returns:
| Type | Description |
|---|---|
SubscriptionEventsPage
|
A SubscriptionEventsPage with events, cursor, and has_more. The |
SubscriptionEventsPage
|
cursor is always an |
SubscriptionEventsPage
|
restarts from the beginning. |
Raises:
| Type | Description |
|---|---|
ValidationError
|
|
OilPriceAPIError
|
|
Example
page = client.subscriptions.events(since=0) for event in page: ... print(event.seq, event.watch_id) next_page = client.subscriptions.events(since=page.cursor)