Handling Exception Error


Can someone help me out with this , here I have used try and exception to catch an error but my program executes after this , hence other error comes up.
Any solution to this?

#Importing all the library
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import time
import datetime
from datetime import datetime, date, time
import yfinance as yf
plt.style.use('fivethirtyeight')
from keras.models import load_model
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import accuracy_score
import streamlit as st

#Loading the model
model = load_model('stock_prediction_model.h5')
start = '2000-01-01'
end = '2021-07-31'

#Start
st.title('Stock Prediction App')
user_input = st.text_input('Enter the stock for which you wanna predict', 'AAPL')
quote = yf.download(user_input, start, end)

#Describing the Data
st.subheader('Data from 2000 - 2021')
st.write(quote.describe())

#Choosing the date
st.header("Pick Date")
date = st.text_input('Date in format(YYYY-MM-DDDD)', '2021-07-20')

#Actual quote
quote2 = yf.download(user_input,start=date, end=date)
st.write('Actual Close' , quote2['Close'])

#Getting the predicted quote
quote_p = yf.download(user_input,start=date, end=date)
new_quote_p = quote_p.filter(['Close']) 
last_100_days = new_quote_p[-100:].values
scalar = MinMaxScaler(feature_range=(0,1))
try:
    last_100_days_scaled = scalar.fit_transform(last_100_days)
except ValueError:
    st.error("Please enter a week day since the stock market is closed on the weekends.")
X_test = []
X_test.append(last_100_days_scaled)
X_test = np.array(X_test)
X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))
pred_price = model.predict(X_test)
pred_price = scalar.inverse_transform(pred_price)
predicted = pred_price
predicted_df = pd.DataFrame(predicted , columns = ['Close'] , index = quote_p.index )
st.write('Predicted Close' , predicted_df)

#Visualisation
st.subheader('Closing Price vs Time')
fig = plt.figure(figsize=(12 , 6))
plt.plot(quote.Close , linewidth = 3)
plt.xlabel("Time")
plt.ylabel("Price")
plt.legend(["Closing Price"], loc ="lower right")
st.pyplot(fig)

st.subheader('Closing Price vs Moving Average of 100 days')
ma100 = quote.Close.rolling(100).mean()
fig = plt.figure(figsize=(12 , 6))
plt.plot(ma100 , linewidth = 3)
plt.plot(quote.Close , linewidth = 3)
plt.xlabel("Time")
plt.ylabel("Price")
plt.legend(["Closing Price", "Moivng Average 100"], loc ="lower right")
st.pyplot(fig)

st.subheader('Closing Price vs Moving Average of 100 days vs Moving Average of 200 days')
ma100 = quote.Close.rolling(100).mean()
ma200 = quote.Close.rolling(200).mean()
fig2 = plt.figure(figsize=(12 , 6))
plt.plot(quote.Close , linewidth = 3 , color= 'blue')
plt.plot(ma100 , linewidth = 3 , color = 'red')
plt.plot(ma200 , linewidth = 3 , color = 'green')
plt.xlabel("Time")
plt.ylabel("Price")
plt.legend(["Closing Price" , "Moving Average 100", "Moving Average 200"], loc ="lower right")
st.pyplot(fig2)

#Prediction of the future prices
data_training = pd.DataFrame(quote['Close'][0:int(len(quote)*0.70)])
data_testing = pd.DataFrame(quote['Close'][int(len(quote)*0.70):int(len(quote))])   
scaler = MinMaxScaler(feature_range=(0,1))
data_training_array = scaler.fit_transform(data_training)
past_100_days = data_training.tail(100) #Last 100 days of data from training dataset
final_quote = past_100_days.append(data_testing , ignore_index=True)
input_data = scaler.fit_transform(final_quote) #Scaling down the testing data in the range 0 and 1
x_test = []
y_test = []
for i in range(100,input_data.shape[0]):
  x_test.append(input_data[i-100 : i])
  y_test.append(input_data[i , 0])

x_test , y_test = np.array(x_test) , np.array(y_test)
y_predicted = model.predict(x_test)
scaler = scaler.scale_
scale_factor = 1/scaler
y_predicted = y_predicted * scale_factor
y_test = y_test * scale_factor

st.subheader('Predicted Price vs Original Price')
fig3 = plt.figure(figsize = (12 , 6))
plt.plot(y_test , 'blue' , label = 'Original Price')
plt.plot(y_predicted , 'red' , label = 'Predicted Price')
plt.xlabel("Time")
plt.ylabel("Price")
plt.legend(['Original Price', 'Predicted Price'], loc ="lower right")
st.pyplot(fig3)

Hi @Tony_Mafyd, Welcome to the community!

The error is caused because last_100_days_scaled is not being defined when a ValueError is caugth, but the variable is expected after the try-except block.

You could wrap the model creation and plots inside functions and include these in the try except block. Better would be to include some logic the make sure you’re not passing a weekend day into the yf.download function.

from datetime import date

date = st.date_input("Pick a date", value=date(2021, 5, 4))

# check if the datetime.date object is a weekday by calling the `weekday` method. 0 = monday, 6 = sunday
if date.weekday() < 5:
    date_str = date.strftime("%Y-%m-%d")
    quote_p = yf.download(user_input,start=date_str, end=date_str)

    # run the rest of your code here
    # ....

else:
    st.error("Please enter a week day since the stock market is closed on the weekends.")

Thank you so much for the help , the app is working perfectly now.

1 Like