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(): # Ensure the ratio exists in the DataFrame if ratio in index_averages.index and value is not None: average = index_averages.loc[ratio]['Average'] # Default interpretation for most ratios (higher = overvalued) interpretation = 'Overvalued' if value > average else 'Undervalued' # Invert interpretation for specific ratios like P/B Ratio, Book-to-Market Ratio if ratio in ['Book-to-Market Ratio']: # Add any other ratios where higher means undervalued interpretation = 'Undervalued' if value > average else 'Overvalued' comparison[ratio] = f"{interpretation} (Your Ratio: {value}, S&P 500 Avg: {average})" else: comparison[ratio] = 'N/A' 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"Valuation Comparison for {ticker_symbol}:") for ratio, result in comparison.items(): st.write(f"{ratio}: {result}")