Skip to main content

Official Python SDK for OilPriceAPI - Real-time and historical oil prices

Project description

OilPriceAPI Python SDK

PyPI version Python Tests Coverage License: MIT

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

🚀 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

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

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


Made with ❤️ by the OilPriceAPI Team

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

oilpriceapi-1.0.1.tar.gz (29.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

oilpriceapi-1.0.1-py3-none-any.whl (27.2 kB view details)

Uploaded Python 3

File details

Details for the file oilpriceapi-1.0.1.tar.gz.

File metadata

  • Download URL: oilpriceapi-1.0.1.tar.gz
  • Upload date:
  • Size: 29.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.3

File hashes

Hashes for oilpriceapi-1.0.1.tar.gz
Algorithm Hash digest
SHA256 b985fa31bd5d9c39368d8aedc138b83c7ed7d9770dbf9943e7ce16435bf39b95
MD5 e62dabab2cc0b48b3c3a706dbe76b7e9
BLAKE2b-256 4c6580cb5fbacd2f49740bfa15e49075109aa513c212899b020eaf5424840ea5

See more details on using hashes here.

File details

Details for the file oilpriceapi-1.0.1-py3-none-any.whl.

File metadata

  • Download URL: oilpriceapi-1.0.1-py3-none-any.whl
  • Upload date:
  • Size: 27.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.3

File hashes

Hashes for oilpriceapi-1.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 c4d2dd47d2d97c578e38a89fccf31085fce987b6ad3d5a6233d3a00a57710979
MD5 108dacb5a4a5ea9ad5fbcd272c27aa82
BLAKE2b-256 e7e9020204493b26076a33d93b81d046c780a98879944420cd7f3143b96415b1

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page