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.
190 lines
7.1 KiB
Python
190 lines
7.1 KiB
Python
"""
|
|
Test script to compare Stock Oracle financial data with direct yfinance data
|
|
"""
|
|
|
|
import asyncio
|
|
import requests
|
|
import yfinance_plus as yf
|
|
from datetime import datetime, timezone
|
|
import pandas as pd
|
|
import json
|
|
from typing import Dict, Any
|
|
|
|
# API configuration
|
|
API_URL = "http://localhost:18001/api/v1"
|
|
|
|
def get_yfinance_data(ticker: str) -> Dict[str, Any]:
|
|
"""Get financial data directly from yfinance"""
|
|
print(f"\n=== Getting yfinance data for {ticker} ===")
|
|
|
|
# Create ticker object
|
|
stock = yf.Ticker(ticker)
|
|
|
|
# Get basic info
|
|
info = stock.info
|
|
print(f"Company: {info.get('longName', 'N/A')}")
|
|
print(f"Sector: {info.get('sector', 'N/A')}")
|
|
print(f"Industry: {info.get('industry', 'N/A')}")
|
|
|
|
# Get quarterly financial statements
|
|
quarterly_income = stock.quarterly_income_stmt
|
|
quarterly_balance = stock.quarterly_balance_sheet
|
|
quarterly_cashflow = stock.quarterly_cashflow
|
|
|
|
# Get current price data
|
|
current_price = info.get('currentPrice', info.get('regularMarketPrice', 0))
|
|
market_cap = info.get('marketCap', 0)
|
|
|
|
print("\n=== Quarterly Income Statement ===")
|
|
if not quarterly_income.empty:
|
|
print(quarterly_income.iloc[:, 0:2]) # Show latest 2 quarters
|
|
|
|
print("\n=== Quarterly Balance Sheet ===")
|
|
if not quarterly_balance.empty:
|
|
print(quarterly_balance.iloc[:, 0:2]) # Show latest 2 quarters
|
|
|
|
print("\n=== Quarterly Cash Flow ===")
|
|
if not quarterly_cashflow.empty:
|
|
print(quarterly_cashflow.iloc[:, 0:2]) # Show latest 2 quarters
|
|
|
|
# Extract specific metrics for comparison
|
|
yfinance_data = {
|
|
'info': info,
|
|
'quarterly_income': quarterly_income.to_dict() if not quarterly_income.empty else {},
|
|
'quarterly_balance': quarterly_balance.to_dict() if not quarterly_balance.empty else {},
|
|
'quarterly_cashflow': quarterly_cashflow.to_dict() if not quarterly_cashflow.empty else {},
|
|
'current_price': current_price,
|
|
'market_cap': market_cap
|
|
}
|
|
|
|
return yfinance_data
|
|
|
|
def get_stock_oracle_data(ticker: str, start_date: str, end_date: str) -> Dict[str, Any]:
|
|
"""Get financial data from Stock Oracle API"""
|
|
print(f"\n=== Getting Stock Oracle data for {ticker} ===")
|
|
|
|
# Request data from API
|
|
response = requests.post(
|
|
f"{API_URL}/financial/data",
|
|
json={
|
|
"ticker": ticker,
|
|
"start_date": start_date,
|
|
"end_date": end_date,
|
|
"period_type": "all",
|
|
"include_metrics": True,
|
|
"force_refresh": False
|
|
}
|
|
)
|
|
|
|
if response.status_code == 200:
|
|
data = response.json()
|
|
print(f"Company: {data['company']['name']}")
|
|
print(f"Sector: {data['company']['sector']}")
|
|
print(f"Industry: {data['company']['industry']}")
|
|
print(f"Number of periods: {len(data['financial_data'])}")
|
|
return data
|
|
else:
|
|
print(f"Error: {response.status_code} - {response.text}")
|
|
return None
|
|
|
|
def compare_financial_metrics(yfinance_data: Dict, oracle_data: Dict):
|
|
"""Compare financial metrics between yfinance and Stock Oracle"""
|
|
print("\n=== COMPARISON RESULTS ===")
|
|
|
|
if not oracle_data or 'financial_data' not in oracle_data:
|
|
print("No Stock Oracle data to compare")
|
|
return
|
|
|
|
# Get the latest quarter from Stock Oracle
|
|
latest_oracle = oracle_data['financial_data'][-1] if oracle_data['financial_data'] else None
|
|
|
|
if not latest_oracle:
|
|
print("No financial data in Stock Oracle")
|
|
return
|
|
|
|
print(f"\nStock Oracle Latest Period: {latest_oracle['period_date']}")
|
|
|
|
# Compare basic metrics
|
|
print("\n--- Revenue Comparison ---")
|
|
oracle_revenue = latest_oracle.get('revenue', 0)
|
|
print(f"Stock Oracle Revenue: ${oracle_revenue:,.2f}")
|
|
|
|
# Try to get revenue from yfinance
|
|
if 'quarterly_income' in yfinance_data and yfinance_data['quarterly_income']:
|
|
quarters = list(yfinance_data['quarterly_income'].keys())
|
|
if quarters:
|
|
latest_quarter = quarters[0]
|
|
yf_revenue = yfinance_data['quarterly_income'][latest_quarter].get('Total Revenue', 0)
|
|
print(f"YFinance Revenue: ${yf_revenue:,.2f}")
|
|
if oracle_revenue > 0:
|
|
diff_pct = ((oracle_revenue - yf_revenue) / yf_revenue) * 100
|
|
print(f"Difference: {diff_pct:.2f}%")
|
|
|
|
print("\n--- Market Cap Comparison ---")
|
|
oracle_market_cap = latest_oracle.get('market_cap', 0)
|
|
yf_market_cap = yfinance_data.get('market_cap', 0)
|
|
print(f"Stock Oracle Market Cap: ${oracle_market_cap:,.2f}")
|
|
print(f"YFinance Market Cap: ${yf_market_cap:,.2f}")
|
|
if oracle_market_cap > 0 and yf_market_cap > 0:
|
|
diff_pct = ((oracle_market_cap - yf_market_cap) / yf_market_cap) * 100
|
|
print(f"Difference: {diff_pct:.2f}%")
|
|
|
|
print("\n--- P/E Ratio Comparison ---")
|
|
oracle_pe = latest_oracle.get('pe_ratio', 0)
|
|
yf_pe = yfinance_data['info'].get('trailingPE', 0)
|
|
print(f"Stock Oracle P/E: {oracle_pe:.2f}")
|
|
print(f"YFinance P/E: {yf_pe:.2f}")
|
|
if oracle_pe > 0 and yf_pe > 0:
|
|
diff_pct = ((oracle_pe - yf_pe) / yf_pe) * 100
|
|
print(f"Difference: {diff_pct:.2f}%")
|
|
|
|
print("\n--- Other Metrics from Stock Oracle ---")
|
|
print(f"EPS: ${latest_oracle.get('eps', 0):.2f}")
|
|
print(f"Total Assets: ${latest_oracle.get('total_assets', 0):,.2f}")
|
|
print(f"Total Equity: ${latest_oracle.get('total_equity', 0):,.2f}")
|
|
print(f"ROE: {latest_oracle.get('roe', 0):.2%}")
|
|
print(f"Net Margin: {latest_oracle.get('net_margin', 0):.2%}")
|
|
|
|
# Check if we have real yfinance quarterly data
|
|
if 'quarterly_income' in yfinance_data and yfinance_data['quarterly_income']:
|
|
print("\n--- Available YFinance Metrics ---")
|
|
quarters = list(yfinance_data['quarterly_income'].keys())
|
|
if quarters:
|
|
latest_quarter = quarters[0]
|
|
print(f"Latest YFinance Quarter: {latest_quarter}")
|
|
|
|
# Show some key metrics from yfinance
|
|
income_data = yfinance_data['quarterly_income'][latest_quarter]
|
|
for key in ['Total Revenue', 'Net Income', 'Operating Income', 'Gross Profit']:
|
|
if key in income_data:
|
|
print(f"{key}: ${income_data[key]:,.2f}")
|
|
|
|
def main():
|
|
"""Main comparison function"""
|
|
# Test with Apple
|
|
ticker = "AAPL"
|
|
start_date = "2024-01-01"
|
|
end_date = "2024-12-31"
|
|
|
|
print(f"Comparing financial data for {ticker}")
|
|
print("=" * 60)
|
|
|
|
# Get data from both sources
|
|
yfinance_data = get_yfinance_data(ticker)
|
|
oracle_data = get_stock_oracle_data(ticker, start_date, end_date)
|
|
|
|
# Compare the data
|
|
compare_financial_metrics(yfinance_data, oracle_data)
|
|
|
|
# Test with another ticker
|
|
print("\n" + "=" * 60)
|
|
ticker = "MSFT"
|
|
print(f"\nComparing financial data for {ticker}")
|
|
print("=" * 60)
|
|
|
|
yfinance_data = get_yfinance_data(ticker)
|
|
oracle_data = get_stock_oracle_data(ticker, start_date, end_date)
|
|
compare_financial_metrics(yfinance_data, oracle_data)
|
|
|
|
if __name__ == "__main__":
|
|
main() |