shaheerawan3 commited on
Commit
f535ff8
·
verified ·
1 Parent(s): 4091fed

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +32 -37
app.py CHANGED
@@ -1,20 +1,21 @@
1
  import streamlit as st
2
  from datetime import date
3
  import yfinance as yf
4
- import pandas as pd # Importing pandas to avoid NameError
5
  from prophet import Prophet
6
  from prophet.plot import plot_plotly
7
- from plotly import graph_objs as go
 
8
 
9
  # Constants for date range
10
  START = "2015-01-01"
11
  TODAY = date.today().strftime("%Y-%m-%d")
12
 
13
  # Streamlit app title
14
- st.title('Stock & Cryptocurrency Forecast App')
15
 
16
  # Stock and cryptocurrency selection
17
- assets = ('GOOG', 'AAPL', 'MSFT', 'GME', 'BTC-USD', 'ETH-USD') # Added BTC and ETH
18
  selected_asset = st.selectbox('Select dataset for prediction', assets)
19
 
20
  # Years of prediction slider
@@ -39,38 +40,24 @@ st.write(data.tail())
39
 
40
  # Check if 'Close' column exists before converting
41
  if 'Close' in data.columns:
42
- # Check data types of the DataFrame
43
- st.write("Data Types:")
44
- st.write(data.dtypes)
45
-
46
- # Display unique values in the 'Close' column for debugging (accessing directly)
47
- unique_close_values = data['Close'].unique() # Accessing directly without pd.Series
48
- st.write("Unique values in 'Close' column:")
49
- st.write(unique_close_values)
50
-
51
  # Ensure 'Close' prices are numeric and handle any missing values
52
  try:
53
- # Convert to numeric with coercion for invalid parsing
54
  data['Close'] = pd.to_numeric(data['Close'], errors='coerce')
55
- # Drop rows with NaN values in 'Close'
56
  data.dropna(subset=['Close'], inplace=True)
57
  except Exception as e:
58
  st.error(f"Error converting 'Close' prices to numeric: {e}")
59
- else:
60
- st.error("The 'Close' column is missing from the data. Please check the selected asset.")
61
 
62
- # Check if there is valid data after processing
63
- if not data.empty and 'Close' in data.columns:
64
- # Plot raw data function
65
- def plot_raw_data():
66
- fig = go.Figure()
67
- fig.add_trace(go.Scatter(x=data['Date'], y=data['Open'], name="Open Price", line=dict(color='blue')))
68
- fig.add_trace(go.Scatter(x=data['Date'], y=data['Close'], name="Close Price", line=dict(color='orange')))
69
- fig.layout.update(title_text='Time Series Data with Rangeslider', xaxis_rangeslider_visible=True)
70
- st.plotly_chart(fig)
71
-
72
- # Call the plotting function if there's enough data
73
- plot_raw_data()
74
 
75
  # Prepare data for Prophet model
76
  df_train = data[['Date', 'Close']]
@@ -78,26 +65,34 @@ if not data.empty and 'Close' in data.columns:
78
 
79
  # Create and fit the Prophet model
80
  m = Prophet()
81
-
82
  try:
83
  m.fit(df_train)
84
-
85
  # Create future dataframe and make predictions
86
  future = m.make_future_dataframe(periods=period)
87
  forecast = m.predict(future)
88
 
 
 
 
 
 
 
 
 
89
  # Show forecast data and plot forecast
90
  st.subheader('Forecast Data')
91
  st.write(forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].tail())
92
- st.write(f'Forecast plot for the next {n_years} years')
93
-
94
- fig1 = plot_plotly(m, forecast)
95
- st.plotly_chart(fig1)
96
 
97
  # Show forecast components
98
  st.subheader("Forecast Components")
99
- fig2 = m.plot_components(forecast)
100
- st.plotly_chart(fig2)
101
 
102
  # Additional Insights: Displaying key metrics
103
  st.subheader("Key Metrics")
 
1
  import streamlit as st
2
  from datetime import date
3
  import yfinance as yf
4
+ import pandas as pd
5
  from prophet import Prophet
6
  from prophet.plot import plot_plotly
7
+ import plotly.graph_objects as go
8
+ from sklearn.metrics import mean_absolute_error, mean_squared_error
9
 
10
  # Constants for date range
11
  START = "2015-01-01"
12
  TODAY = date.today().strftime("%Y-%m-%d")
13
 
14
  # Streamlit app title
15
+ st.title('Advanced Stock & Cryptocurrency Forecast App')
16
 
17
  # Stock and cryptocurrency selection
18
+ assets = ('GOOG', 'AAPL', 'MSFT', 'GME', 'BTC-USD', 'ETH-USD')
19
  selected_asset = st.selectbox('Select dataset for prediction', assets)
20
 
21
  # Years of prediction slider
 
40
 
41
  # Check if 'Close' column exists before converting
42
  if 'Close' in data.columns:
 
 
 
 
 
 
 
 
 
43
  # Ensure 'Close' prices are numeric and handle any missing values
44
  try:
 
45
  data['Close'] = pd.to_numeric(data['Close'], errors='coerce')
 
46
  data.dropna(subset=['Close'], inplace=True)
47
  except Exception as e:
48
  st.error(f"Error converting 'Close' prices to numeric: {e}")
 
 
49
 
50
+ # Plot raw data using candlestick chart for better visualization
51
+ fig_candlestick = go.Figure(data=[go.Candlestick(x=data['Date'],
52
+ open=data['Open'],
53
+ high=data['High'],
54
+ low=data['Low'],
55
+ close=data['Close'])])
56
+ fig_candlestick.update_layout(title=f'{selected_asset} Price Data',
57
+ xaxis_title='Date',
58
+ yaxis_title='Price (USD)',
59
+ xaxis_rangeslider_visible=True)
60
+ st.plotly_chart(fig_candlestick)
 
61
 
62
  # Prepare data for Prophet model
63
  df_train = data[['Date', 'Close']]
 
65
 
66
  # Create and fit the Prophet model
67
  m = Prophet()
68
+
69
  try:
70
  m.fit(df_train)
71
+
72
  # Create future dataframe and make predictions
73
  future = m.make_future_dataframe(periods=period)
74
  forecast = m.predict(future)
75
 
76
+ # Calculate performance metrics on historical predictions (if available)
77
+ if len(df_train) > 30: # Ensure we have enough historical data to evaluate
78
+ historical_forecast = m.predict(df_train)
79
+ mae = mean_absolute_error(df_train['y'], historical_forecast['yhat'])
80
+ rmse = mean_squared_error(df_train['y'], historical_forecast['yhat', squared=False])
81
+ st.write(f"Mean Absolute Error (MAE): {mae:.2f}")
82
+ st.write(f"Root Mean Squared Error (RMSE): {rmse:.2f}")
83
+
84
  # Show forecast data and plot forecast
85
  st.subheader('Forecast Data')
86
  st.write(forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].tail())
87
+
88
+ # Plot forecast with confidence intervals
89
+ fig_forecast = plot_plotly(m, forecast)
90
+ st.plotly_chart(fig_forecast)
91
 
92
  # Show forecast components
93
  st.subheader("Forecast Components")
94
+ fig_components = m.plot_components(forecast)
95
+ st.plotly_chart(fig_components)
96
 
97
  # Additional Insights: Displaying key metrics
98
  st.subheader("Key Metrics")