os1187's picture
Update app.py
011359b verified
raw
history blame
3.04 kB
import streamlit as st
import yfinance as yf
import pandas as pd
# Predefined list of S&P 500 stocks for selection
stocks = ['AAPL', 'MSFT', 'AMZN', 'GOOGL', 'FB', 'BRK.B', 'JNJ', 'V', 'PG', 'JPM',
'UNH', 'MA', 'INTC', 'VZ', 'HD', 'T', 'DIS', 'MRK', 'PFE', 'BAC',
'KO', 'WMT', 'MCD', 'ABT', 'CSCO', 'PEP', 'NFLX', 'XOM', 'CVX', 'NKE',
'LLY', 'ADBE', 'CMCSA', 'ORCL', 'CRM', 'TMO', 'ACN', 'ABBV', 'AVGO', 'TXN',
'COST', 'DHR', 'MDT', 'NEE', 'PYPL', 'AMGN', 'HON', 'LIN', 'PM', 'BA',
'UNP', 'IBM', 'QCOM', 'LMT', 'BMY', 'SBUX', 'MMM', 'GE', 'CAT', 'CVS',
'WFC', 'SCHW', 'RTX', 'AMT', 'GS', 'DE', 'C', 'MS', 'GILD', 'UPS',
'BLK', 'MO', 'MDLZ', 'INTU', 'TGT', 'AXP', 'ANTM', 'ISRG', 'SYK', 'CI',
'PGR', 'BKNG', 'CL', 'SPGI', 'MMC', 'BDX', 'ADP', 'CME', 'USB', 'TJX',
'ZTS', 'FIS', 'GM', 'CB', 'CHTR', 'PLD', 'SO', 'COP', 'DUK', 'EL']
# Assuming you have an updated CSV with S&P 500 averages for financial ratios
sp500_averages_path = 'sp500_averages.csv'
def load_sp500_averages(filepath):
# Load the CSV without specifying an index column name
return pd.read_csv(filepath, header=0, names=['Ratio', 'Average']).set_index('Ratio')
def fetch_stock_data(ticker_symbol):
# Fetch financial data for a single stock
ticker = yf.Ticker(ticker_symbol)
info = ticker.info
pb_ratio = info.get('priceToBook')
book_to_market_ratio = 1 / pb_ratio if pb_ratio and pb_ratio > 0 else None
financials = {
'P/E Ratio': info.get('forwardPE'),
'P/B Ratio': pb_ratio,
'P/S Ratio': info.get('priceToSalesTrailing12Months'),
'Debt to Equity Ratio': info.get('debtToEquity'),
'Return on Equity': info.get('returnOnEquity'),
'Book-to-Market Ratio': book_to_market_ratio,
}
return financials
def compare_to_index(stock_ratios, index_averages):
comparison = {}
for ratio, value in stock_ratios.items():
# Check if the ratio exists in the index_averages DataFrame
if ratio in index_averages.index:
average = index_averages.loc[ratio]['Average']
comparison[ratio] = 'Higher' if value > average else 'Lower'
else:
comparison[ratio] = 'N/A' # Ratio not available in index averages
return comparison
# Load S&P 500 averages
sp500_averages = load_sp500_averages(sp500_averages_path)
# User interface in Streamlit
st.title('S&P 500 Stock Comparison Tool')
# Selection of stock from predefined list
ticker_symbol = st.selectbox('Select a stock', options=stocks)
if ticker_symbol:
with st.spinner(f'Fetching data for {ticker_symbol}...'):
stock_data = fetch_stock_data(ticker_symbol)
comparison = compare_to_index(stock_data, sp500_averages)
st.write(f"Financial Ratios for {ticker_symbol}:")
for ratio, value in stock_data.items():
status = comparison.get(ratio, 'N/A')
st.write(f"{ratio}: {value} ({status} than S&P 500 average)")