#!/usr/bin/env python3
"""Quick test script for Stock Data MCP."""
import sys
import os
# Add parent directory to path
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from stock_data_mcp.providers.yahoo_provider import YahooProvider
from stock_data_mcp.providers.finnhub_provider import FinnhubProvider
from stock_data_mcp.util import ProviderError
def print_section(title: str):
"""Print a section header."""
print(f"\n{'=' * 70}")
print(f" {title}")
print('=' * 70)
def test_yahoo_quote():
"""Test Yahoo quote fetching."""
print_section("Testing Yahoo Provider - Quote")
provider = YahooProvider()
symbols = ["AAPL", "0700.HK"]
for symbol in symbols:
try:
print(f"\nGetting quote for {symbol}...")
quote = provider.get_quote(symbol)
print(f" ✓ Symbol: {quote.symbol}")
print(f" ✓ Price: {quote.price} {quote.currency}")
if quote.change:
print(f" ✓ Change: {quote.change:.2f} ({quote.change_pct:.2f}%)")
print(f" ✓ Source: {quote.source}")
return True
except ProviderError as e:
print(f" ✗ Error: {e.message}")
return False
def test_yahoo_history():
"""Test Yahoo historical data."""
print_section("Testing Yahoo Provider - History")
provider = YahooProvider()
try:
symbol = "AAPL"
start = "2024-01-02"
end = "2024-01-05"
print(f"Getting history for {symbol} from {start} to {end}...")
records = provider.get_history(symbol, start, end, "1d")
print(f" ✓ Found {len(records)} record(s)")
for record in records[:3]:
print(f" {record.date}: Close={record.close:.2f}, Volume={record.volume:,}")
return True
except ProviderError as e:
print(f" ✗ Error: {e.message}")
return False
def test_finnhub_fundamentals():
"""Test Finnhub fundamentals (if API key available)."""
print_section("Testing Finnhub Provider - Fundamentals")
try:
provider = FinnhubProvider()
except ProviderError as e:
print(f" ⊘ Skipped: {e.message}")
print(" → Set FINNHUB_API_KEY environment variable to test")
return None # Skip, not a failure
try:
symbol = "AAPL"
print(f"Getting fundamentals for {symbol}...")
fundamentals = provider.get_fundamentals(symbol)
print(f" ✓ Symbol: {fundamentals.symbol}")
print(f" ✓ Market Cap: {fundamentals.market_cap}")
print(f" ✓ PE Ratio: {fundamentals.pe}")
print(f" ✓ ROE: {fundamentals.roe}")
print(f" ✓ Source: {fundamentals.source}")
return True
except ProviderError as e:
print(f" ✗ Error: {e.message}")
return False
def test_finnhub_statements():
"""Test Finnhub financial statements (if API key available)."""
print_section("Testing Finnhub Provider - Financial Statements")
try:
provider = FinnhubProvider()
except ProviderError as e:
print(f" ⊘ Skipped: {e.message}")
return None # Skip, not a failure
try:
symbol = "AAPL"
print(f"Getting income statement for {symbol}...")
statements = provider.get_financial_statements(symbol, "income", "annual")
print(f" ✓ Symbol: {statements.symbol}")
print(f" ✓ Statement: {statements.statement}")
print(f" ✓ Period: {statements.period}")
print(f" ✓ Found {len(statements.items)} period(s)")
if statements.items:
item = statements.items[0]
print(f" Latest: {item.period_end}")
print(f" Revenue: {item.revenue}")
print(f" Net Income: {item.net_income}")
return True
except ProviderError as e:
print(f" ✗ Error: {e.message}")
return False
def main():
"""Run all tests."""
print("\n" + "=" * 70)
print(" Stock Data MCP Quick Test")
print("=" * 70)
tests = [
("Yahoo Quote", test_yahoo_quote),
("Yahoo History", test_yahoo_history),
("Finnhub Fundamentals", test_finnhub_fundamentals),
("Finnhub Statements", test_finnhub_statements),
]
results = []
for name, test_func in tests:
try:
success = test_func()
results.append((name, success))
except Exception as e:
print(f"\n⚠ Unexpected error in {name}: {e}")
results.append((name, False))
# Summary
print_section("Test Summary")
passed = sum(1 for _, success in results if success is True)
failed = sum(1 for _, success in results if success is False)
skipped = sum(1 for _, success in results if success is None)
total = len(results)
for name, success in results:
if success is True:
status = "✓ PASS"
elif success is False:
status = "✗ FAIL"
else:
status = "⊘ SKIP"
print(f" {status}: {name}")
print(f"\nPassed: {passed}/{total - skipped}")
if skipped > 0:
print(f"Skipped: {skipped}/{total} (Set FINNHUB_API_KEY to enable)")
if failed == 0:
print("\n✓ All required tests passed!")
return 0
else:
print(f"\n✗ {failed} test(s) failed")
return 1
if __name__ == "__main__":
sys.exit(main())