Kaylah072001 commited on
Commit
6019fdd
Β·
verified Β·
1 Parent(s): fa86a67

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +22 -85
app.py CHANGED
@@ -1,103 +1,40 @@
1
- import sys
2
- import subprocess
3
-
4
- # Check and install required libraries
5
- required_libraries = ["streamlit", "transformers", "yfinance", "matplotlib", "Pillow"]
6
- for lib in required_libraries:
7
- try:
8
- __import__(lib)
9
- except ImportError:
10
- subprocess.check_call([sys.executable, "-m", "pip", "install", lib])
11
-
12
  import streamlit as st
13
  from transformers import pipeline
14
  from PIL import Image
15
- import yfinance as yf
16
- import matplotlib.pyplot as plt
17
  import io
18
 
19
- # Cache the stock data retrieval
20
- @st.cache_data
21
- def get_stock_data(ticker, start_date, end_date):
22
- return yf.download(ticker, start=start_date, end=end_date)
23
-
24
  # Load the image classification pipeline
25
  try:
26
- classifier = pipeline(task="image-classification", model="microsoft/resnet-50")
27
  except Exception as e:
28
  st.error(f"Error loading the model: {e}")
29
  st.stop()
30
 
31
  # Set up the Streamlit app title
32
- st.title("Stock Trend Analyzer: Bullish or Bearish? πŸ“ˆπŸ“‰")
33
-
34
- # Input for stock ticker
35
- ticker = st.text_input("Enter a stock ticker (e.g., AAPL, GOOGL):", "AAPL")
36
 
37
- # Date range selection
38
- col1, col2 = st.columns(2)
39
- start_date = col1.date_input("Start date")
40
- end_date = col2.date_input("End date")
41
 
42
- if st.button("Analyze"):
43
- # Fetch stock data
44
- with st.spinner("Fetching stock data..."):
45
- stock_data = get_stock_data(ticker, start_date, end_date)
46
 
47
- if stock_data.empty:
48
- st.error("No data available for the selected stock and date range.")
49
- else:
50
- # Create a plot of the stock data
51
- fig, ax = plt.subplots(figsize=(10, 6))
52
- ax.plot(stock_data.index, stock_data['Close'])
53
- ax.set_title(f"{ticker} Stock Price")
54
- ax.set_xlabel("Date")
55
- ax.set_ylabel("Price")
56
- ax.grid(True)
57
-
58
- # Save the plot to a buffer
59
- buf = io.BytesIO()
60
- fig.savefig(buf, format='png')
61
- buf.seek(0)
62
-
63
- # Convert the buffer to an image
64
- image = Image.open(buf)
65
-
66
- # Display the stock graph
67
- st.image(image, caption=f"{ticker} Stock Price", use_column_width=True)
68
-
69
- # Classify the image
70
- with st.spinner("Analyzing the trend..."):
71
- predictions = classifier(image)
72
-
73
- # Display the predictions
74
- st.header("Trend Analysis")
75
- for p in predictions[:2]: # Display top 2 predictions
76
- sentiment = "Bullish" if "up" in p['label'].lower() else "Bearish"
77
- confidence = round(p['score'] * 100, 1)
78
- st.subheader(f"{sentiment}: {confidence}%")
79
-
80
- # Add color-coded bars for visual representation
81
- color = "green" if sentiment == "Bullish" else "red"
82
- st.progress(confidence / 100, text=f"{sentiment} Confidence")
83
-
84
- # Additional analysis based on the stock data
85
- price_change = stock_data['Close'].iloc[-1] - stock_data['Close'].iloc[0]
86
- percent_change = (price_change / stock_data['Close'].iloc[0]) * 100
87
-
88
- st.subheader("Price Analysis")
89
- st.write(f"Price change: ${price_change:.2f}")
90
- st.write(f"Percent change: {percent_change:.2f}%")
91
 
92
- if percent_change > 0:
93
- st.success(f"The stock price increased by {percent_change:.2f}% over the selected period.")
94
- elif percent_change < 0:
95
- st.error(f"The stock price decreased by {abs(percent_change):.2f}% over the selected period.")
96
- else:
97
- st.info("The stock price remained unchanged over the selected period.")
98
 
99
  else:
100
- st.info("Enter a stock ticker and select a date range to analyze the trend.")
101
-
102
- # Clean up matplotlib figures
103
- plt.close('all')
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
  from transformers import pipeline
3
  from PIL import Image
 
 
4
  import io
5
 
 
 
 
 
 
6
  # Load the image classification pipeline
7
  try:
8
+ classifier = pipeline(task="image-classification", model="julien-c/bullish-or-bearish")
9
  except Exception as e:
10
  st.error(f"Error loading the model: {e}")
11
  st.stop()
12
 
13
  # Set up the Streamlit app title
14
+ st.title("Stock Chart Analyzer: Bullish or Bearish? πŸ“ˆπŸ“‰")
 
 
 
15
 
16
+ # File uploader for image input
17
+ uploaded_file = st.file_uploader("Upload a stock chart image", type=["jpg", "jpeg", "png"])
 
 
18
 
19
+ if uploaded_file is not None:
20
+ # Display the uploaded image
21
+ image = Image.open(uploaded_file)
22
+ st.image(image, caption="Uploaded Stock Chart", use_column_width=True)
23
 
24
+ # Classify the image
25
+ with st.spinner("Analyzing the trend..."):
26
+ predictions = classifier(image)
27
+
28
+ # Display the predictions
29
+ st.header("Trend Analysis")
30
+ for p in predictions:
31
+ sentiment = p['label'].split('_')[0].capitalize()
32
+ confidence = round(p['score'] * 100, 1)
33
+ st.subheader(f"{sentiment}: {confidence}%")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
 
35
+ # Add color-coded bars for visual representation
36
+ color = "green" if sentiment == "Bullish" else "red"
37
+ st.progress(confidence / 100, text=f"{sentiment} Confidence")
 
 
 
38
 
39
  else:
40
+ st.info("Please upload a stock chart image to analyze the trend.")