Spaces:
Running
Running
| """ | |
| Example usage of the Local Database system | |
| Demonstrates integration with all modules | |
| """ | |
| from datetime import datetime, timedelta | |
| from db.local_database import LocalDatabase, DatabaseEntry, DataType | |
| from db.adapters import ( | |
| CalendarAdapter, | |
| FundamentalAdapter, | |
| NewsAdapter, | |
| TechnicalAnalysisAdapter | |
| ) | |
| def example_calendar_scraper(): | |
| """Example: Save and retrieve calendar events""" | |
| print("\n" + "="*60) | |
| print("EXAMPLE 1: Calendar Scraper Integration") | |
| print("="*60) | |
| adapter = CalendarAdapter() | |
| today = datetime.now().date().isoformat() | |
| # Save earnings event | |
| print("\n📅 Saving earnings event for AAPL...") | |
| earnings_data = { | |
| 'company': 'Apple Inc.', | |
| 'time': 'After Market Close', | |
| 'eps_forecast': 1.54, | |
| 'last_year_eps': 1.46, | |
| 'revenue': '89.5B', | |
| 'market_cap': '2.8T' | |
| } | |
| success = adapter.save_earnings_event( | |
| date=today, | |
| ticker='AAPL', | |
| event_data=earnings_data, | |
| expiry_days=30 | |
| ) | |
| print(f"✓ Saved: {success}") | |
| # Save economic event | |
| print("\n🌍 Saving economic event...") | |
| economic_data = { | |
| 'country': 'United States', | |
| 'importance': 'high', | |
| 'event': 'Non-Farm Payrolls', | |
| 'actual': 199000, | |
| 'forecast': 180000, | |
| 'previous': 150000 | |
| } | |
| success = adapter.save_economic_event( | |
| date=today, | |
| event_data=economic_data, | |
| expiry_days=7 | |
| ) | |
| print(f"✓ Saved: {success}") | |
| # Retrieve earnings events | |
| print("\n📋 Retrieving AAPL earnings events...") | |
| events = adapter.get_earnings_events('AAPL') | |
| print(f"Found {len(events)} events") | |
| for event in events: | |
| print(f" Date: {event.date}, Company: {event.data.get('company')}") | |
| def example_fundamental_analysis(): | |
| """Example: Save and retrieve fundamental analysis""" | |
| print("\n" + "="*60) | |
| print("EXAMPLE 2: Fundamental Analysis Integration") | |
| print("="*60) | |
| adapter = FundamentalAdapter() | |
| today = datetime.now().date().isoformat() | |
| # Save financial metrics | |
| print("\n📊 Saving financial metrics for GOOGL...") | |
| metrics = { | |
| 'market_cap': 1850000000000, | |
| 'pe_ratio': 28.5, | |
| 'fcf_yield': 4.08, | |
| 'roic': 0.32, | |
| 'revenue_growth': 0.208, | |
| 'eps_growth': 0.25, | |
| 'net_margin': 0.23, | |
| 'roe': 0.28 | |
| } | |
| success = adapter.save_financial_metrics( | |
| date=today, | |
| ticker='GOOGL', | |
| metrics=metrics, | |
| expiry_days=1 | |
| ) | |
| print(f"✓ Saved: {success}") | |
| # Save investment decision | |
| print("\n🎯 Saving investment decision for GOOGL...") | |
| decision = { | |
| 'recommendation': 'BUY', | |
| 'final_score': 0.67, | |
| 'confidence': 1.0, | |
| 'reasoning': [ | |
| 'Strong FCF yield of 4.08%', | |
| 'Excellent ROIC of 32%', | |
| 'High revenue growth of 20.8%' | |
| ], | |
| 'key_metrics': { | |
| 'fcf_yield': 4.08, | |
| 'roic': 32.0, | |
| 'revenue_growth': 20.8 | |
| }, | |
| 'category_scores': { | |
| 'fcf_yield': 0.85, | |
| 'roic': 0.90, | |
| 'growth': 0.80 | |
| } | |
| } | |
| success = adapter.save_investment_decision( | |
| date=today, | |
| ticker='GOOGL', | |
| decision=decision, | |
| expiry_days=1 | |
| ) | |
| print(f"✓ Saved: {success}") | |
| # Retrieve latest metrics | |
| print("\n📈 Retrieving latest metrics for GOOGL...") | |
| entry = adapter.get_financial_metrics('GOOGL') | |
| if entry: | |
| print(f" Date: {entry.date}") | |
| # Check if this is a metrics entry or decision entry | |
| if 'metrics' in entry.data: | |
| metrics_data = entry.data['metrics'] | |
| print(f" P/E Ratio: {metrics_data.get('pe_ratio')}") | |
| print(f" FCF Yield: {metrics_data.get('fcf_yield')}%") | |
| elif entry.data.get('analysis_type') == 'decision': | |
| print(f" Recommendation: {entry.data.get('recommendation')}") | |
| print(f" Score: {entry.data.get('score')}") | |
| else: | |
| print(f" Analysis Type: {entry.data.get('analysis_type', 'unknown')}") | |
| def example_news_scraper(): | |
| """Example: Save and retrieve news articles""" | |
| print("\n" + "="*60) | |
| print("EXAMPLE 3: News Scraper Integration") | |
| print("="*60) | |
| adapter = NewsAdapter() | |
| today = datetime.now().date().isoformat() | |
| # Save news article | |
| print("\n📰 Saving news article for TSLA...") | |
| article = { | |
| 'title': 'Tesla Announces Record Q4 Deliveries', | |
| 'content': 'Tesla reported record vehicle deliveries...', | |
| 'source': 'Bloomberg', | |
| 'url': 'https://example.com/article', | |
| 'author': 'John Doe' | |
| } | |
| success = adapter.save_news_article( | |
| date=today, | |
| ticker='TSLA', | |
| article=article, | |
| expiry_days=30 | |
| ) | |
| print(f"✓ Saved: {success}") | |
| # Save sentiment analysis | |
| print("\n😊 Saving sentiment analysis for TSLA...") | |
| sentiment = { | |
| 'model': 'finbert-tone', | |
| 'sentiment': 'positive', | |
| 'score': 0.85, | |
| 'confidence': 0.92, | |
| 'breakdown': { | |
| 'positive': 0.85, | |
| 'neutral': 0.10, | |
| 'negative': 0.05 | |
| } | |
| } | |
| success = adapter.save_sentiment_analysis( | |
| date=today, | |
| ticker='TSLA', | |
| sentiment=sentiment, | |
| expiry_days=7 | |
| ) | |
| print(f"✓ Saved: {success}") | |
| # Retrieve news articles | |
| print("\n📋 Retrieving TSLA news articles...") | |
| articles = adapter.get_news_articles('TSLA') | |
| print(f"Found {len(articles)} articles") | |
| for article in articles: | |
| print(f" Title: {article.data.get('title')}") | |
| print(f" Source: {article.data.get('source')}") | |
| def example_technical_analysis(): | |
| """Example: Save and retrieve technical analysis""" | |
| print("\n" + "="*60) | |
| print("EXAMPLE 4: Technical Analysis Integration") | |
| print("="*60) | |
| adapter = TechnicalAnalysisAdapter() | |
| today = datetime.now().date().isoformat() | |
| # Save technical indicators | |
| print("\n📉 Saving technical indicators for NVDA...") | |
| indicators = { | |
| 'rsi': 65.5, | |
| 'macd': 12.3, | |
| 'macd_signal': 10.8, | |
| 'sma_50': 450.25, | |
| 'sma_200': 420.80, | |
| 'bollinger_upper': 480.00, | |
| 'bollinger_lower': 430.00, | |
| 'volume': 45000000 | |
| } | |
| success = adapter.save_technical_indicators( | |
| date=today, | |
| ticker='NVDA', | |
| indicators=indicators, | |
| expiry_days=1 | |
| ) | |
| print(f"✓ Saved: {success}") | |
| # Save trading signal | |
| print("\n🚦 Saving trading signal for NVDA...") | |
| signal = { | |
| 'signal_type': 'BUY', | |
| 'strength': 0.75, | |
| 'triggers': ['RSI oversold', 'MACD crossover'], | |
| 'entry_price': 455.00, | |
| 'stop_loss': 440.00, | |
| 'take_profit': 480.00 | |
| } | |
| success = adapter.save_trading_signal( | |
| date=today, | |
| ticker='NVDA', | |
| signal=signal, | |
| expiry_days=1 | |
| ) | |
| print(f"✓ Saved: {success}") | |
| # Retrieve technical indicators | |
| print("\n📊 Retrieving NVDA technical indicators...") | |
| indicators_list = adapter.get_technical_indicators('NVDA') | |
| print(f"Found {len(indicators_list)} indicator sets") | |
| for ind in indicators_list: | |
| print(f" RSI: {ind.data.get('rsi')}") | |
| print(f" MACD: {ind.data.get('macd')}") | |
| def example_batch_operations(): | |
| """Example: Batch save operations""" | |
| print("\n" + "="*60) | |
| print("EXAMPLE 5: Batch Operations") | |
| print("="*60) | |
| db = LocalDatabase() | |
| today = datetime.now().date().isoformat() | |
| # Create multiple entries | |
| print("\n💾 Batch saving multiple stock analyses...") | |
| entries = [] | |
| tickers = ['AAPL', 'GOOGL', 'MSFT', 'AMZN', 'NVDA'] | |
| for ticker in tickers: | |
| entry = DatabaseEntry( | |
| date=today, | |
| data_type=DataType.FINANCIAL_INFO.value, | |
| ticker=ticker, | |
| data={ | |
| 'analysis_type': 'quick_scan', | |
| 'price': 100.0 + len(ticker), # Dummy data | |
| 'volume': 1000000 * len(ticker) | |
| }, | |
| metadata={'batch_id': 'scan_001'} | |
| ) | |
| entries.append(entry) | |
| count = db.save_batch(entries, expiry_days=1) | |
| print(f"✓ Saved {count}/{len(entries)} entries") | |
| def example_query_operations(): | |
| """Example: Advanced queries""" | |
| print("\n" + "="*60) | |
| print("EXAMPLE 6: Query Operations") | |
| print("="*60) | |
| db = LocalDatabase() | |
| # Query by date range | |
| print("\n🔍 Querying all financial data from last 7 days...") | |
| date_from = (datetime.now() - timedelta(days=7)).date().isoformat() | |
| entries = db.query( | |
| data_type=DataType.FINANCIAL_INFO.value, | |
| date_from=date_from, | |
| limit=10 | |
| ) | |
| print(f"Found {len(entries)} entries:") | |
| for entry in entries[:5]: # Show first 5 | |
| print(f" {entry.date} - {entry.ticker} - {entry.data.get('analysis_type', 'N/A')}") | |
| # Query specific ticker | |
| print("\n🔍 Querying all data for AAPL...") | |
| aapl_entries = db.query(ticker='AAPL', limit=5) | |
| print(f"Found {len(aapl_entries)} AAPL entries") | |
| def example_database_stats(): | |
| """Example: Database statistics""" | |
| print("\n" + "="*60) | |
| print("EXAMPLE 7: Database Statistics") | |
| print("="*60) | |
| db = LocalDatabase() | |
| stats = db.get_stats() | |
| print(f"\n📊 Database Overview:") | |
| print(f" Total Entries: {stats.get('total_entries', 0):,}") | |
| print(f" Total Size: {stats.get('total_size_mb', 0)} MB") | |
| print(f" Expired Entries: {stats.get('expired_entries', 0)}") | |
| by_type = stats.get('by_type', {}) | |
| if by_type: | |
| print(f"\n📁 By Data Type:") | |
| for data_type, count in by_type.items(): | |
| print(f" {data_type}: {count:,}") | |
| def example_integration_workflow(): | |
| """Example: Complete workflow combining all modules""" | |
| print("\n" + "="*60) | |
| print("EXAMPLE 8: Complete Integration Workflow") | |
| print("="*60) | |
| ticker = 'AAPL' | |
| today = datetime.now().date().isoformat() | |
| # 1. Check calendar for upcoming events | |
| print(f"\n1️⃣ Checking calendar for {ticker}...") | |
| calendar_adapter = CalendarAdapter() | |
| earnings = calendar_adapter.get_earnings_events(ticker) | |
| print(f" Found {len(earnings)} upcoming earnings events") | |
| # 2. Save fundamental analysis | |
| print(f"\n2️⃣ Saving fundamental analysis for {ticker}...") | |
| fundamental_adapter = FundamentalAdapter() | |
| decision = { | |
| 'recommendation': 'HOLD', | |
| 'final_score': 0.31, | |
| 'confidence': 0.85, | |
| 'reasoning': ['Strong ROIC but low FCF yield'], | |
| 'key_metrics': {'roic': 73.8, 'fcf_yield': 2.36} | |
| } | |
| fundamental_adapter.save_investment_decision(today, ticker, decision) | |
| print(" ✓ Decision saved") | |
| # 3. Check news sentiment | |
| print(f"\n3️⃣ Saving news sentiment for {ticker}...") | |
| news_adapter = NewsAdapter() | |
| sentiment = { | |
| 'model': 'finbert-tone', | |
| 'sentiment': 'neutral', | |
| 'score': 0.55 | |
| } | |
| news_adapter.save_sentiment_analysis(today, ticker, sentiment) | |
| print(" ✓ Sentiment saved") | |
| # 4. Save technical signal | |
| print(f"\n4️⃣ Saving technical signal for {ticker}...") | |
| technical_adapter = TechnicalAnalysisAdapter() | |
| signal = { | |
| 'signal_type': 'HOLD', | |
| 'strength': 0.60, | |
| 'triggers': ['Neutral RSI', 'No clear pattern'] | |
| } | |
| technical_adapter.save_trading_signal(today, ticker, signal) | |
| print(" ✓ Signal saved") | |
| # 5. Comprehensive analysis | |
| print(f"\n5️⃣ Retrieving comprehensive analysis for {ticker}...") | |
| db = LocalDatabase() | |
| all_data = db.query(ticker=ticker, date_from=today) | |
| print(f"\n📊 Complete {ticker} Analysis ({today}):") | |
| print(f" Total data points: {len(all_data)}") | |
| for entry in all_data: | |
| data_type = entry.data_type | |
| if data_type == 'financial_info': | |
| rec = entry.data.get('recommendation', 'N/A') | |
| print(f" 💰 Fundamental: {rec}") | |
| elif data_type == 'news': | |
| sent = entry.data.get('sentiment', 'N/A') | |
| print(f" 📰 News Sentiment: {sent}") | |
| elif data_type == 'technical_analysis': | |
| sig = entry.data.get('signal_type', 'N/A') | |
| print(f" 📉 Technical Signal: {sig}") | |
| def run_all_examples(): | |
| """Run all examples""" | |
| print("\n" + "="*60) | |
| print("LOCAL DATABASE SYSTEM - EXAMPLE USAGE") | |
| print("="*60) | |
| try: | |
| example_calendar_scraper() | |
| example_fundamental_analysis() | |
| example_news_scraper() | |
| example_technical_analysis() | |
| example_batch_operations() | |
| example_query_operations() | |
| example_database_stats() | |
| example_integration_workflow() | |
| print("\n" + "="*60) | |
| print("✓ All examples completed successfully!") | |
| print("="*60 + "\n") | |
| except Exception as e: | |
| print(f"\n❌ Error running examples: {e}") | |
| import traceback | |
| traceback.print_exc() | |
| if __name__ == "__main__": | |
| run_all_examples() | |