Spaces:
Build error
Build error
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103import sysimport subprocess# Check and install required librariesrequired_libraries = ["streamlit", "transformers", "yfinance", "matplotlib", "Pillow"]for lib in required_libraries:try:__import__(lib)except ImportError:subprocess.check_call([sys.executable, "-m", "pip", "install", lib])import streamlit as stfrom transformers import pipelinefrom PIL import Imageimport yfinance as yfimport matplotlib.pyplot as pltimport io# Cache the stock data retrieval@st.cache_datadef get_stock_data(ticker, start_date, end_date):return yf.download(ticker, start=start_date, end=end_date)# Load the image classification pipelinetry:classifier = pipeline(task="image-classification", model="microsoft/resnet-50")except Exception as e:st.error(f"Error loading the model: {e}")st.stop()# Set up the Streamlit app titlest.title("Stock Trend Analyzer: Bullish or Bearish? ππ")# Input for stock tickerticker = st.text_input("Enter a stock ticker (e.g., AAPL, GOOGL):", "AAPL")# Date range selectioncol1, col2 = st.columns(2)start_date = col1.date_input("Start date")end_date = col2.date_input("End date")if st.button("Analyze"):# Fetch stock datawith st.spinner("Fetching stock data..."):stock_data = get_stock_data(ticker, start_date, end_date)if stock_data.empty:st.error("No data available for the selected stock and date range.")else:# Create a plot of the stock datafig, ax = plt.subplots(figsize=(10, 6))ax.plot(stock_data.index, stock_data['Close'])ax.set_title(f"{ticker} Stock Price")ax.set_xlabel("Date")ax.set_ylabel("Price")ax.grid(True)# Save the plot to a bufferbuf = io.BytesIO()fig.savefig(buf, format='png')buf.seek(0)# Convert the buffer to an imageimage = Image.open(buf)# Display the stock graphst.image(image, caption=f"{ticker} Stock Price", use_column_width=True)# Classify the imagewith st.spinner("Analyzing the trend..."):predictions = classifier(image)# Display the predictionsst.header("Trend Analysis")for p in predictions[:2]: # Display top 2 predictionssentiment = "Bullish" if "up" in p['label'].lower() else "Bearish"confidence = round(p['score'] * 100, 1)st.subheader(f"{sentiment}: {confidence}%")# Add color-coded bars for visual representationcolor = "green" if sentiment == "Bullish" else "red"st.progress(confidence / 100, text=f"{sentiment} Confidence")# Additional analysis based on the stock dataprice_change = stock_data['Close'].iloc[-1] - stock_data['Close'].iloc[0]percent_change = (price_change / stock_data['Close'].iloc[0]) * 100st.subheader("Price Analysis")st.write(f"Price change: ${price_change:.2f}")st.write(f"Percent change: {percent_change:.2f}%")if percent_change > 0:st.success(f"The stock price increased by {percent_change:.2f}% over the selected period.")elif percent_change < 0:st.error(f"The stock price decreased by {abs(percent_change):.2f}% over the selected period.")else:st.info("The stock price remained unchanged over the selected period.")else:st.info("Enter a stock ticker and select a date range to analyze the trend.")# Clean up matplotlib figuresplt.close('all')12345678910111213141516171819202122232425262728293031323334353637383940import streamlit as stfrom transformers import pipelinefrom PIL import Imageimport io# Load the image classification pipelinetry:classifier = pipeline(task="image-classification", model="julien-c/bullish-or-bearish")except Exception as e:st.error(f"Error loading the model: {e}")st.stop()# Set up the Streamlit app titlest.title("Stock Chart Analyzer: Bullish or Bearish? ππ")# File uploader for image inputuploaded_file = st.file_uploader("Upload a stock chart image", type=["jpg", "jpeg", "png"])if uploaded_file is not None:# Display the uploaded imageimage = Image.open(uploaded_file)st.image(image, caption="Uploaded Stock Chart", use_column_width=True)# Classify the imagewith st.spinner("Analyzing the trend..."):predictions = classifier(image)# Display the predictionsst.header("Trend Analysis")for p in predictions:sentiment = p['label'].split('_')[0].capitalize()confidence = round(p['score'] * 100, 1)st.subheader(f"{sentiment}: {confidence}%")# Add color-coded bars for visual representationcolor = "green" if sentiment == "Bullish" else "red"st.progress(confidence / 100, text=f"{sentiment} Confidence")else:st.info("Please upload a stock chart image to analyze the trend.")
app.py+22-85