Spaces:
Running
Running
File size: 13,326 Bytes
3fe0726 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 |
"""
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()
|