Spaces:
Build error
Build error
| import streamlit as st | |
| import yfinance as yf | |
| import pandas as pd | |
| import matplotlib.pyplot as plt | |
| st.title('Stock vs S&P 500 and Dow Jones Comparison') | |
| # User input | |
| user_stock = st.text_input('Enter a stock symbol (e.g., AAPL, TSLA, MSFT)', 'MAR') | |
| if user_stock: | |
| tickers = [user_stock.upper(), '^GSPC', '^DJI'] | |
| try: | |
| # Download past 1 year of daily data | |
| data = yf.download(tickers, period='1y', interval='1d') | |
| # Check if user stock symbol returned data | |
| if data.empty or user_stock.upper() not in data.columns.get_level_values(1): | |
| st.error('Not a valid stock symbol') | |
| else: | |
| # If MultiIndex, focus on 'Close' prices | |
| if isinstance(data.columns, pd.MultiIndex): | |
| close_prices = data['Close'] | |
| else: | |
| close_prices = data | |
| # Normalize (start at 100) | |
| normalized = close_prices / close_prices.iloc[0] * 100 | |
| # Plot | |
| fig, ax = plt.subplots(figsize=(12, 6)) | |
| for column in normalized.columns: | |
| ax.plot(normalized.index, normalized[column], label=column) | |
| ax.set_title(f'{user_stock.upper()} vs S&P 500 vs Dow Jones (Past 1 Year)') | |
| ax.set_xlabel('Date') | |
| ax.set_ylabel('Normalized Price (Start = 100)') | |
| ax.legend() | |
| ax.grid(True) | |
| st.pyplot(fig) | |
| except Exception as e: | |
| st.error('Not a valid stock symbol') |