Python Oil Price API
Get Oil Prices in Python with 3 Lines of Code
Simple Python library for real-time oil prices. Works with pandas, numpy, and your favorite data tools.
pip install oilpriceapi
from oilpriceapi import OilPriceAPI
client = OilPriceAPI(api_key="your_free_key")
wti = client.prices.get("WTI_USD")
brent = client.prices.get("BRENT_CRUDE_USD")
print(f"WTI: ${wti.value}/barrel")
print(f"Brent: ${brent.value}/barrel")
# Output:
# WTI: $71.23/barrel
# Brent: $74.89/barrelInstallation & Setup
1. Install via pip
pip install oilpriceapiRequirements: Python 3.7+, requests library (auto-installed)
3. Make Your First Call
from oilpriceapi import OilPriceAPI
# Initialize client
client = OilPriceAPI(api_key="YOUR_API_KEY")
# Get latest price
wti = client.prices.get("WTI_USD")
print(f"${wti.value}")
# Get historical data
historical = client.historical.get(
commodity="WTI_USD",
start_date="2024-01-01",
end_date="2024-12-31"
)Async Support for High-Performance Apps
import asyncio
from oilpriceapi import AsyncOilPriceAPI
async def get_prices():
async with AsyncOilPriceAPI() as client:
# Fetch multiple commodities concurrently
prices = await asyncio.gather(
client.prices.get("BRENT_CRUDE_USD"),
client.prices.get("WTI_USD"),
client.prices.get("NATURAL_GAS_USD")
)
for price in prices:
print(f"{price.commodity}: ${price.value}")
asyncio.run(get_prices())
# Output:
# BRENT_CRUDE_USD: $74.89
# WTI_USD: $71.23
# NATURAL_GAS_USD: $2.89Async support with connection pooling (max 100 concurrent, 20 keepalive). Perfect for data pipelines and trading systems.
Python Code Examples
Pandas DataFrame Integration
import pandas as pd
from oilpriceapi import OilPriceAPI
client = OilPriceAPI(api_key="KEY")
# Get data as DataFrame
df = client.get_dataframe(
commodities=["WTI_USD", "BRENT_USD"],
start_date="2024-01-01"
)
# Analyze with pandas
df['spread'] = df['BRENT_USD'] - df['WTI_USD']
monthly_avg = df.resample('M').mean()WebSocket Streaming
from oilpriceapi import OilPriceStream
stream = OilPriceStream(api_key="KEY")
def on_price_update(data):
print(f"New price: {data}")
# Stream real-time prices
stream.subscribe(
commodities=["WTI_USD"],
callback=on_price_update
)
stream.connect()Price Alert System
from oilpriceapi import OilPriceAPI
client = OilPriceAPI(api_key="KEY")
# Set price alerts
client.create_alert(
commodity="WTI_USD",
condition="above",
threshold=70.00,
webhook_url="https://your-app.com"
)
# Monitor positions
if client.get_price("WTI_USD") > 70:
send_notification("WTI above $70!")Statistical Analysis
import numpy as np
from oilpriceapi import OilPriceAPI
client = OilPriceAPI(api_key="KEY")
# Get 30-day historical
data = client.get_historical(
"WTI_USD", days=30
)
prices = [d['price'] for d in data]
# Calculate metrics
volatility = np.std(prices)
mean_price = np.mean(prices)
price_range = max(prices) - min(prices)Python SDK Features
Core Features
- ✓Async/await support for high performance
- ✓Automatic retry with exponential backoff
- ✓Built-in caching to reduce API calls
- ✓Type hints for better IDE support
- ✓Comprehensive error handling
Data Science Ready
- ✓Native pandas DataFrame support
- ✓NumPy array conversion
- ✓Jupyter notebook compatible
- ✓Matplotlib/Plotly integration
- ✓Time series analysis utilities
Built for Python Developers
Quantitative Trading
Build trading algorithms with real-time oil price data. Backtest strategies using historical data.
Data Analysis
Analyze energy markets with pandas and NumPy. Create visualizations with matplotlib.
Machine Learning
Train models to predict oil prices. Use scikit-learn, TensorFlow, or PyTorch with our data.
Django/Flask Apps
Build web applications with oil price data. Perfect for energy dashboards and analytics.
Automation Scripts
Automate reporting and alerts. Schedule cron jobs to monitor price movements.
Research & Academia
Academic research on energy markets. Economic modeling with real commodity data.
Frequently Asked Questions
How do I install the Python Oil Price API SDK?
Install via pip with a single command: pip install oilpriceapi. The SDK requires Python 3.7+ and has minimal dependencies for fast installation.
What Python versions are supported?
The SDK supports Python 3.7 and higher, including Python 3.11 and 3.12. It works with both sync and async code patterns for maximum compatibility.
Can I use this with pandas/numpy?
Yes! The SDK has built-in pandas DataFrame support with a get_dataframe() method. It also integrates seamlessly with NumPy for numerical analysis and Matplotlib for visualization.
Is the SDK async-compatible?
Yes! Use AsyncOilPriceAPI for async/await support with connection pooling (max 100 concurrent, 20 keepalive) perfect for high-performance applications.
How do I handle errors in the Python SDK?
The SDK includes automatic retry with exponential backoff and comprehensive error handling. All API errors raise descriptive exceptions with helpful error messages.
Can I cache API responses?
Yes! The SDK has built-in caching to reduce API calls and improve performance. Configure cache TTL and storage backend to match your application needs.
Is the SDK type-hinted?
Yes! Full type hints are included for better IDE support with autocomplete, type checking, and inline documentation. Works great with mypy and other type checkers.
Where can I find Python code examples?
Check out our GitHub repository and API documentation for comprehensive examples covering pandas, async, streaming, and more.
Ready to get started with real-time oil price data?
Get your API key