os1187 commited on
Commit
85b7a89
1 Parent(s): ca45d0b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +56 -35
app.py CHANGED
@@ -1,49 +1,70 @@
1
  import streamlit as st
2
  import yfinance as yf
3
  import pandas as pd
4
- import numpy as np
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
  def fetch_stock_data(ticker_symbol):
 
7
  ticker = yf.Ticker(ticker_symbol)
8
- hist = ticker.history(period="1mo") # Fetch historical data for the last month
9
  info = ticker.info
10
 
11
- # Calculating some financial ratios
12
- try:
13
- pe_ratio = info['forwardPE']
14
- pb_ratio = info['priceToBook']
15
- ps_ratio = info.get('priceToSalesTrailing12Months', np.nan)
16
- debt_to_equity = info.get('debtToEquity', np.nan)
17
- roe = info.get('returnOnEquity', np.nan)
18
- earnings_yield = 1 / pe_ratio if pe_ratio else np.nan
19
- book_to_market_ratio = 1 / pb_ratio if pb_ratio else np.nan
20
-
21
- ratios = {
22
- 'P/E Ratio': pe_ratio,
23
- 'P/B Ratio': pb_ratio,
24
- 'P/S Ratio': ps_ratio,
25
- 'Debt to Equity': debt_to_equity,
26
- 'Return on Equity (ROE)': roe,
27
- 'Earnings Yield': earnings_yield,
28
- 'Book-to-Market Ratio': book_to_market_ratio,
29
- }
30
- except Exception as e:
31
- st.error(f"Failed to fetch data for {ticker_symbol}: {e}")
32
- ratios = {}
33
 
34
- return ratios
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
 
36
- # Streamlit UI
37
- st.title('Stock Financial Ratios Analysis')
38
 
39
- ticker_symbol = st.text_input('Enter Stock Ticker Symbol (e.g., AAPL, MSFT):').upper()
 
40
 
41
  if ticker_symbol:
42
- ratios = fetch_stock_data(ticker_symbol)
43
-
44
- if ratios:
 
45
  st.write(f"Financial Ratios for {ticker_symbol}:")
46
- for ratio, value in ratios.items():
47
- st.write(f"{ratio}: {value}")
48
- else:
49
- st.write("No data available for the given ticker symbol.")
 
 
 
1
  import streamlit as st
2
  import yfinance as yf
3
  import pandas as pd
4
+
5
+ # Predefined list of S&P 500 stocks for selection
6
+ stocks = ['AAPL', 'MSFT', 'AMZN', 'GOOGL', 'FB', 'BRK.B', 'JNJ', 'V', 'PG', 'JPM',
7
+ 'UNH', 'MA', 'INTC', 'VZ', 'HD', 'T', 'DIS', 'MRK', 'PFE', 'BAC',
8
+ 'KO', 'WMT', 'MCD', 'ABT', 'CSCO', 'PEP', 'NFLX', 'XOM', 'CVX', 'NKE',
9
+ 'LLY', 'ADBE', 'CMCSA', 'ORCL', 'CRM', 'TMO', 'ACN', 'ABBV', 'AVGO', 'TXN',
10
+ 'COST', 'DHR', 'MDT', 'NEE', 'PYPL', 'AMGN', 'HON', 'LIN', 'PM', 'BA',
11
+ 'UNP', 'IBM', 'QCOM', 'LMT', 'BMY', 'SBUX', 'MMM', 'GE', 'CAT', 'CVS',
12
+ 'WFC', 'SCHW', 'RTX', 'AMT', 'GS', 'DE', 'C', 'MS', 'GILD', 'UPS',
13
+ 'BLK', 'MO', 'MDLZ', 'INTU', 'TGT', 'AXP', 'ANTM', 'ISRG', 'SYK', 'CI',
14
+ 'PGR', 'BKNG', 'CL', 'SPGI', 'MMC', 'BDX', 'ADP', 'CME', 'USB', 'TJX',
15
+ 'ZTS', 'FIS', 'GM', 'CB', 'CHTR', 'PLD', 'SO', 'COP', 'DUK', 'EL']
16
+
17
+ # Assuming you have an updated CSV with S&P 500 averages for financial ratios
18
+ sp500_averages_path = 'sp500_averages.csv'
19
+
20
+ def load_sp500_averages(filepath):
21
+ # Load S&P 500 averages from a CSV file
22
+ return pd.read_csv(filepath, index_col='Ratio')
23
 
24
  def fetch_stock_data(ticker_symbol):
25
+ # Fetch financial data for a single stock
26
  ticker = yf.Ticker(ticker_symbol)
 
27
  info = ticker.info
28
 
29
+ pb_ratio = info.get('priceToBook')
30
+ book_to_market_ratio = 1 / pb_ratio if pb_ratio and pb_ratio > 0 else None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
 
32
+ financials = {
33
+ 'P/E Ratio': info.get('forwardPE'),
34
+ 'P/B Ratio': pb_ratio,
35
+ 'P/S Ratio': info.get('priceToSalesTrailing12Months'),
36
+ 'Debt to Equity Ratio': info.get('debtToEquity'),
37
+ 'Return on Equity': info.get('returnOnEquity'),
38
+ 'Book-to-Market Ratio': book_to_market_ratio,
39
+ }
40
+ return financials
41
+
42
+ def compare_to_index(stock_ratios, index_averages):
43
+ # Compare stock ratios to S&P 500 averages
44
+ comparison = {}
45
+ for ratio, value in stock_ratios.items():
46
+ average = index_averages.loc[ratio]['Average']
47
+ comparison[ratio] = 'Higher' if value > average else 'Lower'
48
+ return comparison
49
+
50
+ # Load S&P 500 averages
51
+ sp500_averages = load_sp500_averages(sp500_averages_path)
52
 
53
+ # User interface in Streamlit
54
+ st.title('S&P 500 Stock Comparison Tool')
55
 
56
+ # Selection of stock from predefined list
57
+ ticker_symbol = st.selectbox('Select a stock', options=stocks)
58
 
59
  if ticker_symbol:
60
+ with st.spinner(f'Fetching data for {ticker_symbol}...'):
61
+ stock_data = fetch_stock_data(ticker_symbol)
62
+ comparison = compare_to_index(stock_data, sp500_averages)
63
+
64
  st.write(f"Financial Ratios for {ticker_symbol}:")
65
+ for ratio, value in stock_data.items():
66
+ status = comparison.get(ratio, 'N/A')
67
+ st.write(f"{ratio}: {value} ({status} than S&P 500 average)")
68
+
69
+
70
+