Skip to content

OilpriceAPI/python-sdk

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

18 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

OilPriceAPI Python SDK

Real-time oil and commodity price data for Python - Professional-grade API at 98% less cost than Bloomberg Terminal

PyPI version PyPI Downloads Python Tests Coverage License: MIT

Get Free API Key β€’ Documentation β€’ Examples β€’ Pricing

The official Python SDK for OilPriceAPI - Real-time and historical oil prices for Brent Crude, WTI, Natural Gas, and more.

Quick start:

pip install oilpriceapi

πŸš€ Quick Start

Installation

pip install oilpriceapi

Basic Usage

from oilpriceapi import OilPriceAPI

# Initialize client (uses OILPRICEAPI_KEY env var by default)
client = OilPriceAPI()

# Get latest Brent Crude price
brent = client.prices.get("BRENT_CRUDE_USD")
print(f"Brent Crude: ${brent.value:.2f}")
# Output: Brent Crude: $71.45

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

Historical Data with Pandas

# Get historical data as DataFrame
df = client.prices.to_dataframe(
    commodity="BRENT_CRUDE_USD",
    start="2024-01-01",
    end="2024-12-31",
    interval="daily"
)

# Add technical indicators
df = client.analysis.with_indicators(
    df,
    indicators=["sma_20", "sma_50", "rsi", "bollinger_bands"]
)

# Calculate spread between Brent and WTI
spread = client.analysis.spread("BRENT_CRUDE_USD", "WTI_USD", start="2024-01-01")

πŸ“Š Features

  • βœ… Simple API - Intuitive methods for all endpoints
  • βœ… Type Safe - Full type hints for IDE autocomplete
  • βœ… Pandas Integration - First-class DataFrame support
  • βœ… Async Support - High-performance async client
  • βœ… Smart Caching - Reduce API calls automatically
  • βœ… Rate Limit Handling - Automatic retries with backoff
  • βœ… Technical Indicators - Built-in SMA, RSI, MACD, etc.
  • βœ… CLI Tool - Command-line interface included

πŸ“š Documentation

Complete SDK Documentation β†’ | Online Docs β†’

Authentication

# Method 1: Environment variable (recommended)
export OILPRICEAPI_KEY="your_api_key"
client = OilPriceAPI()

# Method 2: Direct initialization
client = OilPriceAPI(api_key="your_api_key")

# Method 3: With configuration
client = OilPriceAPI(
    api_key="your_api_key",
    timeout=30,
    max_retries=3,
    cache="memory",
    cache_ttl=300
)

Available Commodities

  • BRENT_CRUDE_USD - Brent Crude Oil
  • WTI_USD - West Texas Intermediate
  • NATURAL_GAS_USD - Natural Gas
  • DIESEL_USD - Diesel
  • GASOLINE_USD - Gasoline
  • HEATING_OIL_USD - Heating Oil
  • View all commodities

Error Handling

from oilpriceapi.exceptions import OilPriceAPIError, RateLimitError, DataNotFoundError

try:
    price = client.prices.get("INVALID_CODE")
except DataNotFoundError as e:
    print(f"Commodity not found: {e}")
except RateLimitError as e:
    print(f"Rate limited. Resets in {e.seconds_until_reset}s")
except OilPriceAPIError as e:
    print(f"API error: {e}")

⚑ Async Support

import asyncio
from oilpriceapi import AsyncOilPriceAPI

async def get_prices():
    async with AsyncOilPriceAPI() as client:
        prices = await asyncio.gather(
            client.prices.get("BRENT_CRUDE_USD"),
            client.prices.get("WTI_USD"),
            client.prices.get("NATURAL_GAS_USD")
        )
        return prices

# Run async function
prices = asyncio.run(get_prices())

πŸ› οΈ CLI Tool

# Get current price
oilprice get BRENT_CRUDE_USD

# Export historical data
oilprice export WTI_USD --start 2024-01-01 --format csv -o wti_2024.csv

# Watch prices in real-time
oilprice watch BRENT_CRUDE_USD --interval 60

πŸ§ͺ Testing

The SDK includes utilities for testing your applications:

from oilpriceapi.testing import MockClient

def test_my_strategy():
    client = MockClient()
    client.set_price("BRENT_CRUDE_USD", 75.50)

    result = my_trading_strategy(client)
    assert result.action == "BUY"

πŸ“ˆ Examples

Real-World Use Cases

See EXAMPLES.md for comprehensive examples including:

  • πŸ“Š Trading Strategies - Moving averages, spread analysis, risk management
  • πŸ“ˆ Data Analysis - Seasonal patterns, correlations, forecasting
  • πŸ’» Web Applications - Dashboards, REST APIs, monitoring systems
  • πŸ“€ Data Export - Excel reports, database integration, alerts

Code Samples

Check out the examples/ directory for:

πŸ”§ Development

# Clone repository
git clone https://github.com/oilpriceapi/python-sdk
cd python-sdk

# Install development dependencies
pip install -e ".[dev]"

# Run tests
pytest

# Format code
black .

# Type checking
mypy oilpriceapi

πŸ“ License

MIT License - see LICENSE file for details.

🀝 Contributing

Contributions are welcome! Please see our Contributing Guide for details.

πŸ’¬ Support

πŸ”— Links


🌟 Why OilPriceAPI?

OilPriceAPI provides professional-grade commodity price data at 98% less cost than Bloomberg Terminal ($24,000/year vs $45/month). Trusted by energy traders, financial analysts, and developers worldwide.

Key Benefits

  • ⚑ Real-time data updated every 5 minutes
  • πŸ“Š Historical data for trend analysis and backtesting
  • πŸ”’ 99.9% uptime with enterprise-grade reliability
  • πŸš€ 5-minute integration with this Python SDK
  • πŸ’° Free tier with 1,000 requests/month to get started

Start Free β†’ | View Pricing β†’ | Read Docs β†’


Made with ❀️ by the OilPriceAPI Team

About

Official Python SDK for OilPriceAPI - Real-time and historical oil, gas, and energy commodity price data

Topics

Resources

License

Code of conduct

Contributing

Security policy

Stars

Watchers

Forks

Packages

No packages published

Contributors 2

  •  
  •