You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
287 lines
9.9 KiB
Python
287 lines
9.9 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
Stock Oracle Client Usage Examples
|
|
|
|
This script demonstrates how to use the Stock Oracle Python client
|
|
for various data retrieval tasks.
|
|
"""
|
|
|
|
import sys
|
|
import os
|
|
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
|
|
|
from stock_oracle_client import StockOracleClient, ETFDataNotAvailableError, PriceInterval, PeriodType
|
|
from datetime import datetime, date, timedelta
|
|
import json
|
|
|
|
|
|
def print_section(title):
|
|
"""Helper to print section headers"""
|
|
print("\n" + "="*60)
|
|
print(f" {title}")
|
|
print("="*60)
|
|
|
|
|
|
def example_basic_usage():
|
|
"""Basic client usage examples"""
|
|
print_section("BASIC USAGE")
|
|
|
|
# Initialize client
|
|
client = StockOracleClient("http://localhost:18001")
|
|
|
|
# Check API health
|
|
health = client.get_health()
|
|
print(f"✅ API Status: {health['status']}")
|
|
print(f" Version: {health.get('version', 'Unknown')}")
|
|
|
|
# Get financial data for Apple
|
|
print("\n📊 Financial Data (AAPL - Last Year):")
|
|
financial = client.get_financial_data("AAPL", period="1y")
|
|
print(f" Company: {financial['company']['name']}")
|
|
print(f" Sector: {financial['company'].get('sector', 'N/A')}")
|
|
print(f" Data points: {len(financial['financial_data'])}")
|
|
|
|
if financial['financial_data']:
|
|
latest = financial['financial_data'][0]
|
|
print(f" Latest filing: {latest['date']}")
|
|
if 'metrics' in latest:
|
|
metrics = latest['metrics']
|
|
print(f" P/E Ratio: {metrics.get('pe_ratio', 'N/A')}")
|
|
print(f" ROE: {metrics.get('return_on_equity', 'N/A'):.2%}" if metrics.get('return_on_equity') else " ROE: N/A")
|
|
|
|
# Get price data
|
|
print("\n📈 Price Data (AAPL - Last 3 Months):")
|
|
prices = client.get_price_data("AAPL", period="3m")
|
|
print(f" Data points: {len(prices['price_data'])}")
|
|
if prices['price_data']:
|
|
latest = prices['price_data'][-1]
|
|
print(f" Latest date: {latest['date']}")
|
|
print(f" Close: ${latest['close']:.2f}")
|
|
print(f" Volume: {latest['volume']:,}")
|
|
|
|
|
|
def example_etf_holdings():
|
|
"""ETF holdings examples with availability checking"""
|
|
print_section("ETF HOLDINGS")
|
|
|
|
client = StockOracleClient("http://localhost:18001")
|
|
|
|
# Get current ETF holdings
|
|
print("\n📊 Current Holdings (QQQ):")
|
|
etf = client.get_etf_holdings("QQQ", include_holdings=True)
|
|
if etf['success']:
|
|
print(f" As of: {etf['as_of_date']}")
|
|
print(f" Total holdings: {etf['data']['holdings_count']}")
|
|
print(f" Total value: ${etf['data']['filing_info']['total_value']:,.2f}")
|
|
|
|
# Show top 5 holdings
|
|
if etf['data']['holdings']:
|
|
print("\n Top 5 Holdings:")
|
|
for i, holding in enumerate(etf['data']['holdings'][:5], 1):
|
|
print(f" {i}. {holding['name']}: {holding['percentage']:.2f}%")
|
|
|
|
# Check availability for historical date
|
|
print("\n📅 Availability Check (QQQM on 2020-01-01):")
|
|
availability = client.check_etf_availability("QQQM", "2020-01-01")
|
|
|
|
if not availability.get('exists_for_date'):
|
|
print(f" ❌ ETF did not exist on 2020-01-01")
|
|
if availability.get('etf_launch_date'):
|
|
print(f" Launch date: {availability['etf_launch_date']}")
|
|
if availability.get('available_date_range'):
|
|
date_range = availability['available_date_range']
|
|
print(f" Available from: {date_range['start']} to {date_range['end']}")
|
|
|
|
# Try with fallback
|
|
print("\n🔄 ETF Holdings with Fallback (QQQM):")
|
|
try:
|
|
etf = client.get_etf_holdings_with_fallback("QQQM", "2020-01-01", include_holdings=False)
|
|
print(f" ✅ Got data for: {etf['as_of_date']}")
|
|
print(f" Holdings count: {etf['data']['holdings_count']}")
|
|
except ETFDataNotAvailableError as e:
|
|
print(f" ❌ No data available: {e}")
|
|
|
|
|
|
def example_bulk_operations():
|
|
"""Bulk data retrieval examples"""
|
|
print_section("BULK OPERATIONS")
|
|
|
|
client = StockOracleClient("http://localhost:18001")
|
|
|
|
# Bulk financial data
|
|
print("\n💼 Bulk Financial Data (Tech Giants):")
|
|
tickers = ["AAPL", "MSFT", "GOOGL", "AMZN", "META"]
|
|
bulk_financial = client.get_bulk_financial_data(
|
|
tickers,
|
|
period="6m",
|
|
period_type=PeriodType.QUARTERLY,
|
|
include_metrics=True
|
|
)
|
|
|
|
print(f" Requested: {len(bulk_financial['requested_tickers'])} tickers")
|
|
print(f" Successful: {len(bulk_financial['results'])}")
|
|
|
|
# Show summary for each ticker
|
|
for ticker in tickers:
|
|
if ticker in bulk_financial['results']:
|
|
data = bulk_financial['results'][ticker]
|
|
if data['financial_data']:
|
|
latest = data['financial_data'][0]
|
|
print(f" {ticker}: Latest filing {latest['date']}")
|
|
|
|
# Bulk ETF holdings
|
|
print("\n📊 Bulk ETF Holdings:")
|
|
etf_tickers = ["QQQ", "SPY", "ARKK", "IWM"]
|
|
bulk_etf = client.get_bulk_etf_holdings(etf_tickers, include_holdings=False)
|
|
|
|
print(f" Total ETFs: {bulk_etf['total']}")
|
|
print(f" Successful: {bulk_etf['successful']}")
|
|
|
|
for ticker, data in bulk_etf['results'].items():
|
|
if data.get('success'):
|
|
print(f" {ticker}: {data['data']['holdings_count']} holdings as of {data['as_of_date']}")
|
|
|
|
|
|
def example_advanced_queries():
|
|
"""Advanced query examples with date ranges and intervals"""
|
|
print_section("ADVANCED QUERIES")
|
|
|
|
client = StockOracleClient("http://localhost:18001")
|
|
|
|
# Specific date range query
|
|
print("\n📅 Date Range Query (Q1 2024):")
|
|
start_date = date(2024, 1, 1)
|
|
end_date = date(2024, 3, 31)
|
|
|
|
financial = client.get_financial_data(
|
|
"MSFT",
|
|
start_date=start_date,
|
|
end_date=end_date,
|
|
period_type=PeriodType.QUARTERLY
|
|
)
|
|
|
|
print(f" Period: {start_date} to {end_date}")
|
|
print(f" Data points: {len(financial['financial_data'])}")
|
|
|
|
# Different price intervals
|
|
print("\n⏰ Price Data with Different Intervals:")
|
|
intervals = [
|
|
(PriceInterval.ONE_DAY, "Daily"),
|
|
(PriceInterval.ONE_WEEK, "Weekly"),
|
|
(PriceInterval.ONE_MONTH, "Monthly")
|
|
]
|
|
|
|
for interval, label in intervals:
|
|
prices = client.get_price_data(
|
|
"TSLA",
|
|
period="3m",
|
|
interval=interval
|
|
)
|
|
print(f" {label}: {len(prices['price_data'])} data points")
|
|
|
|
# Historical ETF data
|
|
print("\n📜 Historical ETF Data (SPY - 1 year ago):")
|
|
one_year_ago = (datetime.now() - timedelta(days=365)).date()
|
|
|
|
try:
|
|
etf = client.get_etf_holdings("SPY", as_of_date=one_year_ago, include_holdings=False)
|
|
if etf['success']:
|
|
print(f" Date: {etf['as_of_date']}")
|
|
print(f" Holdings: {etf['data']['holdings_count']}")
|
|
print(f" Total value: ${etf['data']['filing_info']['total_value']:,.2f}")
|
|
except ETFDataNotAvailableError as e:
|
|
print(f" ❌ Data not available: {e}")
|
|
|
|
|
|
def example_error_handling():
|
|
"""Error handling examples"""
|
|
print_section("ERROR HANDLING")
|
|
|
|
client = StockOracleClient("http://localhost:18001", auto_retry=True, max_retries=2)
|
|
|
|
# Invalid ticker
|
|
print("\n❌ Invalid Ticker Test:")
|
|
try:
|
|
data = client.get_financial_data("INVALID123", period="1m")
|
|
except Exception as e:
|
|
print(f" Expected error: {e}")
|
|
|
|
# ETF that didn't exist on date
|
|
print("\n❌ ETF Before Launch Date:")
|
|
try:
|
|
etf = client.get_etf_holdings("ARKK", as_of_date="2010-01-01")
|
|
except ETFDataNotAvailableError as e:
|
|
print(f" Expected error: {e}")
|
|
if e.availability_info:
|
|
print(f" ETF launch date: {e.availability_info.get('etf_launch_date', 'Unknown')}")
|
|
|
|
# Ticker validation
|
|
print("\n✅ Ticker Validation:")
|
|
valid_tickers = ["AAPL", "MSFT", "INVALID"]
|
|
for ticker in valid_tickers:
|
|
is_valid = client.validate_ticker(ticker)
|
|
print(f" {ticker}: {'Valid ✅' if is_valid else 'Invalid ❌'}")
|
|
|
|
|
|
def example_utilities():
|
|
"""Utility functions and helper methods"""
|
|
print_section("UTILITY FUNCTIONS")
|
|
|
|
client = StockOracleClient("http://localhost:18001")
|
|
|
|
# Get supported ETFs
|
|
print("\n📋 Supported ETFs:")
|
|
supported = client.get_supported_etfs()
|
|
print(f" Total: {supported['total_etfs']} ETFs")
|
|
print(f" Examples: {', '.join(supported['supported_tickers'][:10])}...")
|
|
|
|
# Search tickers (client-side)
|
|
print("\n🔍 Ticker Search:")
|
|
queries = ["AA", "APP", "GO"]
|
|
for query in queries:
|
|
results = client.search_tickers(query)
|
|
print(f" '{query}': {results}")
|
|
|
|
# Get latest filing date
|
|
print("\n📅 Latest Filing Dates:")
|
|
tickers = ["AAPL", "MSFT", "GOOGL"]
|
|
for ticker in tickers:
|
|
filing_date = client.get_latest_filing_date(ticker)
|
|
print(f" {ticker}: {filing_date if filing_date else 'N/A'}")
|
|
|
|
# Get data catalog
|
|
print("\n📚 Data Catalog Sample:")
|
|
catalog = client.get_data_catalog()
|
|
if 'categories' in catalog:
|
|
for category, fields in list(catalog['categories'].items())[:2]:
|
|
print(f" {category}: {len(fields)} fields")
|
|
|
|
|
|
def main():
|
|
"""Run all examples"""
|
|
print("\n" + "="*60)
|
|
print(" STOCK ORACLE CLIENT EXAMPLES")
|
|
print("="*60)
|
|
print("\nMake sure the API is running at http://localhost:18001")
|
|
|
|
try:
|
|
# Run examples
|
|
example_basic_usage()
|
|
example_etf_holdings()
|
|
example_bulk_operations()
|
|
example_advanced_queries()
|
|
example_error_handling()
|
|
example_utilities()
|
|
|
|
print("\n" + "="*60)
|
|
print(" ✅ ALL EXAMPLES COMPLETED SUCCESSFULLY")
|
|
print("="*60)
|
|
|
|
except Exception as e:
|
|
print(f"\n❌ Error running examples: {e}")
|
|
import traceback
|
|
traceback.print_exc()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main() |