akazmi commited on
Commit
d448b9a
1 Parent(s): 30cf2a0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +34 -36
app.py CHANGED
@@ -4,7 +4,7 @@ import yfinance as yf
4
  import requests
5
  from bs4 import BeautifulSoup
6
  import xml.etree.ElementTree as ET
7
- import re # Add this import at the top of your code
8
 
9
  # Set up the models for Named Entity Recognition, Sentiment Analysis, and Text Generation
10
  ner_model = "Cassie-0121/fin-bert-finetuned-ner"
@@ -21,15 +21,16 @@ st.title("AI-Powered Financial Analysis App")
21
  # Sidebar for selecting stock
22
  st.sidebar.header("Select Stock for Analysis")
23
  top_100_stocks = [
24
- "AAPL", "MSFT", "GOOGL", "AMZN", "TSLA", "META", "NVDA", "BRK-B", "JNJ", "JPM",
25
- "V", "PG", "UNH", "DIS", "MA", "HD", "BAC", "XOM", "VZ", "PFE", "KO", "PEP", "MRK",
26
- "WMT", "CSCO", "INTC", "NFLX", "NVDA", "AMD", "BABA", "T", "GS", "NKE", "WFC", "BA",
27
- "MCD", "CVX", "BMY", "GS", "IBM", "GE", "DELL", "CAT", "XLC", "LMT", "TMO", "RTX",
28
- "ZTS", "MDT", "AMAT", "SBUX", "SPGI", "PYPL", "CVS", "UNP", "MO", "CSX", "UPS", "LLY",
29
- "HUM", "C", "ADBE", "LULU", "PLD", "MS", "USB", "TGT", "CCI", "SYK", "BAX", "VRTX",
30
- "ADP", "FIS", "AMGN", "FDX", "ISRG", "AIG", "SCHW", "TRV", "ACN", "MCO", "AON", "EXC",
31
- "MDLZ", "REGN", "EOG", "INTU", "AMT", "AFL", "KLAC", "MELI", "COP", "CB", "ADSK", "LRCX",
32
- "F", "EQIX", "DHR", "TROW", "APD", "CHTR", "DOW", "NSC", "GE", "LHX", "ALL", "PXD"
 
33
  ]
34
  selected_stock = st.sidebar.selectbox("Choose a stock for analysis:", top_100_stocks)
35
 
@@ -112,60 +113,57 @@ else:
112
  # Investment advice for a specific stock
113
  st.header("Investment Advice or Strategy")
114
 
115
- # Get user input for stock symbol (e.g., "AAPL", "GOOGL", "MSFT")
116
- stock_symbol = selected_stock # input("Enter the stock symbol (e.g., AAPL, GOOGL, MSFT): ").upper()
117
-
118
- # Fetch stock data for the selected symbol
119
- stock = yf.Ticker(stock_symbol)
120
-
121
- # Get historical data for the last month
122
  data = stock.history(period="1mo")
123
 
124
- # Debugging: Show the data to check if it's being fetched correctly
125
- st.write(data)
126
-
127
  # Ensure data is available
128
  if len(data) < 2:
129
- st.warning(f"Not enough data available for {stock_symbol}. Please check the stock symbol.")
130
  else:
131
  # Get the latest closing price
132
  latest_close = data['Close'][-1]
133
 
134
- # Get the 50-day moving average (optional, can be adjusted)
135
  moving_avg_50 = data['Close'].rolling(window=50).mean().iloc[-1] if len(data) > 50 else None
136
 
137
- # Calculate stock volatility (standard deviation of returns)
138
- returns = data['Close'].pct_change()
139
- volatility = returns.std()
 
 
 
 
 
140
 
141
- # Prepare the investment advice based on the stock data and trends
142
  investment_advice = f"""
143
- Investment Strategy for {stock_symbol}:
144
  - Latest Closing Price: ${latest_close:.2f}
145
  """
146
 
147
- # Add the 50-day moving average only if it's not None
148
  if moving_avg_50 is not None:
149
- investment_advice += f"- 50-Day Moving Average: {moving_avg_50:.2f}\n"
150
  else:
151
  investment_advice += "- 50-Day Moving Average: Not available (insufficient data)\n"
152
 
153
  investment_advice += f"""
154
- - Stock Volatility (1-Month): {volatility:.2%}
155
- Based on recent stock data, {stock_symbol} is currently trading at ${latest_close:.2f}. The stock has shown a recent uptrend and is supported by strong fundamentals, making it a solid investment for long-term growth. However, the volatility (standard deviation of returns) indicates some price fluctuations in the short term, so investors should be cautious of potential short-term risks.
156
  ### Suggested Actions:
157
  1. **Consider Buying** if the stock is trading below its 50-day moving average, as this may indicate an undervalued opportunity for long-term investors.
158
  2. **Watch for Volatility**: If the stock experiences significant price swings, it may indicate market uncertainty or external factors affecting the stock.
159
- 3. **Monitor Earnings Reports**: {stock_symbol}'s quarterly earnings report will provide important insights into its revenue streams and future prospects.
160
- 4. **Long-term Investment**: Due to its strong market position and potential growth, {stock_symbol} remains a good candidate for long-term portfolios.
161
  ### Risks:
162
  - **Market Volatility**: As indicated by the volatility of returns, there could be some short-term price swings.
163
  - **Competition**: The competitive landscape in the industry is constantly evolving, which could impact future performance.
164
  ### Expected Benefits:
165
- - **Growth Potential**: {stock_symbol}'s growth in its core business or new ventures should continue to drive long-term stock price appreciation.
166
  - **Strong Cash Flow**: The company’s significant cash reserves may allow for innovation, stock buybacks, and dividend payments to shareholders.
167
- In conclusion, {stock_symbol} represents a good long-term investment, but investors should be mindful of its short-term volatility.
168
  """
169
 
170
- # Display the investment strategy in a readable format
171
  st.write(investment_advice)
 
4
  import requests
5
  from bs4 import BeautifulSoup
6
  import xml.etree.ElementTree as ET
7
+ import numpy as np
8
 
9
  # Set up the models for Named Entity Recognition, Sentiment Analysis, and Text Generation
10
  ner_model = "Cassie-0121/fin-bert-finetuned-ner"
 
21
  # Sidebar for selecting stock
22
  st.sidebar.header("Select Stock for Analysis")
23
  top_100_stocks = [
24
+ "AAPL", "MSFT", "GOOGL", "AMZN", "TSLA", "META", "NVDA", "BRK-B", "JNJ", "JPM",
25
+ "V", "PG", "UNH", "DIS", "MA", "HD", "BAC", "XOM", "VZ", "PFE",
26
+ "KO", "PEP", "MRK", "WMT", "CSCO", "ABT", "CMCSA", "ADBE", "NKE", "CRM",
27
+ "T", "INTC", "ORCL", "IBM", "AVGO", "TXN", "LLY", "NFLX", "QCOM", "COST",
28
+ "MCD", "HON", "PM", "BMY", "WBA", "DHR", "UNP", "RTX", "ACN", "UPS",
29
+ "LOW", "CAT", "SCHW", "SPGI", "LIN", "NEE", "CVS", "MDT", "INTU", "BLK",
30
+ "GS", "AMT", "MS", "DE", "CI", "BA", "C", "ZTS", "PLD", "GE",
31
+ "NOW", "MO", "SBUX", "AMGN", "SYK", "MMM", "ADP", "TGT", "DUK", "SO",
32
+ "BKNG", "CB", "ANTM", "AXP", "BDX", "ISRG", "TJX", "MMC", "APD", "NSC",
33
+ "USB", "ECL", "CL", "CCI", "WM", "PGR", "MDLZ", "EQIX", "LMT", "ATVI"
34
  ]
35
  selected_stock = st.sidebar.selectbox("Choose a stock for analysis:", top_100_stocks)
36
 
 
113
  # Investment advice for a specific stock
114
  st.header("Investment Advice or Strategy")
115
 
116
+ # Fetch stock data for the last month to calculate volatility
117
+ stock = yf.Ticker(selected_stock)
 
 
 
 
 
118
  data = stock.history(period="1mo")
119
 
 
 
 
120
  # Ensure data is available
121
  if len(data) < 2:
122
+ st.warning(f"Not enough data available for {selected_stock}. Please check the stock symbol.")
123
  else:
124
  # Get the latest closing price
125
  latest_close = data['Close'][-1]
126
 
127
+ # Get the 50-day moving average (if enough data is available)
128
  moving_avg_50 = data['Close'].rolling(window=50).mean().iloc[-1] if len(data) > 50 else None
129
 
130
+ # Calculate daily returns
131
+ data['Daily Return'] = data['Close'].pct_change()
132
+
133
+ # Calculate daily volatility (standard deviation of daily returns)
134
+ daily_volatility = data['Daily Return'].std()
135
+
136
+ # Annualize the daily volatility to match Yahoo Finance's convention
137
+ annualized_volatility = daily_volatility * np.sqrt(252)
138
 
139
+ # Prepare the investment advice based on stock data and trends
140
  investment_advice = f"""
141
+ Investment Strategy for {selected_stock}:
142
  - Latest Closing Price: ${latest_close:.2f}
143
  """
144
 
145
+ # Add the 50-day moving average only if it's available
146
  if moving_avg_50 is not None:
147
+ investment_advice += f"- 50-Day Moving Average: ${moving_avg_50:.2f}\n"
148
  else:
149
  investment_advice += "- 50-Day Moving Average: Not available (insufficient data)\n"
150
 
151
  investment_advice += f"""
152
+ - Stock Volatility (Annualized 1-Month): {annualized_volatility:.2%}
153
+ Based on recent stock data, {selected_stock} is currently trading at ${latest_close:.2f}. The stock has shown a recent uptrend and is supported by strong fundamentals, making it a solid investment for long-term growth. However, the volatility indicates some price fluctuations in the short term, so investors should be cautious of potential short-term risks.
154
  ### Suggested Actions:
155
  1. **Consider Buying** if the stock is trading below its 50-day moving average, as this may indicate an undervalued opportunity for long-term investors.
156
  2. **Watch for Volatility**: If the stock experiences significant price swings, it may indicate market uncertainty or external factors affecting the stock.
157
+ 3. **Monitor Earnings Reports**: {selected_stock}'s quarterly earnings report will provide important insights into its revenue streams and future prospects.
158
+ 4. **Long-term Investment**: Due to its strong market position and potential growth, {selected_stock} remains a good candidate for long-term portfolios.
159
  ### Risks:
160
  - **Market Volatility**: As indicated by the volatility of returns, there could be some short-term price swings.
161
  - **Competition**: The competitive landscape in the industry is constantly evolving, which could impact future performance.
162
  ### Expected Benefits:
163
+ - **Growth Potential**: {selected_stock}'s growth in its core business or new ventures should continue to drive long-term stock price appreciation.
164
  - **Strong Cash Flow**: The company’s significant cash reserves may allow for innovation, stock buybacks, and dividend payments to shareholders.
165
+ In conclusion, {selected_stock} is a strong stock with long-term growth potential, but investors should monitor market trends and the stock's volatility to time their investments effectively.
166
  """
167
 
168
+ # Display the generated investment strategy
169
  st.write(investment_advice)