dev2607 commited on
Commit
12a207c
Β·
verified Β·
1 Parent(s): a82d24c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +138 -75
app.py CHANGED
@@ -1,41 +1,30 @@
1
  import streamlit as st
2
  import yfinance as yf
3
  import pandas as pd
 
4
  from groq import Groq
5
  import os
6
- import requests
7
  from duckduckgo_search import DDGS
8
 
9
- # Streamlit App Configuratio
 
 
 
10
  st.set_page_config(
11
  page_title="Financial Analysis AI Agent",
12
  page_icon="πŸ’Ή",
13
- layout="centered"
14
  )
15
 
16
- # Custom CSS for center alignment
17
- st.markdown("""
18
- <style>
19
- .reportview-container .main .block-container {
20
- text-align: center;
21
- }
22
- .stTextInput > div > div > input {
23
- text-align: center;
24
- }
25
- .stSelectbox > div > div > div {
26
- text-align: center;
27
- }
28
- </style>
29
- """, unsafe_allow_html=True)
30
-
31
  # Initialize Groq Client
32
  def get_groq_client():
33
  try:
34
- # Try to get API key from Hugging Face secrets first
35
- groq_api_key = st.secrets.get("GROQ_API_KEY") or os.getenv("GROQ_API_KEY")
36
 
37
  if not groq_api_key:
38
- st.error("Groq API Key is missing. Please set it in Secrets or .env file.")
39
  return None
40
 
41
  return Groq(api_key=groq_api_key)
@@ -69,6 +58,74 @@ def get_stock_info(symbol):
69
  st.error(f"Error fetching stock information: {e}")
70
  return None
71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
  # Fetch News Using DuckDuckGo
73
  def get_duckduckgo_news(symbol, limit=5):
74
  try:
@@ -138,68 +195,74 @@ def main():
138
  st.title("πŸš€ Advanced Financial Insight AI")
139
  st.markdown("Comprehensive stock analysis with DuckDuckGo news search")
140
 
141
- # Center columns for inputs
142
- col1, col2, col3 = st.columns([1,2,1])
143
 
144
- with col2:
145
- # Stock Symbol Input
146
- stock_symbol = st.text_input(
147
- "Enter Stock Symbol",
148
- value="NVDA",
149
- help="Enter a valid stock ticker (e.g., AAPL, GOOGL)"
150
- )
151
 
152
- # Analysis Type Selection
153
- query_type = st.selectbox(
154
- "Select Analysis Type",
155
- [
156
- "Comprehensive Analysis",
157
- "Analyst Recommendations",
158
- "Latest News Analysis"
159
- ]
160
- )
161
 
162
- # Generate Analysis Button
163
- if st.button("Generate Analysis"):
164
- with st.spinner("Fetching and analyzing stock data..."):
165
- try:
166
- # Fetch Stock Information
167
- stock_info = get_stock_info(stock_symbol)
168
-
169
- if stock_info:
170
- # Display Stock Information
171
- st.subheader(f"Financial Snapshot: {stock_symbol}")
172
- info_df = pd.DataFrame.from_dict(stock_info, orient='index', columns=['Value'])
173
- st.table(info_df)
174
-
175
- # Fetch News via DuckDuckGo
176
- real_time_news = get_duckduckgo_news(stock_symbol)
177
-
178
- # Display News
179
- st.subheader("πŸ“° Latest News")
180
- for news in real_time_news:
181
- st.markdown(f"**{news['title']}**")
182
- st.markdown(f"*Source: {news['publisher']}*")
183
- st.markdown(f"[Read more]({news['link']})")
184
- st.markdown("---")
185
-
186
- # Generate AI Analysis
187
- ai_analysis = generate_ai_analysis(stock_info, real_time_news, query_type)
188
-
189
- # Display AI Analysis
190
- st.subheader("πŸ€– AI-Powered Insights")
191
- st.write(ai_analysis)
192
-
193
- except Exception as e:
194
- st.error(f"An error occurred: {e}")
 
 
 
 
 
 
 
 
195
 
196
  # Disclaimer
197
- st.markdown("<div style='text-align: center; margin-top: 20px;'>", unsafe_allow_html=True)
198
- st.warning(
199
  "🚨 Disclaimer: This is an AI-generated analysis. "
200
  "Always consult with a financial advisor before making investment decisions."
201
  )
202
- st.markdown("</div>", unsafe_allow_html=True)
203
 
204
  # Run the Streamlit app
205
  if __name__ == "__main__":
 
1
  import streamlit as st
2
  import yfinance as yf
3
  import pandas as pd
4
+ import plotly.graph_objs as plt
5
  from groq import Groq
6
  import os
7
+ from dotenv import load_dotenv
8
  from duckduckgo_search import DDGS
9
 
10
+ # Load environment variables from .env file
11
+ load_dotenv()
12
+
13
+ # Streamlit App Configuration
14
  st.set_page_config(
15
  page_title="Financial Analysis AI Agent",
16
  page_icon="πŸ’Ή",
17
+ layout="wide"
18
  )
19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  # Initialize Groq Client
21
  def get_groq_client():
22
  try:
23
+ # Try to get API key from environment variables
24
+ groq_api_key = os.getenv("GROQ_API_KEY")
25
 
26
  if not groq_api_key:
27
+ st.error("Groq API Key is missing. Please set GROQ_API_KEY in your .env file.")
28
  return None
29
 
30
  return Groq(api_key=groq_api_key)
 
58
  st.error(f"Error fetching stock information: {e}")
59
  return None
60
 
61
+ # Fetch Historical Stock Data and Calculate Volatility
62
+ def get_stock_volatility(symbol, period='1y'):
63
+ try:
64
+ # Download historical stock data
65
+ stock_data = yf.download(symbol, period=period)
66
+
67
+ if stock_data.empty:
68
+ st.error(f"No historical data found for {symbol}")
69
+ return None
70
+
71
+ # Calculate daily returns
72
+ stock_data['Daily Returns'] = stock_data['Close'].pct_change()
73
+
74
+ # Calculate rolling volatility (30-day standard deviation of returns)
75
+ stock_data['Rolling Volatility'] = stock_data['Daily Returns'].rolling(window=30).std() * (252 ** 0.5) # Annualized
76
+
77
+ return stock_data
78
+ except Exception as e:
79
+ st.error(f"Error fetching historical stock data: {e}")
80
+ return None
81
+
82
+ # Create Volatility Visualization
83
+ def create_volatility_chart(stock_data):
84
+ try:
85
+ # Create figure with two y-axes
86
+ fig = plt.Figure()
87
+
88
+ # Price line
89
+ fig.add_trace(
90
+ plt.Scatter(
91
+ x=stock_data.index,
92
+ y=stock_data['Close'],
93
+ name='Stock Price',
94
+ line=dict(color='blue'),
95
+ yaxis='y1'
96
+ )
97
+ )
98
+
99
+ # Volatility line
100
+ fig.add_trace(
101
+ plt.Scatter(
102
+ x=stock_data.index,
103
+ y=stock_data['Rolling Volatility'],
104
+ name='30-Day Volatility',
105
+ line=dict(color='red'),
106
+ yaxis='y2'
107
+ )
108
+ )
109
+
110
+ # Layout configuration
111
+ fig.update_layout(
112
+ title=f'Stock Price and Volatility',
113
+ xaxis_title='Date',
114
+ yaxis_title='Stock Price',
115
+ yaxis2=dict(
116
+ title='Annualized Volatility',
117
+ overlaying='y',
118
+ side='right'
119
+ ),
120
+ height=600,
121
+ legend=dict(x=0, y=1.1, orientation='h')
122
+ )
123
+
124
+ return fig
125
+ except Exception as e:
126
+ st.error(f"Error creating volatility chart: {e}")
127
+ return None
128
+
129
  # Fetch News Using DuckDuckGo
130
  def get_duckduckgo_news(symbol, limit=5):
131
  try:
 
195
  st.title("πŸš€ Advanced Financial Insight AI")
196
  st.markdown("Comprehensive stock analysis with DuckDuckGo news search")
197
 
198
+ # Sidebar Configuration
199
+ st.sidebar.header("πŸ” Stock Analysis")
200
 
201
+ # Stock Symbol Input
202
+ stock_symbol = st.sidebar.text_input(
203
+ "Enter Stock Symbol",
204
+ value="NVDA",
205
+ help="Enter a valid stock ticker (e.g., AAPL, GOOGL)"
206
+ )
 
207
 
208
+ # Analysis Type Selection
209
+ query_type = st.sidebar.selectbox(
210
+ "Select Analysis Type",
211
+ [
212
+ "Comprehensive Analysis",
213
+ "Analyst Recommendations",
214
+ "Latest News Analysis"
215
+ ]
216
+ )
217
 
218
+ # Generate Analysis Button
219
+ if st.sidebar.button("Generate Analysis"):
220
+ with st.spinner("Fetching and analyzing stock data..."):
221
+ try:
222
+ # Fetch Stock Information
223
+ stock_info = get_stock_info(stock_symbol)
224
+
225
+ if stock_info:
226
+ # Display Stock Information
227
+ st.subheader(f"Financial Snapshot: {stock_symbol}")
228
+ info_df = pd.DataFrame.from_dict(stock_info, orient='index', columns=['Value'])
229
+ st.table(info_df)
230
+
231
+ # Fetch and Display Volatility Chart
232
+ volatility_data = get_stock_volatility(stock_symbol)
233
+ if volatility_data is not None:
234
+ # Create and Display Volatility Chart
235
+ st.subheader("πŸ“Š Stock Price and Volatility")
236
+ volatility_chart = create_volatility_chart(volatility_data)
237
+ st.plotly_chart(volatility_chart, use_container_width=True)
238
+
239
+ # Fetch News via DuckDuckGo
240
+ real_time_news = get_duckduckgo_news(stock_symbol)
241
+
242
+ # Display News
243
+ st.subheader("πŸ“° Latest News")
244
+ for news in real_time_news:
245
+ st.markdown(f"**{news['title']}**")
246
+ st.markdown(f"*Source: {news['publisher']}*")
247
+ st.markdown(f"[Read more]({news['link']})")
248
+ st.markdown("---")
249
+
250
+ # Generate AI Analysis
251
+ ai_analysis = generate_ai_analysis(stock_info, real_time_news, query_type)
252
+
253
+ # Display AI Analysis
254
+ st.subheader("πŸ€– AI-Powered Insights")
255
+ st.write(ai_analysis)
256
+
257
+ except Exception as e:
258
+ st.error(f"An error occurred: {e}")
259
 
260
  # Disclaimer
261
+ st.sidebar.markdown("---")
262
+ st.sidebar.warning(
263
  "🚨 Disclaimer: This is an AI-generated analysis. "
264
  "Always consult with a financial advisor before making investment decisions."
265
  )
 
266
 
267
  # Run the Streamlit app
268
  if __name__ == "__main__":