reaperdoesntknow commited on
Commit
b8e2abb
·
verified ·
1 Parent(s): ca36d55

Create app.pu

Browse files
Files changed (1) hide show
  1. app.pu +2100 -0
app.pu ADDED
@@ -0,0 +1,2100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict, Any, List, Tuple
2
+ import streamlit as st
3
+ import yfinance as yf
4
+ import pandas as pd
5
+ import plotly.graph_objects as go
6
+ import plotly.express as px
7
+ from datetime import datetime, timedelta
8
+ from newsapi.newsapi_client import NewsApiClient
9
+ import requests
10
+ import os
11
+ import sqlite3
12
+ from sqlite3 import Error
13
+ import json
14
+ import openai
15
+ from prophet import Prophet
16
+ from prophet.plot import plot_plotly
17
+ from sklearn.preprocessing import StandardScaler, MinMaxScaler
18
+ import asyncio
19
+ import aiohttp
20
+ from functools import partial
21
+ import torch
22
+ import torch.nn as nn
23
+ import torch.nn.functional as F
24
+ import torch.optim as optim
25
+ from torch_geometric.nn import GCNConv
26
+ from torch_geometric.data import Data
27
+ import skfuzzy as fuzz
28
+ import skfuzzy.control as ctrl
29
+ import numpy as np
30
+ import networkx as nx
31
+ import random
32
+ import matplotlib.pyplot as plt
33
+ from streamlit_autorefresh import st_autorefresh
34
+ import cvxpy as cp # For portfolio optimization
35
+ from sklearn.ensemble import IsolationForest # For anomaly detection
36
+
37
+ # ----------------------------
38
+ # Configuration and Constants
39
+ # ----------------------------
40
+
41
+ # Load environment variables
42
+ OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
43
+ FMP_API_KEY = os.getenv("FMP_API_KEY")
44
+ NEWS_API_KEY = os.getenv("NEWS_API_KEY")
45
+
46
+ if not OPENAI_API_KEY or not FMP_API_KEY or not NEWS_API_KEY:
47
+ st.error(
48
+ "API keys for OpenAI, Financial Modeling Prep, and NewsAPI are not set. Please set them in the `.streamlit/secrets.toml` file."
49
+ )
50
+ st.stop()
51
+
52
+ # Initialize OpenAI
53
+ openai.api_key = OPENAI_API_KEY
54
+
55
+ # Initialize NewsApiClient
56
+ newsapi = NewsApiClient(api_key=NEWS_API_KEY)
57
+
58
+ # Database Configuration
59
+ DATABASE = "stock_dashboard.db"
60
+
61
+ # ----------------------------
62
+ # API Rate Limits Configuration
63
+ # ----------------------------
64
+
65
+ # Define API rate limits (example limits; adjust based on your subscription)
66
+ API_RATE_LIMITS = {
67
+ "FMP": {
68
+ "max_requests_per_day": 500,
69
+ "current_count": 0,
70
+ "last_reset": datetime.utcnow().date()
71
+ },
72
+ "NewsAPI": {
73
+ "max_requests_per_day": 500,
74
+ "current_count": 0,
75
+ "last_reset": datetime.utcnow().date()
76
+ },
77
+ "OpenAI": {
78
+ "max_requests_per_day": 1000,
79
+ "current_count": 0,
80
+ "last_reset": datetime.utcnow().date()
81
+ }
82
+ }
83
+
84
+ # ----------------------------
85
+ # Helper Functions
86
+ # ----------------------------
87
+
88
+ def local_css():
89
+ """Injects custom CSS for enhanced styling."""
90
+ st.markdown(
91
+ """
92
+ <style>
93
+ /* Sidebar Styling */
94
+ .css-1d391kg {
95
+ background-color: #f0f2f6;
96
+ }
97
+ /* Header Styling */
98
+ .title {
99
+ font-size: 3rem;
100
+ text-align: center;
101
+ color: #2e86de;
102
+ margin-bottom: 0;
103
+ }
104
+ .description {
105
+ text-align: center;
106
+ color: #555555;
107
+ margin-top: 0;
108
+ margin-bottom: 2rem;
109
+ font-size: 1.2rem;
110
+ }
111
+ /* DataFrame Styling */
112
+ .dataframe th, .dataframe td {
113
+ text-align: center;
114
+ padding: 10px;
115
+ }
116
+ /* Footer Styling */
117
+ .footer {
118
+ text-align: center;
119
+ color: #888888;
120
+ margin-top: 3rem;
121
+ font-size: 0.9rem;
122
+ }
123
+ /* Dark Mode Styling */
124
+ .dark-mode {
125
+ background-color: #1e1e1e;
126
+ color: #ffffff;
127
+ }
128
+ /* Chat Interface Styling */
129
+ .chat-container {
130
+ max-height: 500px;
131
+ overflow-y: auto;
132
+ padding: 10px;
133
+ border: 1px solid #ccc;
134
+ border-radius: 5px;
135
+ background-color: #f9f9f9;
136
+ margin-bottom: 1rem;
137
+ }
138
+ .user-message {
139
+ text-align: right;
140
+ margin: 5px 0;
141
+ color: #2e86de;
142
+ }
143
+ .assistant-message {
144
+ text-align: left;
145
+ margin: 5px 0;
146
+ color: #e74c3c;
147
+ }
148
+ /* Tooltip Styling */
149
+ .tooltip {
150
+ position: relative;
151
+ display: inline-block;
152
+ border-bottom: 1px dotted black;
153
+ }
154
+
155
+ .tooltip .tooltiptext {
156
+ visibility: hidden;
157
+ width: 220px;
158
+ background-color: #555;
159
+ color: #fff;
160
+ text-align: left;
161
+ border-radius: 6px;
162
+ padding: 5px;
163
+ position: absolute;
164
+ z-index: 1;
165
+ bottom: 125%; /* Position above */
166
+ left: 50%;
167
+ margin-left: -110px;
168
+ opacity: 0;
169
+ transition: opacity 0.3s;
170
+ }
171
+
172
+ .tooltip:hover .tooltiptext {
173
+ visibility: visible;
174
+ opacity: 1;
175
+ }
176
+
177
+ /* Button Styling */
178
+ .css-1aumxhk {
179
+ background-color: #2e86de;
180
+ color: white;
181
+ }
182
+ </style>
183
+ """,
184
+ unsafe_allow_html=True,
185
+ )
186
+
187
+ def initialize_database():
188
+ """
189
+ Initializes the SQLite database and creates necessary tables if they don't exist.
190
+ """
191
+ try:
192
+ conn = sqlite3.connect(DATABASE)
193
+ cursor = conn.cursor()
194
+ # Create interactions table
195
+ cursor.execute("""
196
+ CREATE TABLE IF NOT EXISTS interactions (
197
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
198
+ timestamp TEXT NOT NULL,
199
+ user_input TEXT NOT NULL,
200
+ assistant_response TEXT NOT NULL
201
+ )
202
+ """)
203
+ # Create stock_cache table
204
+ cursor.execute("""
205
+ CREATE TABLE IF NOT EXISTS stock_cache (
206
+ ticker TEXT PRIMARY KEY,
207
+ fetched_at TEXT NOT NULL,
208
+ data TEXT NOT NULL
209
+ )
210
+ """)
211
+ # Create portfolio table
212
+ cursor.execute("""
213
+ CREATE TABLE IF NOT EXISTS portfolio (
214
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
215
+ ticker TEXT NOT NULL,
216
+ added_at TEXT NOT NULL
217
+ )
218
+ """)
219
+ # Create api_usage table
220
+ cursor.execute("""
221
+ CREATE TABLE IF NOT EXISTS api_usage (
222
+ api_name TEXT PRIMARY KEY,
223
+ request_count INTEGER NOT NULL,
224
+ last_reset TEXT NOT NULL
225
+ )
226
+ """)
227
+ # Initialize api_usage records if they don't exist
228
+ for api in API_RATE_LIMITS.keys():
229
+ cursor.execute("""
230
+ INSERT OR IGNORE INTO api_usage (api_name, request_count, last_reset)
231
+ VALUES (?, ?, ?)
232
+ """, (api, 0, datetime.utcnow().date().isoformat()))
233
+ conn.commit()
234
+ conn.close()
235
+ except Error as e:
236
+ st.error(f"Error initializing database: {e}")
237
+ st.stop()
238
+
239
+ def insert_interaction(user_input, assistant_response):
240
+ """
241
+ Inserts a user interaction into the interactions table.
242
+ """
243
+ try:
244
+ conn = sqlite3.connect(DATABASE)
245
+ cursor = conn.cursor()
246
+ cursor.execute("""
247
+ INSERT INTO interactions (timestamp, user_input, assistant_response)
248
+ VALUES (?, ?, ?)
249
+ """, (datetime.utcnow().isoformat(), user_input, assistant_response))
250
+ conn.commit()
251
+ conn.close()
252
+ except Error as e:
253
+ st.error(f"Error inserting interaction: {e}")
254
+
255
+ def fetch_interactions(limit=50):
256
+ """
257
+ Fetches the most recent user interactions.
258
+ """
259
+ try:
260
+ conn = sqlite3.connect(DATABASE)
261
+ cursor = conn.cursor()
262
+ cursor.execute("""
263
+ SELECT timestamp, user_input, assistant_response
264
+ FROM interactions
265
+ ORDER BY id DESC
266
+ LIMIT ?
267
+ """, (limit,))
268
+ rows = cursor.fetchall()
269
+ conn.close()
270
+ return rows
271
+ except Error as e:
272
+ st.error(f"Error fetching interactions: {e}")
273
+ return []
274
+
275
+ def clear_interactions():
276
+ """
277
+ Clears all records from the interactions table.
278
+ """
279
+ try:
280
+ conn = sqlite3.connect(DATABASE)
281
+ cursor = conn.cursor()
282
+ cursor.execute("DELETE FROM interactions")
283
+ conn.commit()
284
+ conn.close()
285
+ st.success("All interactions have been cleared.")
286
+ except Error as e:
287
+ st.error(f"Error clearing interactions: {e}")
288
+
289
+ def insert_stock_cache(ticker, data):
290
+ """
291
+ Inserts or updates stock data in the stock_cache table.
292
+ """
293
+ try:
294
+ conn = sqlite3.connect(DATABASE)
295
+ cursor = conn.cursor()
296
+ cursor.execute("""
297
+ INSERT INTO stock_cache (ticker, fetched_at, data)
298
+ VALUES (?, ?, ?)
299
+ ON CONFLICT(ticker) DO UPDATE SET
300
+ fetched_at=excluded.fetched_at,
301
+ data=excluded.data
302
+ """, (ticker.upper(), datetime.utcnow().isoformat(), json.dumps(data, default=str)))
303
+ conn.commit()
304
+ conn.close()
305
+ except Error as e:
306
+ st.error(f"Error inserting stock cache: {e}")
307
+
308
+ def fetch_stock_cache(ticker):
309
+ """
310
+ Fetches cached stock data for a given ticker.
311
+ """
312
+ try:
313
+ conn = sqlite3.connect(DATABASE)
314
+ cursor = conn.cursor()
315
+ cursor.execute("""
316
+ SELECT fetched_at, data
317
+ FROM stock_cache
318
+ WHERE ticker = ?
319
+ """, (ticker.upper(),))
320
+ row = cursor.fetchone()
321
+ conn.close()
322
+ if row:
323
+ fetched_at, data = row
324
+ return json.loads(data), fetched_at
325
+ return None, None
326
+ except Error as e:
327
+ st.error(f"Error fetching stock cache: {e}")
328
+ return None, None
329
+
330
+ def clear_stock_cache():
331
+ """
332
+ Clears all records from the stock_cache table.
333
+ """
334
+ try:
335
+ conn = sqlite3.connect(DATABASE)
336
+ cursor = conn.cursor()
337
+ cursor.execute("DELETE FROM stock_cache")
338
+ conn.commit()
339
+ conn.close()
340
+ st.success("All cached stock data has been cleared.")
341
+ except Error as e:
342
+ st.error(f"Error clearing stock cache: {e}")
343
+
344
+ def add_to_portfolio(ticker):
345
+ """
346
+ Adds a ticker to the user's portfolio.
347
+ """
348
+ try:
349
+ conn = sqlite3.connect(DATABASE)
350
+ cursor = conn.cursor()
351
+ cursor.execute("""
352
+ INSERT INTO portfolio (ticker, added_at)
353
+ VALUES (?, ?)
354
+ """, (ticker.upper(), datetime.utcnow().isoformat()))
355
+ conn.commit()
356
+ conn.close()
357
+ st.success(f"{ticker.upper()} has been added to your portfolio.")
358
+ except Error as e:
359
+ st.error(f"Error adding to portfolio: {e}")
360
+
361
+ def remove_from_portfolio(ticker):
362
+ """
363
+ Removes a ticker from the user's portfolio.
364
+ """
365
+ try:
366
+ conn = sqlite3.connect(DATABASE)
367
+ cursor = conn.cursor()
368
+ cursor.execute("""
369
+ DELETE FROM portfolio
370
+ WHERE ticker = ?
371
+ """, (ticker.upper(),))
372
+ conn.commit()
373
+ conn.close()
374
+ st.success(f"{ticker.upper()} has been removed from your portfolio.")
375
+ except Error as e:
376
+ st.error(f"Error removing from portfolio: {e}")
377
+
378
+ def fetch_portfolio():
379
+ """
380
+ Fetches the user's portfolio.
381
+ """
382
+ try:
383
+ conn = sqlite3.connect(DATABASE)
384
+ cursor = conn.cursor()
385
+ cursor.execute("""
386
+ SELECT ticker
387
+ FROM portfolio
388
+ """)
389
+ rows = cursor.fetchall()
390
+ conn.close()
391
+ return [row[0] for row in rows]
392
+ except Error as e:
393
+ st.error(f"Error fetching portfolio: {e}")
394
+ return []
395
+
396
+ def update_api_usage(api_name):
397
+ """
398
+ Increments the API usage count for the specified API and checks rate limits.
399
+ Returns True if the API call is allowed, False otherwise.
400
+ """
401
+ try:
402
+ conn = sqlite3.connect(DATABASE)
403
+ cursor = conn.cursor()
404
+ cursor.execute("""
405
+ SELECT request_count, last_reset
406
+ FROM api_usage
407
+ WHERE api_name = ?
408
+ """, (api_name,))
409
+ row = cursor.fetchone()
410
+ if row:
411
+ request_count, last_reset = row
412
+ last_reset_date = datetime.fromisoformat(last_reset).date()
413
+ today = datetime.utcnow().date()
414
+ if last_reset_date < today:
415
+ # Reset the count
416
+ cursor.execute("""
417
+ UPDATE api_usage
418
+ SET request_count = 1, last_reset = ?
419
+ WHERE api_name = ?
420
+ """, (today.isoformat(), api_name))
421
+ conn.commit()
422
+ conn.close()
423
+ API_RATE_LIMITS[api_name]["current_count"] = 1
424
+ API_RATE_LIMITS[api_name]["last_reset"] = today
425
+ return True
426
+ else:
427
+ if request_count < API_RATE_LIMITS[api_name]["max_requests_per_day"]:
428
+ # Increment the count
429
+ cursor.execute("""
430
+ UPDATE api_usage
431
+ SET request_count = request_count + 1
432
+ WHERE api_name = ?
433
+ """, (api_name,))
434
+ conn.commit()
435
+ conn.close()
436
+ API_RATE_LIMITS[api_name]["current_count"] += 1
437
+ return True
438
+ else:
439
+ # Rate limit exceeded
440
+ conn.close()
441
+ st.warning(f"{api_name} API rate limit exceeded for today.")
442
+ return False
443
+ else:
444
+ # API not found in usage table
445
+ conn.close()
446
+ st.error(f"API usage record for {api_name} not found.")
447
+ return False
448
+ except Error as e:
449
+ st.error(f"Error updating API usage: {e}")
450
+ return False
451
+
452
+ async def fetch_single_stock_data(session, ticker):
453
+ """
454
+ Asynchronously fetches stock data for a single ticker, respecting API rate limits.
455
+ """
456
+ if not update_api_usage("FMP"):
457
+ st.warning(f"Financial Modeling Prep API rate limit exceeded. Skipping {ticker.upper()}.")
458
+ return ticker, {}
459
+ cached_data, fetched_at = fetch_stock_cache(ticker)
460
+ if cached_data:
461
+ return ticker, cached_data
462
+ else:
463
+ try:
464
+ stock = yf.Ticker(ticker)
465
+ info = stock.info
466
+ insert_stock_cache(ticker, info)
467
+ return ticker, info
468
+ except Exception as e:
469
+ st.error(f"Error fetching data for {ticker}: {e}")
470
+ return ticker, {}
471
+
472
+ async def fetch_all_stock_data(tickers):
473
+ """
474
+ Asynchronously fetches stock data for all tickers.
475
+ """
476
+ async with aiohttp.ClientSession() as session:
477
+ tasks = []
478
+ for ticker in tickers:
479
+ task = asyncio.ensure_future(fetch_single_stock_data(session, ticker))
480
+ tasks.append(task)
481
+ responses = await asyncio.gather(*tasks)
482
+ return responses
483
+
484
+ # -----------------------------
485
+ # Fuzzy Logic for Mutation Rate
486
+ # -----------------------------
487
+
488
+ def prepare_graph(num_nodes=10):
489
+ """
490
+ Prepares a graph with edge weights.
491
+ """
492
+ graph = nx.complete_graph(num_nodes)
493
+ for u, v in graph.edges:
494
+ graph[u][v]['weight'] = random.randint(1, 100) # Assign random weights
495
+ return graph
496
+
497
+ def visualize_fuzzy_logic(controller):
498
+ """
499
+ Visualizes fuzzy membership functions.
500
+ """
501
+ x = np.arange(0, 1.01, 0.01)
502
+ fig, ax = plt.subplots(figsize=(8, 5))
503
+ ax.plot(x, fuzz.trapmf(x, [0, 0, 0.3, 0.5]), label="Low Uncertainty")
504
+ ax.plot(x, fuzz.trimf(x, [0.3, 0.5, 0.7]), label="Medium Uncertainty")
505
+ ax.plot(x, fuzz.trapmf(x, [0.5, 0.7, 1, 1]), label="High Uncertainty")
506
+ ax.legend()
507
+ ax.set_title("Fuzzy Membership Functions")
508
+ ax.set_xlabel("Uncertainty")
509
+ ax.set_ylabel("Membership Degree")
510
+ st.pyplot(fig)
511
+
512
+ class FuzzyMutationController:
513
+ def __init__(self):
514
+ # Define fuzzy variables
515
+ self.uncertainty = ctrl.Antecedent(np.arange(0, 1.01, 0.01), 'uncertainty')
516
+ self.mutation_rate = ctrl.Consequent(np.arange(0, 1.01, 0.01), 'mutation_rate')
517
+
518
+ # Define membership functions
519
+ self.uncertainty['low'] = fuzz.trapmf(self.uncertainty.universe, [0, 0, 0.3, 0.5])
520
+ self.uncertainty['medium'] = fuzz.trimf(self.uncertainty.universe, [0.3, 0.5, 0.7])
521
+ self.uncertainty['high'] = fuzz.trapmf(self.uncertainty.universe, [0.5, 0.7, 1, 1])
522
+
523
+ self.mutation_rate['low'] = fuzz.trapmf(self.mutation_rate.universe, [0, 0, 0.1, 0.3])
524
+ self.mutation_rate['medium'] = fuzz.trimf(self.mutation_rate.universe, [0.1, 0.3, 0.5])
525
+ self.mutation_rate['high'] = fuzz.trapmf(self.mutation_rate.universe, [0.3, 0.5, 1, 1])
526
+
527
+ # Define fuzzy rules
528
+ rule1 = ctrl.Rule(self.uncertainty['low'], self.mutation_rate['low'])
529
+ rule2 = ctrl.Rule(self.uncertainty['medium'], self.mutation_rate['medium'])
530
+ rule3 = ctrl.Rule(self.uncertainty['high'], self.mutation_rate['high'])
531
+
532
+ # Create control system and simulation
533
+ self.mutation_ctrl = ctrl.ControlSystem([rule1, rule2, rule3])
534
+ self.mutation_sim = ctrl.ControlSystemSimulation(self.mutation_ctrl)
535
+
536
+ def compute_mutation_rate(self, uncertainty_value):
537
+ # Ensure uncertainty_value is within [0, 1]
538
+ uncertainty_value = min(max(uncertainty_value, 0), 1)
539
+ self.mutation_sim.input['uncertainty'] = uncertainty_value
540
+ self.mutation_sim.compute()
541
+ mutation_rate = self.mutation_sim.output['mutation_rate']
542
+ # Ensure mutation_rate is within [0, 1]
543
+ mutation_rate = min(max(mutation_rate, 0), 1)
544
+ return mutation_rate
545
+
546
+ # -----------------------------
547
+ # Genetic Algorithm Definition
548
+ # -----------------------------
549
+
550
+ class GeneticAlgorithm:
551
+ def __init__(self, graph, fuzzy_controller, population_size=50, generations=100):
552
+ self.graph = graph
553
+ self.nodes = list(graph.nodes)
554
+ self.fuzzy_controller = fuzzy_controller
555
+ self.population_size = population_size
556
+ self.generations = generations
557
+
558
+ def fitness(self, path):
559
+ """
560
+ Calculates the fitness of a path.
561
+ """
562
+ score = 0
563
+ for i in range(len(path)):
564
+ u = path[i]
565
+ v = path[(i + 1) % len(path)] # Wrap around to the start
566
+ if self.graph.has_edge(u, v):
567
+ score += self.graph[u][v].get('weight', 0) # Use weight attribute
568
+ else:
569
+ score -= 1000 # Penalize missing edges heavily
570
+ return score
571
+
572
+ def run(self) -> Tuple[List[Any], List[float], List[float]]:
573
+ # Initialize random population of paths
574
+ population = [random.sample(self.nodes, len(self.nodes)) for _ in range(self.population_size)]
575
+ best_fitness_history = []
576
+ mutation_rate_history = []
577
+
578
+ for generation in range(self.generations):
579
+ # Evaluate fitness of the population
580
+ fitness_scores = [self.fitness(path) for path in population]
581
+
582
+ # Normalize fitness scores
583
+ fitness_array = np.array(fitness_scores)
584
+ fitness_mean = np.mean(fitness_array)
585
+ fitness_std = np.std(fitness_array)
586
+ uncertainty_value = fitness_std / (abs(fitness_mean) + 1e-6)
587
+ # Normalize uncertainty_value to [0, 1]
588
+ uncertainty_value = uncertainty_value / (uncertainty_value + 1)
589
+
590
+ # Compute mutation rate using fuzzy logic
591
+ mutation_rate = self.fuzzy_controller.compute_mutation_rate(uncertainty_value)
592
+
593
+ # Select top candidates (elitism)
594
+ sorted_population = [path for _, path in sorted(zip(fitness_scores, population), reverse=True)]
595
+ population = sorted_population[:self.population_size // 2]
596
+
597
+ # Generate new population through crossover and mutation
598
+ new_population = population.copy()
599
+ while len(new_population) < self.population_size:
600
+ parent1, parent2 = random.sample(population, 2)
601
+ child = self.crossover(parent1, parent2)
602
+ child = self.mutate(child, mutation_rate)
603
+ new_population.append(child)
604
+
605
+ population = new_population
606
+
607
+ # Record best fitness and mutation rate
608
+ best_fitness = max(fitness_scores)
609
+ best_fitness_history.append(best_fitness)
610
+ mutation_rate_history.append(mutation_rate)
611
+
612
+ # Update progress bar in Streamlit
613
+ if 'ga_progress' in st.session_state:
614
+ st.session_state.ga_progress.progress((generation + 1) / self.generations)
615
+ st.session_state.ga_status.text(f"Generation {generation + 1}/{self.generations}")
616
+ st.session_state.ga_chart.add_rows({"Best Fitness": best_fitness})
617
+
618
+ # Return the best path found
619
+ fitness_scores = [self.fitness(path) for path in population]
620
+ best_index = fitness_scores.index(max(fitness_scores))
621
+ best_path = population[best_index]
622
+ return best_path, best_fitness_history, mutation_rate_history
623
+
624
+ def crossover(self, parent1, parent2):
625
+ # Ordered Crossover (OX)
626
+ size = len(parent1)
627
+ start, end = sorted(random.sample(range(size), 2))
628
+ child = [None] * size
629
+
630
+ # Copy a slice from parent1 to child
631
+ child[start:end] = parent1[start:end]
632
+
633
+ # Fill the remaining positions with genes from parent2
634
+ ptr = end
635
+ for gene in parent2:
636
+ if gene not in child:
637
+ if ptr >= size:
638
+ ptr = 0
639
+ child[ptr] = gene
640
+ ptr += 1
641
+ return child
642
+
643
+ def mutate(self, individual, mutation_rate):
644
+ if random.random() < mutation_rate:
645
+ idx1, idx2 = random.sample(range(len(individual)), 2)
646
+ individual[idx1], individual[idx2] = individual[idx2], individual[idx1]
647
+ return individual
648
+
649
+ # ----------------------------
650
+ # AI Assistant Integration
651
+ # ----------------------------
652
+
653
+ class RealAgent:
654
+ """Main agent logic handling interactions with the OpenAI Assistant."""
655
+
656
+ def __init__(self):
657
+ self.agent_state = AgentState()
658
+
659
+ def process(self, user_input: str, selected_tickers: List[str], stock_df: pd.DataFrame,
660
+ historical_dfs: Dict[str, pd.DataFrame], news_articles: Dict[str, List[Dict[str, Any]]],
661
+ fsirdm_data: Dict[str, Any]) -> str:
662
+ """
663
+ Processes user input and generates a response using the AI Assistant.
664
+ """
665
+ # Retrieve conversation history for context
666
+ conversation_history = self.agent_state.get_conversation_history()
667
+
668
+ # Generate additional context from the data
669
+ additional_context = self.generate_additional_context(selected_tickers, stock_df, historical_dfs, news_articles, fsirdm_data)
670
+
671
+ # Generate response using OpenAI
672
+ response = generate_openai_response(conversation_history, user_input, additional_context)
673
+
674
+ # Store interaction
675
+ self.agent_state.store_interaction(user_input, response)
676
+ insert_interaction(user_input, response)
677
+ return response
678
+
679
+ def generate_additional_context(self, selected_tickers: List[str], stock_df: pd.DataFrame,
680
+ historical_dfs: Dict[str, pd.DataFrame], news_articles: Dict[str, List[Dict[str, Any]]],
681
+ fsirdm_data: Dict[str, Any]) -> str:
682
+ """
683
+ Generates a concise summary of the selected stocks' data, historical data, news, and FSIRDM analysis to provide context to the assistant.
684
+ """
685
+ try:
686
+ # Get stock data
687
+ stock_data = stock_df[stock_df['Ticker'].isin(selected_tickers)].to_dict(orient='records')
688
+
689
+ # Get historical data metrics
690
+ historical_metrics: Dict[str, Any] = {}
691
+ for ticker in selected_tickers:
692
+ hist_df = historical_dfs.get(ticker, pd.DataFrame())
693
+ if not hist_df.empty:
694
+ metrics = {
695
+ "Latest Close": hist_df['Close'].iloc[-1],
696
+ "52 Week High": hist_df['Close'].max(),
697
+ "52 Week Low": hist_df['Close'].min(),
698
+ "SMA 20": hist_df['SMA_20'].iloc[-1],
699
+ "EMA 20": hist_df['EMA_20'].iloc[-1],
700
+ "Volatility (Std Dev)": hist_df['Close'].std(),
701
+ "RSI": hist_df['RSI'].iloc[-1]
702
+ }
703
+ else:
704
+ metrics = "No historical data available."
705
+ historical_metrics[ticker] = metrics
706
+
707
+ # Get FSIRDM analysis
708
+ fsirdm_summary = fsirdm_data
709
+
710
+ # Get latest news headlines
711
+ news_summary: Dict[str, Any] = {}
712
+ if news_articles and isinstance(news_articles, dict):
713
+ for ticker, articles in news_articles.items():
714
+ if articles and isinstance(articles, list):
715
+ news_summary[ticker] = [
716
+ {
717
+ "Title": article['Title'],
718
+ "Description": article['Description'],
719
+ "URL": article['URL'],
720
+ "Published At": article['Published At']
721
+ }
722
+ for article in articles
723
+ ]
724
+ else:
725
+ news_summary[ticker] = "No recent news articles found."
726
+ else:
727
+ news_summary = "No recent news articles found."
728
+
729
+ # Combine all summaries into a structured JSON format
730
+ additional_context = {
731
+ "Stock Data": stock_data,
732
+ "Historical Metrics": historical_metrics,
733
+ "FSIRDM Analysis": fsirdm_summary,
734
+ "Latest News": news_summary
735
+ }
736
+
737
+ # Convert to JSON string with proper date formatting
738
+ additional_context_json = json.dumps(additional_context, default=str, indent=4)
739
+
740
+ # Truncate if necessary to stay within token limits
741
+ max_length = 32000 # Adjust based on token count estimates
742
+ if len(additional_context_json) > max_length:
743
+ additional_context_json = additional_context_json[:max_length] + "..."
744
+
745
+ return additional_context_json
746
+ except Exception as e:
747
+ st.error(f"Error generating additional context: {e}")
748
+ return ""
749
+
750
+ class AgentState:
751
+ """Manages the agent's memory and state."""
752
+
753
+ def __init__(self):
754
+ self.short_term_memory: List[Dict[str, str]] = self.load_memory()
755
+
756
+ def load_memory(self) -> List[Dict[str, str]]:
757
+ """
758
+ Loads recent interactions from the database to provide context.
759
+ """
760
+ interactions = fetch_interactions(limit=50)
761
+ memory: List[Dict[str, str]] = []
762
+ for interaction in reversed(interactions): # oldest first
763
+ timestamp, user_input, assistant_response = interaction
764
+ memory.append({
765
+ "user_input": user_input,
766
+ "assistant_response": assistant_response
767
+ })
768
+ return memory
769
+
770
+ def store_interaction(self, user_input: str, response: str) -> None:
771
+ """
772
+ Stores a new interaction in the memory.
773
+ """
774
+ self.short_term_memory.append({"user_input": user_input, "assistant_response": response})
775
+ if len(self.short_term_memory) > 10:
776
+ self.short_term_memory.pop(0)
777
+
778
+ def get_conversation_history(self) -> List[Dict[str, str]]:
779
+ """
780
+ Returns the current conversation history.
781
+ """
782
+ return self.short_term_memory
783
+
784
+ def reset_memory(self) -> None:
785
+ """
786
+ Resets the short-term memory.
787
+ """
788
+ self.short_term_memory = []
789
+
790
+ def generate_openai_response(conversation_history: List[Dict[str, str]], user_input: str, additional_context: str) -> str:
791
+ """
792
+ Generates a response from OpenAI's GPT-4 model based on the conversation history, user input, and additional context.
793
+ """
794
+ try:
795
+ # Prepare the messages for the model
796
+ messages = [
797
+ {
798
+ "role": "system",
799
+ "content": (
800
+ "You are a financial AI assistant leveraging the FS-IRDM framework to analyze real-time stock data and news sentiment. "
801
+ "You compare multiple stocks, quantify uncertainties with fuzzy memberships, and classify stocks into high-growth, stable, and risky categories. "
802
+ "Utilize transformation matrices and continuous utility functions to optimize portfolio decisions while conserving expected utility. "
803
+ "Dynamically adapt through sensitivity analysis and stochastic modeling of market volatility, ensuring decision integrity with homeomorphic mappings. "
804
+ "Refine utility functions based on investor preferences and risk aversion, employ advanced non-linear optimization and probabilistic risk analysis, "
805
+ "and ensure secure data handling with fuzzy logic-enhanced memory compression and diffeomorphic encryption. Additionally, provide robust, explainable recommendations "
806
+ "and comprehensive reporting, maintaining consistency, adaptability, and efficiency in dynamic financial environments. "
807
+ "Use and learn from every single interaction to better tune your strategy and optimize the portfolio."
808
+ )
809
+ }
810
+ ]
811
+
812
+ # Add additional context (stock data, historical data, news, FSIRDM analysis)
813
+ if additional_context:
814
+ messages.append({"role": "system", "content": f"Here is the relevant data:\n{additional_context}"})
815
+
816
+ # Add past interactions
817
+ for interaction in conversation_history:
818
+ messages.append({"role": "user", "content": interaction['user_input']})
819
+ messages.append({"role": "assistant", "content": interaction['assistant_response']})
820
+
821
+ # Add the current user input
822
+ messages.append({"role": "user", "content": user_input})
823
+
824
+ # Call OpenAI API
825
+ response = openai.ChatCompletion.create(
826
+ model="gpt-4",
827
+ messages=messages,
828
+ max_tokens=1500, # Adjust based on requirements
829
+ n=1,
830
+ stop=None,
831
+ temperature=0.7,
832
+ )
833
+
834
+ assistant_response: str = response.choices[0].message['content'].strip()
835
+ return assistant_response
836
+ except Exception as e:
837
+ st.error(f"Error generating response from OpenAI: {e}")
838
+ return "I'm sorry, I couldn't process your request at the moment."
839
+
840
+ # ----------------------------
841
+ # Swarm of AI Agents Definitions
842
+ # ----------------------------
843
+
844
+ class DataAnalysisAgent:
845
+ """Agent responsible for in-depth data analysis."""
846
+
847
+ def analyze_market_trends(self, stock_df: pd.DataFrame) -> Dict[str, Any]:
848
+ """
849
+ Analyzes market trends based on current stock data.
850
+ """
851
+ try:
852
+ analysis = {}
853
+ # Example: Calculate average PE ratio
854
+ avg_pe = stock_df['PE Ratio'].mean()
855
+ analysis['Average PE Ratio'] = avg_pe
856
+
857
+ # Example: Identify top-performing sectors
858
+ sector_performance = stock_df.groupby('Sector')['Market Cap'].sum().reset_index()
859
+ top_sectors = sector_performance.sort_values(by='Market Cap', ascending=False).head(3)
860
+ analysis['Top Sectors by Market Cap'] = top_sectors.to_dict(orient='records')
861
+
862
+ # Add more sophisticated analyses as needed
863
+ return analysis
864
+ except Exception as e:
865
+ st.error(f"Error in Data Analysis Agent: {e}")
866
+ return {}
867
+
868
+ class PredictionAgent:
869
+ """Agent responsible for forecasting and predictions."""
870
+
871
+ def forecast_stock_trends(self, historical_dfs: Dict[str, pd.DataFrame], forecast_period: int = 90) -> Dict[str, Any]:
872
+ """
873
+ Forecasts future stock trends using Prophet.
874
+ """
875
+ try:
876
+ forecasts = {}
877
+ for ticker, hist_df in historical_dfs.items():
878
+ if hist_df.empty:
879
+ forecasts[ticker] = "No historical data available."
880
+ continue
881
+ model, forecast_df = forecast_stock_price(hist_df, forecast_period)
882
+ if model is not None and not forecast_df.empty:
883
+ forecasts[ticker] = forecast_df[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].tail(30).to_dict(orient='records')
884
+ else:
885
+ forecasts[ticker] = "Forecasting model could not generate predictions."
886
+ return forecasts
887
+ except Exception as e:
888
+ st.error(f"Error in Prediction Agent: {e}")
889
+ return {}
890
+
891
+ class SentimentAnalysisAgent:
892
+ """Agent responsible for analyzing news sentiment."""
893
+
894
+ def analyze_sentiment(self, news_articles: Dict[str, List[Dict[str, Any]]]) -> Dict[str, float]:
895
+ """
896
+ Analyzes sentiment of news articles using OpenAI's sentiment analysis.
897
+ Returns sentiment scores per ticker.
898
+ """
899
+ sentiment_scores = {}
900
+ try:
901
+ for ticker, articles in news_articles.items():
902
+ if not articles:
903
+ sentiment_scores[ticker] = 0.0 # Neutral sentiment
904
+ continue
905
+ sentiments = []
906
+ for article in articles:
907
+ prompt = f"Analyze the sentiment of the following news article and rate it from -1 (very negative) to 1 (very positive):\n\nTitle: {article['Title']}\nDescription: {article['Description']}"
908
+ sentiment = get_sentiment_from_openai(prompt)
909
+ sentiments.append(sentiment)
910
+ # Average sentiment score
911
+ if sentiments:
912
+ avg_sentiment = sum(sentiments) / len(sentiments)
913
+ sentiment_scores[ticker] = avg_sentiment
914
+ else:
915
+ sentiment_scores[ticker] = 0.0
916
+ return sentiment_scores
917
+ except Exception as e:
918
+ st.error(f"Error in Sentiment Analysis Agent: {e}")
919
+ return sentiment_scores
920
+
921
+ class AnomalyDetectionAgent:
922
+ """Agent responsible for detecting anomalies in stock data."""
923
+
924
+ def detect_anomalies(self, stock_df: pd.DataFrame, historical_dfs: Dict[str, pd.DataFrame]) -> Dict[str, List[str]]:
925
+ """
926
+ Detects anomalies in stock data using Isolation Forest.
927
+ Returns a dictionary with tickers as keys and list of anomaly dates as values.
928
+ """
929
+ anomalies = {}
930
+ try:
931
+ for ticker in stock_df['Ticker']:
932
+ hist_df = historical_dfs.get(ticker, pd.DataFrame())
933
+ if hist_df.empty:
934
+ anomalies[ticker] = ["No historical data available."]
935
+ continue
936
+ # Use Isolation Forest on Close prices
937
+ model = IsolationForest(contamination=0.05, random_state=42)
938
+ hist_df = hist_df.sort_values(by='Date')
939
+ hist_df['Close_Log'] = np.log(hist_df['Close'] + 1) # Log transform to stabilize variance
940
+ model.fit(hist_df[['Close_Log']])
941
+ hist_df['Anomaly'] = model.predict(hist_df[['Close_Log']])
942
+ anomaly_dates = hist_df[hist_df['Anomaly'] == -1]['Date'].tolist()
943
+ anomalies[ticker] = anomaly_dates if len(anomaly_dates) > 0 else ["No anomalies detected."]
944
+ return anomalies
945
+ except Exception as e:
946
+ st.error(f"Error in Anomaly Detection Agent: {e}")
947
+ return anomalies
948
+
949
+ class PortfolioOptimizationAgent:
950
+ """Agent responsible for optimizing the user's portfolio."""
951
+
952
+ def optimize_portfolio(self, stock_df: pd.DataFrame, historical_dfs: Dict[str, pd.DataFrame]) -> Dict[str, Any]:
953
+ """
954
+ Optimizes the portfolio using mean-variance optimization.
955
+ Returns the optimal weights for each stock.
956
+ """
957
+ try:
958
+ tickers = stock_df['Ticker'].tolist()
959
+ returns_data = []
960
+ valid_tickers = []
961
+
962
+ # Calculate daily returns for each ticker
963
+ for ticker in tickers:
964
+ hist_df = historical_dfs.get(ticker, pd.DataFrame())
965
+ if hist_df.empty or len(hist_df) < 2:
966
+ st.warning(f"Not enough historical data for {ticker} to calculate returns.")
967
+ continue
968
+ hist_df = hist_df.sort_values(by='Date')
969
+ hist_df['Return'] = hist_df['Close'].pct_change()
970
+ returns = hist_df['Return'].dropna()
971
+ returns_data.append(returns)
972
+ valid_tickers.append(ticker)
973
+
974
+ # Check if there are enough tickers to optimize
975
+ if len(valid_tickers) < 2:
976
+ st.error("Not enough tickers with sufficient historical data for portfolio optimization.")
977
+ return {"Optimal Weights": "Insufficient data."}
978
+
979
+ # Create a DataFrame of returns
980
+ returns_df = pd.concat(returns_data, axis=1, join='inner')
981
+ returns_df.columns = valid_tickers
982
+
983
+ # Calculate expected returns and covariance matrix
984
+ expected_returns = returns_df.mean() * 252 # Annualize
985
+ cov_matrix = returns_df.cov() * 252 # Annualize
986
+
987
+ # Check if covariance matrix is positive semi-definite
988
+ if not self.is_positive_semi_definite(cov_matrix.values):
989
+ st.error("Covariance matrix is not positive semi-definite. Adjusting...")
990
+ cov_matrix_values = self.nearest_positive_semi_definite(cov_matrix.values)
991
+ else:
992
+ cov_matrix_values = cov_matrix.values
993
+
994
+ n = len(valid_tickers)
995
+ weights = cp.Variable(n)
996
+ portfolio_return = expected_returns.values @ weights
997
+ portfolio_risk = cp.quad_form(weights, cov_matrix_values)
998
+ risk_aversion = 0.5 # Adjust based on preference
999
+
1000
+ # Define the optimization problem
1001
+ problem = cp.Problem(cp.Maximize(portfolio_return - risk_aversion * portfolio_risk),
1002
+ [cp.sum(weights) == 1, weights >= 0])
1003
+ problem.solve()
1004
+
1005
+ if weights.value is not None:
1006
+ optimal_weights = {ticker: round(weight, 4) for ticker, weight in zip(valid_tickers, weights.value)}
1007
+ return {"Optimal Weights": optimal_weights}
1008
+ else:
1009
+ return {"Optimal Weights": "Optimization failed."}
1010
+ except Exception as e:
1011
+ st.error(f"Error in Portfolio Optimization Agent: {e}")
1012
+ return {"Optimal Weights": "Optimization failed."}
1013
+
1014
+ def nearest_positive_semi_definite(self, A):
1015
+ """
1016
+ Finds the nearest positive semi-definite matrix to A.
1017
+ """
1018
+ try:
1019
+ B = (A + A.T) / 2
1020
+ _, s, V = np.linalg.svd(B)
1021
+ H = np.dot(V.T, np.dot(np.diag(s), V))
1022
+ A2 = (B + H) / 2
1023
+ A3 = (A2 + A2.T) / 2
1024
+
1025
+ if self.is_positive_semi_definite(A3):
1026
+ return A3
1027
+ else:
1028
+ return np.eye(A.shape[0]) # Fallback to identity matrix
1029
+ except Exception as e:
1030
+ st.error(f"Error in making matrix positive semi-definite: {e}")
1031
+ return np.eye(A.shape[0])
1032
+
1033
+ def is_positive_semi_definite(self, A):
1034
+ """
1035
+ Checks if matrix A is positive semi-definite.
1036
+ """
1037
+ try:
1038
+ return np.all(np.linalg.eigvals(A) >= -1e-10)
1039
+ except Exception as e:
1040
+ st.error(f"Error checking positive semi-definiteness: {e}")
1041
+ return False
1042
+
1043
+ class RealTimeAlertingAgent:
1044
+ """Agent responsible for real-time alerting based on stock data."""
1045
+
1046
+ def generate_alerts(self, stock_df: pd.DataFrame, sentiment_scores: Dict[str, float],
1047
+ anomaly_data: Dict[str, List[str]]) -> Dict[str, List[str]]:
1048
+ """
1049
+ Generates alerts based on specific conditions such as high volatility, negative sentiment, or detected anomalies.
1050
+ Returns a dictionary with tickers as keys and list of alerts as values.
1051
+ """
1052
+ alerts = {}
1053
+ try:
1054
+ for index, row in stock_df.iterrows():
1055
+ ticker = row['Ticker']
1056
+ alerts[ticker] = []
1057
+ # Example Alert 1: High PE Ratio
1058
+ if row['PE Ratio'] > 25:
1059
+ alerts[ticker].append("High PE Ratio detected.")
1060
+
1061
+ # Example Alert 2: Negative Sentiment
1062
+ sentiment = sentiment_scores.get(ticker, 0)
1063
+ if sentiment < -0.5:
1064
+ alerts[ticker].append("Negative sentiment in recent news.")
1065
+
1066
+ # Example Alert 3: Anomalies detected
1067
+ anomaly_dates = anomaly_data.get(ticker, [])
1068
+ if anomaly_dates and anomaly_dates != ["No anomalies detected."]:
1069
+ alerts[ticker].append(f"Anomalies detected on dates: {', '.join(map(str, anomaly_dates))}")
1070
+
1071
+ # Add more alert conditions as needed
1072
+ return alerts
1073
+ except Exception as e:
1074
+ st.error(f"Error in Real-Time Alerting Agent: {e}")
1075
+ return alerts
1076
+
1077
+ # Initialize agents
1078
+ if 'real_agent' not in st.session_state:
1079
+ st.session_state.real_agent = RealAgent()
1080
+
1081
+ if 'data_analysis_agent' not in st.session_state:
1082
+ st.session_state.data_analysis_agent = DataAnalysisAgent()
1083
+
1084
+ if 'prediction_agent' not in st.session_state:
1085
+ st.session_state.prediction_agent = PredictionAgent()
1086
+
1087
+ if 'sentiment_analysis_agent' not in st.session_state:
1088
+ st.session_state.sentiment_analysis_agent = SentimentAnalysisAgent()
1089
+
1090
+ if 'anomaly_detection_agent' not in st.session_state:
1091
+ st.session_state.anomaly_detection_agent = AnomalyDetectionAgent()
1092
+
1093
+ if 'portfolio_optimization_agent' not in st.session_state:
1094
+ st.session_state.portfolio_optimization_agent = PortfolioOptimizationAgent()
1095
+
1096
+ if 'real_time_alerting_agent' not in st.session_state:
1097
+ st.session_state.real_time_alerting_agent = RealTimeAlertingAgent()
1098
+
1099
+ # ----------------------------
1100
+ # AI Assistant Tools
1101
+ # ----------------------------
1102
+
1103
+ def get_sentiment_from_openai(prompt: str) -> float:
1104
+ """
1105
+ Uses OpenAI's GPT-4 to analyze sentiment and return a numerical score.
1106
+ """
1107
+ try:
1108
+ response = openai.ChatCompletion.create(
1109
+ model="gpt-4",
1110
+ messages=[
1111
+ {"role": "system", "content": "You are an assistant that analyzes the sentiment of news articles. Rate the sentiment from -1 (very negative) to 1 (very positive)."},
1112
+ {"role": "user", "content": prompt}
1113
+ ],
1114
+ max_tokens=10,
1115
+ temperature=0.0,
1116
+ )
1117
+ sentiment_text = response.choices[0].message['content'].strip()
1118
+ # Extract numerical value from response
1119
+ try:
1120
+ sentiment_score = float(sentiment_text)
1121
+ except ValueError:
1122
+ sentiment_score = 0.0 # Default to neutral if parsing fails
1123
+ # Clamp the score between -1 and 1
1124
+ sentiment_score = max(min(sentiment_score, 1.0), -1.0)
1125
+ return sentiment_score
1126
+ except Exception as e:
1127
+ st.error(f"Error in Sentiment Analysis: {e}")
1128
+ return 0.0
1129
+
1130
+ # ----------------------------
1131
+ # FSIRDM Framework Integration
1132
+ # ----------------------------
1133
+
1134
+ def generate_fsirdm_analysis(stock_df: pd.DataFrame, historical_dfs: Dict[str, pd.DataFrame],
1135
+ forecast_period: int) -> Dict[str, Any]:
1136
+ """
1137
+ Generates FSIRDM analysis based on stock data and historical data.
1138
+ Returns a dictionary summarizing the analysis.
1139
+ """
1140
+ try:
1141
+ # Example FSIRDM Analysis Components:
1142
+ # Fuzzy Set Membership for Risk
1143
+ risk_levels = {}
1144
+ for index, row in stock_df.iterrows():
1145
+ rsi = row['RSI']
1146
+ if rsi < 30:
1147
+ risk = "High Risk"
1148
+ elif 30 <= rsi <= 70:
1149
+ risk = "Moderate Risk"
1150
+ else:
1151
+ risk = "Low Risk"
1152
+ risk_levels[row['Ticker']] = risk
1153
+
1154
+ # Quantitative Analysis
1155
+ quantitative_analysis = {}
1156
+ for ticker in stock_df['Ticker']:
1157
+ hist_df = historical_dfs.get(ticker, pd.DataFrame())
1158
+ if not hist_df.empty:
1159
+ latest_close = hist_df['Close'].iloc[-1]
1160
+ sma = hist_df['SMA_20'].iloc[-1]
1161
+ ema = hist_df['EMA_20'].iloc[-1]
1162
+ volatility = hist_df['Close'].std()
1163
+ quantitative_analysis[ticker] = {
1164
+ "Latest Close": latest_close,
1165
+ "SMA 20": sma,
1166
+ "EMA 20": ema,
1167
+ "Volatility": volatility
1168
+ }
1169
+ else:
1170
+ quantitative_analysis[ticker] = "No historical data available."
1171
+
1172
+ # Risk Assessment
1173
+ risk_assessment = risk_levels
1174
+
1175
+ # Portfolio Optimization Suggestions
1176
+ optimization_suggestions = {}
1177
+ for ticker in stock_df['Ticker']:
1178
+ # Simple heuristic: If RSI < 30 and high volatility, suggest to hold or buy
1179
+ # If RSI > 70 and low volatility, suggest to sell
1180
+ if risk_assessment[ticker] == "High Risk" and quantitative_analysis[ticker] != "No historical data available.":
1181
+ optimization_suggestions[ticker] = "Consider holding or buying."
1182
+ elif risk_assessment[ticker] == "Low Risk" and quantitative_analysis[ticker] != "No historical data available.":
1183
+ optimization_suggestions[ticker] = "Consider selling or reducing position."
1184
+ else:
1185
+ optimization_suggestions[ticker] = "Hold current position."
1186
+
1187
+ # Combine all FSIRDM components
1188
+ fsirdm_summary = {
1189
+ "Risk Assessment": risk_assessment,
1190
+ "Quantitative Analysis": quantitative_analysis,
1191
+ "Optimization Suggestions": optimization_suggestions
1192
+ }
1193
+
1194
+ return fsirdm_summary
1195
+ except Exception as e:
1196
+ st.error(f"Error generating FSIRDM analysis: {e}")
1197
+ return {}
1198
+
1199
+ # ----------------------------
1200
+ # AI Orchestrator Definition
1201
+ # ----------------------------
1202
+
1203
+ class AIOrchestrator:
1204
+ """Orchestrates the swarm of AI agents to provide comprehensive insights."""
1205
+
1206
+ def __init__(self):
1207
+ self.data_analysis_agent = st.session_state.data_analysis_agent
1208
+ self.prediction_agent = st.session_state.prediction_agent
1209
+ self.sentiment_analysis_agent = st.session_state.sentiment_analysis_agent
1210
+ self.anomaly_detection_agent = st.session_state.anomaly_detection_agent
1211
+ self.portfolio_optimization_agent = st.session_state.portfolio_optimization_agent
1212
+ self.real_time_alerting_agent = st.session_state.real_time_alerting_agent
1213
+
1214
+ def generate_insights(self, stock_df: pd.DataFrame, historical_dfs: Dict[str, pd.DataFrame],
1215
+ news_articles: Dict[str, List[Dict[str, Any]]], forecast_period: int) -> Dict[str, Any]:
1216
+ """
1217
+ Runs all agents and aggregates their insights.
1218
+ """
1219
+ insights = {}
1220
+ # Data Analysis
1221
+ data_trends = self.data_analysis_agent.analyze_market_trends(stock_df)
1222
+ insights['Data Trends'] = data_trends
1223
+
1224
+ # Predictions
1225
+ forecasts = self.prediction_agent.forecast_stock_trends(historical_dfs, forecast_period)
1226
+ insights['Forecasts'] = forecasts
1227
+
1228
+ # Sentiment Analysis
1229
+ sentiments = self.sentiment_analysis_agent.analyze_sentiment(news_articles)
1230
+ insights['Sentiment Scores'] = sentiments
1231
+
1232
+ # Anomaly Detection
1233
+ anomalies = self.anomaly_detection_agent.detect_anomalies(stock_df, historical_dfs)
1234
+ insights['Anomalies'] = anomalies
1235
+
1236
+ # Portfolio Optimization
1237
+ portfolio_opt = self.portfolio_optimization_agent.optimize_portfolio(stock_df, historical_dfs)
1238
+ insights['Portfolio Optimization'] = portfolio_opt
1239
+
1240
+ # Real-Time Alerting
1241
+ alerts = self.real_time_alerting_agent.generate_alerts(stock_df, sentiments, anomalies)
1242
+ insights['Alerts'] = alerts
1243
+
1244
+ return insights
1245
+
1246
+ # ----------------------------
1247
+ # Main Application
1248
+ # ----------------------------
1249
+
1250
+ def run_and_visualize(ga):
1251
+ """
1252
+ Runs the GA and visualizes results.
1253
+ """
1254
+ with st.spinner("Running Genetic Algorithm..."):
1255
+ best_path, fitness_history, mutation_rate_history = ga.run()
1256
+
1257
+ st.success("Genetic Algorithm completed!")
1258
+
1259
+ # Best Path Visualization
1260
+ st.write("### Best Path Found:")
1261
+ st.write(best_path)
1262
+
1263
+ # Fitness and Mutation Rate Trends
1264
+ st.write("### Fitness and Mutation Rate Trends")
1265
+ st.line_chart({
1266
+ "Best Fitness": fitness_history,
1267
+ "Mutation Rate": mutation_rate_history
1268
+ })
1269
+
1270
+ def main():
1271
+ # Initialize Database
1272
+ initialize_database()
1273
+
1274
+ # Apply local CSS
1275
+ local_css()
1276
+
1277
+ # Auto-refresh the app every 60 seconds for real-time data
1278
+ count = st_autorefresh(interval=60 * 1000, limit=100, key="autorefreshcounter")
1279
+
1280
+ # Title and Description with enhanced styling
1281
+ st.markdown("<h1 class='title'>📈 Stock Dashboard</h1>", unsafe_allow_html=True)
1282
+ st.markdown("""
1283
+ <p class='description'>
1284
+ Explore and manage your favorite stocks. View comprehensive financial metrics, analyze historical performance with predictive insights, compare multiple stocks, stay updated with the latest news, and interact with our AI Assistant.
1285
+ </p>
1286
+ """, unsafe_allow_html=True)
1287
+
1288
+ # Sidebar Configuration
1289
+ st.sidebar.header("🔧 Settings")
1290
+
1291
+ # Dark/Light Mode Toggle
1292
+ theme = st.sidebar.radio("Theme", ("Light", "Dark"))
1293
+ if theme == "Dark":
1294
+ st.markdown(
1295
+ """
1296
+ <style>
1297
+ body {
1298
+ background-color: #1e1e1e;
1299
+ color: #ffffff;
1300
+ }
1301
+ .chat-container {
1302
+ background-color: #2e2e2e;
1303
+ color: #ffffff;
1304
+ }
1305
+ </style>
1306
+ """,
1307
+ unsafe_allow_html=True
1308
+ )
1309
+ else:
1310
+ st.markdown(
1311
+ """
1312
+ <style>
1313
+ body {
1314
+ background-color: #ffffff;
1315
+ color: #000000;
1316
+ }
1317
+ .chat-container {
1318
+ background-color: #f9f9f9;
1319
+ color: #000000;
1320
+ }
1321
+ </style>
1322
+ """,
1323
+ unsafe_allow_html=True
1324
+ )
1325
+
1326
+ # Sidebar Options for Database Management
1327
+ st.sidebar.header("🗂️ Database Management")
1328
+ db_option = st.sidebar.selectbox(
1329
+ "Select an option",
1330
+ ("None", "View Interactions", "Clear Interactions", "Clear Cache", "Manage Portfolio")
1331
+ )
1332
+
1333
+ if db_option == "View Interactions":
1334
+ st.sidebar.markdown("### Recent Interactions")
1335
+ interactions = fetch_interactions()
1336
+ if interactions:
1337
+ for interaction in interactions:
1338
+ timestamp, user_input, assistant_response = interaction
1339
+ st.sidebar.markdown(
1340
+ f"- **{timestamp}**\n **You:** {user_input}\n **Assistant:** {assistant_response}\n")
1341
+ else:
1342
+ st.sidebar.info("No interactions to display.")
1343
+ elif db_option == "Clear Interactions":
1344
+ if st.sidebar.button("🗑️ Clear All Interactions"):
1345
+ clear_interactions()
1346
+ # Also reset AgentState's memory
1347
+ st.session_state.real_agent.agent_state.reset_memory()
1348
+ elif db_option == "Clear Cache":
1349
+ if st.sidebar.button("🗑️ Clear All Cached Stock Data"):
1350
+ clear_stock_cache()
1351
+ elif db_option == "Manage Portfolio":
1352
+ manage_portfolio()
1353
+
1354
+ # Fetch the top 10 stock tickers
1355
+ with st.spinner("Fetching top 10 stocks by market capitalization..."):
1356
+ top_10_tickers = get_top_10_stocks()
1357
+
1358
+ # User can add more stocks
1359
+ st.sidebar.header("📈 Add Stocks to Dashboard")
1360
+ user_tickers = st.sidebar.text_input("Enter stock tickers separated by commas (e.g., AAPL, MSFT, GOOGL):")
1361
+ add_button = st.sidebar.button("➕ Add Stocks", key="add_button")
1362
+ remove_button = st.sidebar.button("- Remove Stocks", key="remove_button")
1363
+
1364
+ if add_button and user_tickers:
1365
+ user_tickers_list = [ticker.strip().upper() for ticker in user_tickers.split(",")]
1366
+ for ticker in user_tickers_list:
1367
+ if ticker and ticker not in top_10_tickers and ticker not in fetch_portfolio():
1368
+ add_to_portfolio(ticker)
1369
+ st.sidebar.success("Selected stocks have been added to your portfolio.")
1370
+ if remove_button and user_tickers:
1371
+ user_tickers_list = [ticker.strip().upper() for ticker in user_tickers.split(",")]
1372
+ for ticker in user_tickers_list:
1373
+ if ticker and ticker in top_10_tickers:
1374
+ remove_from_portfolio(ticker)
1375
+ st.sidebar.success("Selected stocks have been removed from your portfolio.")
1376
+
1377
+ # Sidebar Configuration
1378
+ st.sidebar.title("🧬 Genetic Algorithm with Fuzzy Logic")
1379
+ st.sidebar.header("Configuration")
1380
+
1381
+ # Parameters
1382
+ population_size = st.sidebar.slider("Population Size", 10, 200, 50)
1383
+ generations = st.sidebar.slider("Generations", 10, 500, 100)
1384
+ uncertainty_input = st.sidebar.slider("Uncertainty Level", 0.0, 1.0, 0.5)
1385
+
1386
+ # Graph Preparation
1387
+ st.sidebar.header("Graph Configuration")
1388
+ num_nodes = st.sidebar.slider("Number of Nodes", 5, 20, 10)
1389
+ graph = prepare_graph(num_nodes)
1390
+
1391
+ # Fuzzy Logic
1392
+ fuzzy_controller = FuzzyMutationController()
1393
+ mutation_rate = fuzzy_controller.compute_mutation_rate(uncertainty_input)
1394
+ st.sidebar.write(f"Computed Mutation Rate: {mutation_rate:.2f}")
1395
+
1396
+ # Visualize Fuzzy Logic
1397
+ st.sidebar.header("Fuzzy Logic Visualization")
1398
+ visualize_fuzzy_logic(fuzzy_controller)
1399
+
1400
+ # Run Genetic Algorithm
1401
+ st.header("🧬 Genetic Algorithm Results")
1402
+ ga = GeneticAlgorithm(graph, fuzzy_controller, population_size, generations)
1403
+
1404
+ if st.button("Run Genetic Algorithm"):
1405
+ run_and_visualize(ga)
1406
+ visualize_graph(graph, best_path=ga.run()[0])
1407
+
1408
+ # Fetch portfolio tickers
1409
+ portfolio_tickers = fetch_portfolio()
1410
+
1411
+ # Combine top 10 and portfolio tickers, ensuring uniqueness
1412
+ all_tickers = list(set(top_10_tickers + portfolio_tickers))
1413
+
1414
+ if not all_tickers:
1415
+ st.warning("No stocks to display. Please add stocks to your portfolio.")
1416
+ st.stop()
1417
+
1418
+ # Sidebar Options
1419
+ refresh_data = st.sidebar.button("🔄 Refresh Data")
1420
+ download_format = st.sidebar.selectbox("Download Format", ("CSV", "JSON"))
1421
+ time_period = st.sidebar.selectbox(
1422
+ "Select Time Period for Historical Data",
1423
+ ("1mo", "3mo", "6mo", "1y", "2y", "5y", "10y", "ytd", "max")
1424
+ )
1425
+
1426
+ # Refresh data if button is clicked
1427
+ if refresh_data:
1428
+ with st.spinner("Refreshing stock data..."):
1429
+ stock_df = get_stock_data(all_tickers)
1430
+ st.success("Data refreshed successfully!")
1431
+ else:
1432
+ with st.spinner("Fetching stock data..."):
1433
+ stock_df = get_stock_data(all_tickers)
1434
+
1435
+ # Ensure relevant columns are numeric
1436
+ numeric_cols = ["Market Cap", "Current Price (USD)", "52 Week High", "52 Week Low",
1437
+ "PE Ratio", "Dividend Yield", "EPS", "Beta", "Revenue", "Net Income", "RSI"]
1438
+
1439
+ for col in numeric_cols:
1440
+ stock_df[col] = pd.to_numeric(stock_df[col], errors='coerce').fillna(0)
1441
+
1442
+ # Verify data types
1443
+ st.write("**Data Types After Conversion:**")
1444
+ st.write(stock_df.dtypes)
1445
+
1446
+ # Now, compute sector_performance from numeric 'Market Cap'
1447
+ sector_performance = stock_df.groupby('Sector')['Market Cap'].sum().reset_index()
1448
+
1449
+ # Filter out sectors with zero or negative Market Cap
1450
+ sector_performance = sector_performance[sector_performance['Market Cap'] > 0]
1451
+
1452
+ if sector_performance.empty:
1453
+ st.warning("No valid sector performance data available for visualization.")
1454
+ else:
1455
+ # Continue with formatting and plotting
1456
+ stock_df_formatted = format_data(stock_df)
1457
+
1458
+ # Display the DataFrame with enhanced styling
1459
+ st.subheader("📊 Stocks by Market Capitalization")
1460
+ st.data_editor(
1461
+ stock_df_formatted.style.set_table_styles([
1462
+ {'selector': 'th',
1463
+ 'props': [('background-color', '#2e86de'), ('color', 'white'), ('font-size', '14px'),
1464
+ ('text-align', 'center')]},
1465
+ {'selector': 'td', 'props': [('text-align', 'center'), ('font-size', '13px')]},
1466
+ {'selector': 'tr:nth-child(even)', 'props': [('background-color', '#f2f2f2')]},
1467
+ ]).hide(axis='index'),
1468
+ height=600,
1469
+ use_container_width=True
1470
+ )
1471
+
1472
+ # Sector Performance Treemap
1473
+ st.markdown("### 🔥 Sector Performance Treemap")
1474
+ try:
1475
+ fig_heatmap = px.treemap(
1476
+ sector_performance,
1477
+ path=['Sector'],
1478
+ values='Market Cap',
1479
+ title='Market Capitalization by Sector',
1480
+ color='Market Cap',
1481
+ color_continuous_scale='RdBu',
1482
+ hover_data={'Market Cap': ':.2f'}
1483
+ )
1484
+ st.plotly_chart(fig_heatmap, use_container_width=True)
1485
+ except ZeroDivisionError as zde:
1486
+ st.error(f"Error creating treemap: {zde}")
1487
+ except Exception as e:
1488
+ st.error(f"An unexpected error occurred while creating treemap: {e}")
1489
+
1490
+ # Comparative Metrics Visualization
1491
+ st.markdown("### 📊 Comparative Metrics")
1492
+
1493
+ comparative_metrics = ["Market Cap", "Current Price (USD)", "52 Week High", "52 Week Low",
1494
+ "PE Ratio", "Dividend Yield", "EPS", "Beta", "Revenue", "Net Income", "RSI"]
1495
+
1496
+ for metric in comparative_metrics:
1497
+ fig = px.bar(
1498
+ stock_df,
1499
+ x='Ticker',
1500
+ y=metric,
1501
+ color='Sector',
1502
+ title=f'{metric} Comparison',
1503
+ labels={metric: metric, 'Ticker': 'Stock Ticker'},
1504
+ text_auto='.2s' if 'Cap' in metric or 'Revenue' in metric or 'Income' in metric else '.2f'
1505
+ )
1506
+ st.plotly_chart(fig, use_container_width=True)
1507
+
1508
+ # Download Buttons
1509
+ st.markdown("### 📥 Download Data")
1510
+ col1, col2 = st.columns(2)
1511
+
1512
+ with col1:
1513
+ if download_format == "CSV":
1514
+ csv_data = convert_df_to_csv(stock_df)
1515
+ st.download_button(
1516
+ label="📥 Download CSV",
1517
+ data=csv_data,
1518
+ file_name='stocks_data.csv',
1519
+ mime='text/csv',
1520
+ )
1521
+ with col2:
1522
+ if download_format == "JSON":
1523
+ json_data = convert_df_to_json(stock_df)
1524
+ st.download_button(
1525
+ label="📥 Download JSON",
1526
+ data=json_data,
1527
+ file_name='stocks_data.json',
1528
+ mime='application/json',
1529
+ )
1530
+
1531
+ # Additional Features: Historical Performance
1532
+ st.markdown("---")
1533
+ st.markdown("### 📈 Stock Performance Over Time")
1534
+
1535
+ # Let user select multiple tickers to view historical data
1536
+ selected_tickers = st.multiselect("🔍 Select Stocks to Compare Historical Performance", all_tickers, default=[all_tickers[0]])
1537
+
1538
+ if not selected_tickers:
1539
+ st.warning("Please select at least one stock to view historical performance.")
1540
+ else:
1541
+ historical_dfs = {}
1542
+ for ticker in selected_tickers:
1543
+ historical_df = get_historical_data(ticker, period=time_period)
1544
+ if not historical_df.empty:
1545
+ # Calculate additional metrics for better insights
1546
+ historical_df['SMA_20'] = historical_df['Close'].rolling(window=20).mean()
1547
+ historical_df['EMA_20'] = historical_df['Close'].ewm(span=20, adjust=False).mean()
1548
+ historical_df['BB_upper'] = historical_df['SMA_20'] + 2 * historical_df['Close'].rolling(window=20).std()
1549
+ historical_df['BB_lower'] = historical_df['SMA_20'] - 2 * historical_df['Close'].rolling(window=20).std()
1550
+ delta = historical_df['Close'].diff()
1551
+ up = delta.clip(lower=0)
1552
+ down = -1 * delta.clip(upper=0)
1553
+ roll_up = up.rolling(window=14).mean()
1554
+ roll_down = down.rolling(window=14).mean()
1555
+ RS = roll_up / roll_down
1556
+ historical_df['RSI'] = 100.0 - (100.0 / (1.0 + RS))
1557
+ historical_dfs[ticker] = historical_df
1558
+ else:
1559
+ historical_dfs[ticker] = pd.DataFrame()
1560
+
1561
+ # Interactive Comparative Candlestick Chart using Plotly
1562
+ fig_candlestick = go.Figure()
1563
+
1564
+ for ticker in selected_tickers:
1565
+ hist_df = historical_dfs.get(ticker, pd.DataFrame())
1566
+ if hist_df.empty:
1567
+ continue
1568
+ fig_candlestick.add_trace(go.Candlestick(
1569
+ x=hist_df['Date'],
1570
+ open=hist_df['Open'],
1571
+ high=hist_df['High'],
1572
+ low=hist_df['Low'],
1573
+ close=hist_df['Close'],
1574
+ name=f'{ticker} Candlestick'
1575
+ ))
1576
+ fig_candlestick.add_trace(go.Scatter(
1577
+ x=hist_df['Date'],
1578
+ y=hist_df['SMA_20'],
1579
+ mode='lines',
1580
+ line=dict(width=1),
1581
+ name=f'{ticker} SMA 20'
1582
+ ))
1583
+ fig_candlestick.add_trace(go.Scatter(
1584
+ x=hist_df['Date'],
1585
+ y=hist_df['EMA_20'],
1586
+ mode='lines',
1587
+ line=dict(width=1),
1588
+ name=f'{ticker} EMA 20'
1589
+ ))
1590
+
1591
+ fig_candlestick.update_layout(
1592
+ title="Comparative Candlestick Chart with Moving Averages",
1593
+ xaxis_title="Date",
1594
+ yaxis_title="Price (USD)",
1595
+ xaxis_rangeslider_visible=False
1596
+ )
1597
+
1598
+ st.plotly_chart(fig_candlestick, use_container_width=True)
1599
+
1600
+ # Comparative RSI
1601
+ st.markdown("#### Comparative Relative Strength Index (RSI)")
1602
+ fig_rsi = go.Figure()
1603
+
1604
+ for ticker in selected_tickers:
1605
+ hist_df = historical_dfs.get(ticker, pd.DataFrame())
1606
+ if hist_df.empty:
1607
+ continue
1608
+ fig_rsi.add_trace(go.Scatter(
1609
+ x=hist_df['Date'],
1610
+ y=hist_df['RSI'],
1611
+ mode='lines',
1612
+ name=f'{ticker} RSI'
1613
+ ))
1614
+
1615
+ fig_rsi.add_hline(y=70, line_dash="dash", line_color="red")
1616
+ fig_rsi.add_hline(y=30, line_dash="dash", line_color="green")
1617
+ fig_rsi.update_layout(
1618
+ title="Relative Strength Index (RSI) Comparison",
1619
+ xaxis_title="Date",
1620
+ yaxis_title="RSI",
1621
+ yaxis=dict(range=[0, 100])
1622
+ )
1623
+ st.plotly_chart(fig_rsi, use_container_width=True)
1624
+
1625
+ # Forecasting with Prophet for each selected ticker
1626
+ st.markdown("#### 🔮 Future Price Prediction")
1627
+ forecast_period = st.slider("Select Forecast Period (Days):", min_value=30, max_value=365, value=90,
1628
+ step=30)
1629
+
1630
+ forecast_figs = []
1631
+ # Initialize AI Orchestrator
1632
+ ai_orchestrator = AIOrchestrator()
1633
+ # Generate insights from agents
1634
+ fsirdm_data = ai_orchestrator.generate_insights(stock_df, historical_dfs, {}, forecast_period)
1635
+
1636
+ for ticker in selected_tickers:
1637
+ model, forecast_df = forecast_stock_price(historical_dfs.get(ticker, pd.DataFrame()), forecast_period)
1638
+ if model is not None and not forecast_df.empty:
1639
+ fig_forecast = plot_plotly(model, forecast_df)
1640
+ fig_forecast.update_layout(
1641
+ title=f"{ticker} Price Forecast for Next {forecast_period} Days",
1642
+ xaxis_title="Date",
1643
+ yaxis_title="Price (USD)"
1644
+ )
1645
+ forecast_figs.append(fig_forecast)
1646
+ st.plotly_chart(fig_forecast, use_container_width=True)
1647
+ else:
1648
+ st.warning(f"Forecasting model could not generate predictions for {ticker}.")
1649
+
1650
+ # Real-Time Notifications
1651
+ # Implement notifications for significant changes here if needed
1652
+
1653
+ # News and Analysis
1654
+ st.markdown("---")
1655
+ st.markdown("### 📰 Latest News")
1656
+
1657
+ news_articles = get_stock_news(selected_tickers)
1658
+
1659
+ if news_articles:
1660
+ for ticker, articles in news_articles.items():
1661
+ st.markdown(f"#### {ticker} News")
1662
+ if articles and isinstance(articles, list):
1663
+ for article in articles:
1664
+ st.markdown(f"**[{article['Title']}]({article['URL']})**")
1665
+ try:
1666
+ published_date = datetime.strptime(article['Published At'], "%Y-%m-%dT%H:%M:%SZ")
1667
+ formatted_date = published_date.strftime("%B %d, %Y %H:%M")
1668
+ except ValueError:
1669
+ formatted_date = article['Published At']
1670
+ st.markdown(f"*{formatted_date}*")
1671
+ st.markdown(f"{article['Description']}")
1672
+ st.markdown("---")
1673
+ else:
1674
+ st.info("No recent news articles found.")
1675
+ else:
1676
+ st.info("No recent news articles found.")
1677
+
1678
+ # AI Assistant Interaction
1679
+ st.markdown("---")
1680
+ st.markdown("### 🤖 Ask the Generis AI")
1681
+ st.empty()
1682
+ user_input = st.text_input("Ask a question about stocks or market trends:", type="default")
1683
+
1684
+ # ----------------------------
1685
+ # Added "Clear Chat" Button
1686
+ # ----------------------------
1687
+ if st.button("🗑️ Clear Chat"):
1688
+ clear_chat()
1689
+ st.success("Chat history has been cleared.")
1690
+
1691
+ if user_input:
1692
+ with st.spinner("Processing your request..."):
1693
+ response = st.session_state.real_agent.process(
1694
+ user_input, selected_tickers, stock_df, historical_dfs, news_articles, fsirdm_data
1695
+ )
1696
+ # Display the conversation in a chat-like format
1697
+ st.markdown(f"<div class='user-message'><strong>You:</strong> {user_input}</div>",
1698
+ unsafe_allow_html=True)
1699
+ st.markdown(f"<div class='assistant-message'><strong>Assistant:</strong> {response}</div>",
1700
+ unsafe_allow_html=True)
1701
+ st.markdown("</div>", unsafe_allow_html=True)
1702
+
1703
+ # Display AI Generated Insights
1704
+ st.markdown("---")
1705
+ st.markdown("### 🤖 AI Generated Insights")
1706
+ ai_orchestrator = AIOrchestrator()
1707
+ insights = ai_orchestrator.generate_insights(stock_df, historical_dfs, news_articles, forecast_period)
1708
+
1709
+ # Display Data Trends
1710
+ st.subheader("📊 Data Trends")
1711
+ data_trends = insights.get('Data Trends', {})
1712
+ if data_trends:
1713
+ st.json(data_trends)
1714
+ else:
1715
+ st.info("No data trends available.")
1716
+
1717
+ # Display Forecasts
1718
+ st.subheader("🔮 Forecasts")
1719
+ forecasts = insights.get('Forecasts', {})
1720
+ if forecasts:
1721
+ for ticker, forecast in forecasts.items():
1722
+ st.markdown(f"**{ticker} Forecast:**")
1723
+ if isinstance(forecast, list):
1724
+ forecast_df = pd.DataFrame(forecast)
1725
+ st.dataframe(forecast_df)
1726
+ else:
1727
+ st.write(forecast)
1728
+ else:
1729
+ st.info("No forecasts available.")
1730
+
1731
+ # Display Sentiment Scores
1732
+ st.subheader("😊 Sentiment Scores")
1733
+ sentiments = insights.get('Sentiment Scores', {})
1734
+ if sentiments:
1735
+ st.json(sentiments)
1736
+ else:
1737
+ st.info("No sentiment scores available.")
1738
+
1739
+ # Display Anomalies
1740
+ st.subheader("⚠️ Anomalies Detected")
1741
+ anomalies = insights.get('Anomalies', {})
1742
+ if anomalies:
1743
+ for ticker, anomaly_dates in anomalies.items():
1744
+ st.markdown(f"**{ticker}:** {', '.join(map(str, anomaly_dates))}")
1745
+ else:
1746
+ st.info("No anomalies detected.")
1747
+
1748
+ # Display Portfolio Optimization
1749
+ st.subheader("💼 Portfolio Optimization")
1750
+ portfolio_opt = insights.get('Portfolio Optimization', {})
1751
+ if portfolio_opt:
1752
+ st.json(portfolio_opt)
1753
+ else:
1754
+ st.info("No portfolio optimization available.")
1755
+
1756
+ # Display Alerts
1757
+ st.subheader("🚨 Alerts")
1758
+ alerts = insights.get('Alerts', {})
1759
+ if alerts:
1760
+ for ticker, alert_list in alerts.items():
1761
+ if alert_list:
1762
+ for alert in alert_list:
1763
+ st.warning(f"{ticker}: {alert}")
1764
+ else:
1765
+ st.info("No alerts generated.")
1766
+
1767
+ # Footer
1768
+ st.markdown("---")
1769
+ st.markdown("<p class='footer'>© 2024 Your Company Name. All rights reserved.</p>", unsafe_allow_html=True)
1770
+
1771
+ def forecast_stock_price(historical_df: pd.DataFrame, periods: int = 90) -> Tuple[Any, pd.DataFrame]:
1772
+ """
1773
+ Uses Facebook's Prophet to forecast future stock prices.
1774
+ Returns both the fitted model and the forecast DataFrame.
1775
+ """
1776
+ try:
1777
+ if historical_df.empty:
1778
+ return None, pd.DataFrame()
1779
+ df_prophet = historical_df[['Date', 'Close']].rename(columns={'Date': 'ds', 'Close': 'y'})
1780
+ model = Prophet(daily_seasonality=False, yearly_seasonality=True, weekly_seasonality=True)
1781
+ model.fit(df_prophet)
1782
+ future = model.make_future_dataframe(periods=periods)
1783
+ forecast = model.predict(future)
1784
+ return model, forecast # Return both model and forecast
1785
+ except Exception as e:
1786
+ st.error(f"Error in forecasting: {e}")
1787
+ return None, pd.DataFrame()
1788
+
1789
+ def clear_chat():
1790
+ """
1791
+ Clears the conversation history by deleting interactions from the database
1792
+ and resetting the AgentState's memory.
1793
+ """
1794
+ clear_interactions()
1795
+ st.session_state.real_agent.agent_state.reset_memory()
1796
+
1797
+ def manage_portfolio():
1798
+ """
1799
+ Manages the user's portfolio by allowing addition and removal of stocks.
1800
+ """
1801
+ st.header("📁 Manage Your Portfolio")
1802
+ portfolio = fetch_portfolio()
1803
+ if portfolio:
1804
+ st.subheader("Your Portfolio:")
1805
+ portfolio_df = pd.DataFrame(portfolio, columns=["Ticker"])
1806
+ st.data_editor(portfolio_df, height=500, use_container_width=True, key="portfolio_editor")
1807
+
1808
+ remove_tickers = st.multiselect(label="Select stocks to remove from your portfolio:", options=portfolio)
1809
+ if st.button("🗑️ Remove Selected Stocks") and remove_tickers:
1810
+ for ticker in remove_tickers:
1811
+ remove_from_portfolio(ticker)
1812
+ st.success("Selected stocks have been removed from your portfolio.")
1813
+ else:
1814
+ st.info("Your portfolio is empty. Add stocks to get started.")
1815
+
1816
+ st.markdown("---")
1817
+ st.subheader("Add New Stocks to Portfolio")
1818
+ new_ticker = st.text_input("Enter a stock ticker to add:")
1819
+ if st.button("➕ Add to Portfolio"):
1820
+ if new_ticker:
1821
+ add_to_portfolio(new_ticker)
1822
+ else:
1823
+ st.warning("Please enter a valid stock ticker.")
1824
+
1825
+ def get_top_10_stocks() -> List[str]:
1826
+ """
1827
+ Fetches the top 10 stocks by market capitalization using Financial Modeling Prep API.
1828
+ Utilizes the database cache if available and not expired.
1829
+ """
1830
+ try:
1831
+ # Check if cache exists for 'TOP10'
1832
+ conn = sqlite3.connect(DATABASE)
1833
+ cursor = conn.cursor()
1834
+ cursor.execute("""
1835
+ SELECT fetched_at, data
1836
+ FROM stock_cache
1837
+ WHERE ticker = 'TOP10'
1838
+ """)
1839
+ row = cursor.fetchone()
1840
+ conn.close()
1841
+ use_cache = False
1842
+ if row:
1843
+ fetched_at, data = row
1844
+ fetched_time = datetime.fromisoformat(fetched_at).date()
1845
+ today = datetime.utcnow().date()
1846
+ if (today - fetched_time).days < 1: # 1 day TTL
1847
+ use_cache = True
1848
+ tickers = json.loads(data)
1849
+ if not use_cache:
1850
+ if not update_api_usage("FMP"):
1851
+ st.warning("Financial Modeling Prep API rate limit exceeded. Cannot fetch top 10 stocks.")
1852
+ return []
1853
+ url = f"https://financialmodelingprep.com/api/v3/stock-screener?marketCapMoreThan=1000000000&limit=100&apikey={FMP_API_KEY}"
1854
+ response = requests.get(url)
1855
+ response.raise_for_status()
1856
+ data = response.json()
1857
+ if not isinstance(data, list):
1858
+ st.error("Unexpected response format from Financial Modeling Prep API.")
1859
+ return []
1860
+ sorted_data = sorted(data, key=lambda x: x.get('marketCap', 0), reverse=True)
1861
+ top_10 = sorted_data[:10]
1862
+ tickers = [stock['symbol'] for stock in top_10]
1863
+ # Cache the top 10 tickers
1864
+ insert_stock_cache('TOP10', tickers)
1865
+ return tickers
1866
+ except Exception as e:
1867
+ st.error(f"Error fetching top 10 stocks: {e}")
1868
+ return []
1869
+
1870
+ @st.cache_data(ttl=600)
1871
+ def get_stock_data(tickers: List[str]) -> pd.DataFrame:
1872
+ """
1873
+ Fetches detailed stock data for the given list of tickers using yfinance.
1874
+ Utilizes the database cache if available.
1875
+ """
1876
+ # Use asyncio to fetch data concurrently
1877
+ loop = asyncio.new_event_loop()
1878
+ asyncio.set_event_loop(loop)
1879
+ responses = loop.run_until_complete(fetch_all_stock_data(tickers))
1880
+ loop.close()
1881
+
1882
+ stock_info = []
1883
+ for ticker, info in responses:
1884
+ stock_info.append({
1885
+ "Ticker": ticker,
1886
+ "Name": info.get("shortName", "N/A"),
1887
+ "Sector": info.get("sector", "N/A"),
1888
+ "Industry": info.get("industry", "N/A"),
1889
+ "Market Cap": info.get("marketCap", 0), # Default to 0 if missing
1890
+ "Current Price (USD)": info.get("currentPrice", 0),
1891
+ "52 Week High": info.get("fiftyTwoWeekHigh", 0),
1892
+ "52 Week Low": info.get("fiftyTwoWeekLow", 0),
1893
+ "PE Ratio": info.get("trailingPE", 0),
1894
+ "Dividend Yield": info.get("dividendYield", 0),
1895
+ "EPS": info.get("trailingEps", 0),
1896
+ "Beta": info.get("beta", 0),
1897
+ "Revenue": info.get("totalRevenue", 0),
1898
+ "Net Income": info.get("netIncomeToCommon", 0),
1899
+ "RSI": calculate_rsi(info.get("symbol", "N/A"), period=14) # Calculate RSI
1900
+ })
1901
+ df = pd.DataFrame(stock_info)
1902
+
1903
+ # Data Cleaning: Ensure all numeric columns are indeed numeric
1904
+ numeric_cols = ["Market Cap", "Current Price (USD)", "52 Week High", "52 Week Low",
1905
+ "PE Ratio", "Dividend Yield", "EPS", "Beta", "Revenue", "Net Income", "RSI"]
1906
+
1907
+ for col in numeric_cols:
1908
+ df[col] = pd.to_numeric(df[col], errors='coerce').fillna(0)
1909
+
1910
+ return df
1911
+
1912
+ def calculate_rsi(ticker: str, period: int = 14) -> float:
1913
+ """
1914
+ Calculates the Relative Strength Index (RSI) for a given ticker.
1915
+ """
1916
+ try:
1917
+ stock = yf.Ticker(ticker)
1918
+ hist = stock.history(period="1y")
1919
+ if hist.empty:
1920
+ return 0.0
1921
+ delta = hist['Close'].diff()
1922
+ up = delta.clip(lower=0)
1923
+ down = -1 * delta.clip(upper=0)
1924
+ roll_up = up.rolling(window=period).mean()
1925
+ roll_down = down.rolling(window=period).mean()
1926
+ RS = roll_up / roll_down
1927
+ RSI = 100.0 - (100.0 / (1.0 + RS))
1928
+ return RSI.iloc[-1] if not RSI.empty else 0.0
1929
+ except Exception as e:
1930
+ st.error(f"Error calculating RSI for {ticker}: {e}")
1931
+ return 0.0
1932
+
1933
+ @st.cache_data(ttl=600)
1934
+ def get_historical_data(ticker: str, period: str = "1mo") -> pd.DataFrame:
1935
+ """
1936
+ Fetches historical stock data.
1937
+ """
1938
+ try:
1939
+ stock = yf.Ticker(ticker)
1940
+ hist = stock.history(period=period)
1941
+ if hist.empty:
1942
+ st.warning(f"No historical data available for {ticker} in the selected period.")
1943
+ return pd.DataFrame()
1944
+ hist.reset_index(inplace=True)
1945
+ hist['Date'] = hist['Date'].dt.date
1946
+ return hist
1947
+ except Exception as e:
1948
+ st.error(f"Error fetching historical data for {ticker}: {e}")
1949
+ return pd.DataFrame()
1950
+
1951
+ @st.cache_data(ttl=600)
1952
+ def get_stock_news(tickers: List[str]) -> Dict[str, List[Dict[str, Any]]]:
1953
+ """
1954
+ Fetches latest news for the given tickers using NewsAPI.
1955
+ Returns a dictionary with tickers as keys and list of articles as values.
1956
+ """
1957
+ news_dict = {}
1958
+ for ticker in tickers:
1959
+ if not update_api_usage("NewsAPI"):
1960
+ st.warning("NewsAPI rate limit exceeded. Cannot fetch latest news.")
1961
+ news_dict[ticker] = []
1962
+ continue
1963
+ try:
1964
+ stock = yf.Ticker(ticker)
1965
+ company_name = stock.info.get('shortName', ticker)
1966
+ query = f"{ticker} OR \"{company_name}\""
1967
+
1968
+ articles = newsapi.get_everything(
1969
+ q=query,
1970
+ language='en',
1971
+ sort_by='publishedAt',
1972
+ page_size=5
1973
+ )
1974
+
1975
+ news = []
1976
+ for article in articles.get('articles', []):
1977
+ news.append({
1978
+ "Title": article['title'],
1979
+ "Description": article['description'],
1980
+ "URL": article['url'],
1981
+ "Published At": article['publishedAt']
1982
+ })
1983
+ news_dict[ticker] = news
1984
+ except Exception as e:
1985
+ st.error(f"Error fetching news for {ticker}: {e}")
1986
+ news_dict[ticker] = []
1987
+ return news_dict
1988
+
1989
+ def convert_df_to_csv(df: pd.DataFrame) -> bytes:
1990
+ """Converts DataFrame to CSV."""
1991
+ return df.to_csv(index=False).encode('utf-8')
1992
+
1993
+ def convert_df_to_json(df: pd.DataFrame) -> bytes:
1994
+ """Converts DataFrame to JSON."""
1995
+ return df.to_json(orient='records', indent=4).encode('utf-8')
1996
+
1997
+ def format_data(df: pd.DataFrame) -> pd.DataFrame:
1998
+ """
1999
+ Formats numerical columns for better readability.
2000
+ """
2001
+ df_formatted = df.copy()
2002
+ df_formatted["Market Cap"] = df_formatted["Market Cap"].apply(
2003
+ lambda x: f"${x:,.2f}" if isinstance(x, (int, float)) else "N/A"
2004
+ )
2005
+ df_formatted["Current Price (USD)"] = df_formatted["Current Price (USD)"].apply(
2006
+ lambda x: f"${x:,.2f}" if isinstance(x, (int, float)) else "N/A"
2007
+ )
2008
+ df_formatted["52 Week High"] = df_formatted["52 Week High"].apply(
2009
+ lambda x: f"${x:,.2f}" if isinstance(x, (int, float)) else "N/A"
2010
+ )
2011
+ df_formatted["52 Week Low"] = df_formatted["52 Week Low"].apply(
2012
+ lambda x: f"${x:,.2f}" if isinstance(x, (int, float)) else "N/A"
2013
+ )
2014
+ df_formatted["PE Ratio"] = df_formatted["PE Ratio"].apply(
2015
+ lambda x: f"{x:.2f}" if isinstance(x, (int, float)) else "N/A"
2016
+ )
2017
+ df_formatted["Dividend Yield"] = df_formatted["Dividend Yield"].apply(
2018
+ lambda x: f"{x:.2%}" if isinstance(x, (int, float)) else "N/A"
2019
+ )
2020
+ df_formatted["EPS"] = df_formatted["EPS"].apply(
2021
+ lambda x: f"{x:.2f}" if isinstance(x, (int, float)) else "N/A"
2022
+ )
2023
+ df_formatted["Beta"] = df_formatted["Beta"].apply(
2024
+ lambda x: f"{x:.2f}" if isinstance(x, (int, float)) else "N/A"
2025
+ )
2026
+ df_formatted["Revenue"] = df_formatted["Revenue"].apply(
2027
+ lambda x: f"${x:,.2f}" if isinstance(x, (int, float)) else "N/A"
2028
+ )
2029
+ df_formatted["Net Income"] = df_formatted["Net Income"].apply(
2030
+ lambda x: f"${x:,.2f}" if isinstance(x, (int, float)) else "N/A"
2031
+ )
2032
+ df_formatted["RSI"] = df_formatted["RSI"].apply(
2033
+ lambda x: f"{x:.2f}" if isinstance(x, (int, float)) else "N/A"
2034
+ )
2035
+ return df_formatted
2036
+
2037
+ def get_stock_price(ticker: str) -> str:
2038
+ """
2039
+ Fetches the current price of the given ticker.
2040
+ """
2041
+ try:
2042
+ stock = yf.Ticker(ticker)
2043
+ price = stock.info.get('currentPrice', None)
2044
+ if price is None:
2045
+ return f"Could not fetch the current price for {ticker.upper()}."
2046
+ return f"The current price of {ticker.upper()} is ${price:.2f}"
2047
+ except Exception as e:
2048
+ return f"Error fetching stock price for {ticker.upper()}: {e}"
2049
+
2050
+ def get_stock_summary(ticker: str) -> str:
2051
+ """
2052
+ Fetches a summary of the given ticker.
2053
+ """
2054
+ try:
2055
+ stock = yf.Ticker(ticker)
2056
+ info = stock.info
2057
+ summary = {
2058
+ "Name": info.get("shortName", "N/A"),
2059
+ "Sector": info.get("sector", "N/A"),
2060
+ "Industry": info.get("industry", "N/A"),
2061
+ "Current Price (USD)": info.get("currentPrice", "N/A"),
2062
+ "52 Week High": info.get("fiftyTwoWeekHigh", "N/A"),
2063
+ "52 Week Low": info.get("fiftyTwoWeekLow", "N/A"),
2064
+ "Market Cap": info.get("marketCap", "N/A"),
2065
+ }
2066
+ response = "\n".join([f"{key}: {value}" for key, value in summary.items()])
2067
+ return response
2068
+ except Exception as e:
2069
+ return f"Error fetching summary for {ticker.upper()}: {e}"
2070
+
2071
+ def get_latest_news(query: str) -> List[Dict[str, Any]]:
2072
+ """
2073
+ Fetches the latest news articles based on the query.
2074
+ """
2075
+ if not update_api_usage("NewsAPI"):
2076
+ st.warning("NewsAPI rate limit exceeded. Cannot fetch latest news.")
2077
+ return []
2078
+ try:
2079
+ articles = newsapi.get_everything(q=query, language='en', sort_by='publishedAt', page_size=3)
2080
+ if not articles['articles']:
2081
+ return []
2082
+ news_list: List[Dict[str, Any]] = []
2083
+ for article in articles['articles']:
2084
+ news_list.append({
2085
+ "Title": article['title'],
2086
+ "Description": article['description'],
2087
+ "URL": article['url'],
2088
+ "Published At": article['publishedAt']
2089
+ })
2090
+ return news_list
2091
+ except Exception as e:
2092
+ st.error(f"Error fetching news for {query}: {e}")
2093
+ return []
2094
+
2095
+ # ----------------------------
2096
+ # Run the Application
2097
+ # ----------------------------
2098
+
2099
+ if __name__ == "__main__":
2100
+ main()