import pandas as pd import numpy as np import math import matplotlib.pyplot as plt from sklearn.preprocessing import MinMaxScaler from sklearn.metrics import mean_squared_error import tensorflow as tf from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense from tensorflow.keras.layers import LSTM import gradio as gr import yfinance as yf def get_ans(inp): tickers = yf.Tickers(inp) x = tickers.tickers[inp].history(period="15y") df = x df.reset_index(inplace=True) df1 = df.reset_index()['Close'] df['Date'] = pd.to_datetime(df['Date']) scaler = MinMaxScaler(feature_range=(0, 1)) df1 = scaler.fit_transform(np.array(df1).reshape(-1, 1)) training_size = int(len(df1) * 0.65) test_size = len(df1) - training_size train_data, test_data = df1[0:training_size, :], df1[training_size:len(df1), :1] def create_dataset(dataset, time_step=1): dataX, dataY = [], [] for i in range(len(dataset) - time_step - 1): a = dataset[i:(i + time_step), 0] dataX.append(a) dataY.append(dataset[i + time_step, 0]) return np.array(dataX), np.array(dataY) time_step = 100 X_train, y_train = create_dataset(train_data, time_step) X_test, ytest = create_dataset(test_data, time_step) X_train = X_train.reshape(X_train.shape[0], X_train.shape[1], 1) X_test = X_test.reshape(X_test.shape[0], X_test.shape[1], 1) model = Sequential() model.add(LSTM(50, return_sequences=True, input_shape=(100, 1))) model.add(LSTM(50, return_sequences=True)) model.add(LSTM(50)) model.add(Dense(1)) model.compile(loss='mean_squared_error', optimizer='adam') model.fit(X_train,y_train,validation_data=(X_test,ytest),epochs=2,batch_size=64,verbose=1) train_predict=model.predict(X_train) test_predict=model.predict(X_test) train_predict=scaler.inverse_transform(train_predict) test_predict=scaler.inverse_transform(test_predict) look_back=100 trainPredictPlot = np.empty_like(df1) trainPredictPlot[:, :] = np.nan trainPredictPlot[look_back:len(train_predict)+look_back, :] = train_predict # shift test predictions for plotting testPredictPlot = np.empty_like(df1) testPredictPlot[:, :] = np.nan testPredictPlot[len(train_predict)+(look_back*2)+1:len(df1)-1, :] = test_predict # plot baseline and predictions plt.plot(scaler.inverse_transform(df1)) plt.plot(trainPredictPlot) plt.plot(testPredictPlot) x_input=test_data[341:].reshape(1,-1) resize_var = x_input.size temp_input=list(x_input) temp_input=temp_input[0].tolist() lst_output=[] n_steps=100 i=0 while(i<30): if(len(temp_input)>100): #print(temp_input) x_input=np.array(temp_input[1:]) # print("{} day input {}".format(i,x_input)) x_input=x_input.reshape(1,-1) x_input = x_input.reshape((1, x_input.size, 1)) #print(x_input) yhat = model.predict(x_input, verbose=0) # print("{} day output {}".format(i,yhat)) temp_input.extend(yhat[0].tolist()) temp_input=temp_input[1:] #print(temp_input) lst_output.extend(yhat.tolist()) i=i+1 else: x_input = x_input.reshape((1, n_steps,1)) yhat = model.predict(x_input, verbose=0) # print(yhat[0]) temp_input.extend(yhat[0].tolist()) # print(len(temp_input)) lst_output.extend(yhat.tolist()) i=i+1 day_new=np.arange(1,101) day_pred=np.arange(101,131) df3=df1. tolist() df3.extend (lst_output) len_lis = len(lst_output) df3=pd.DataFrame(df3, columns=['Values']) df3['index']=range(1, len(df3) + 1) lst_output = pd.DataFrame(lst_output, columns=["Values"]) lst_output['index']=range(1, len(lst_output) + 1) return plt, gr.update(visible=True,value=df, x="Date",y="Open", height=500, width=800),gr.update(visible=True,value=df[-300:], x="Date",y="Open", height=500, width=800),gr.update(visible=True,value=df[-30:], x="Date",y="Open", height=500, width=800), max(np.asarray(df['Open'])), min(np.asarray(df['Open'])), max(np.asarray(df['Open'])[-300:]), min(np.asarray(df['Open'][-300:])), max(np.asarray(df['Open'])[-30:]), min(np.asarray(df['Open'][-30:])), lst_output["Values"][0], gr.update(visible=True,value=lst_output, x="index",y="Values", height=500, width=800), gr.update(visible=True,value=df3, x="index",y="Values", height=500, width=800), gr.update(visible=True,value=df3[-300:], x="index",y="Values", height=500, width=800) with gr.Blocks() as demo: with gr.Row().style(equal_height=True): with gr.Column(): gr.Markdown("

BI Project

") gr.Markdown("

Give the Ticker of the company you want to analyse. We will provide complete insights on the given company.

") with gr.Row(): with gr.Column(): Name_of_the_company = gr.Textbox(placeholder="eg, GOOG / MSFT / AAPL", label="TICKER of the company") btn = gr.Button("ANALYSE") gr.Markdown("

Analysis

") gr.Markdown("

Regression Trends of Price

") mp = gr.Plot() gr.Markdown("

Price over time

") with gr.Tab("All Time"): mp1 = gr.LinePlot(visible=False, label="All time", height=1000, width=1000) with gr.Row(): Max_all = gr.Textbox(placeholder="The Maximum price the stock has ever reached", label='Maximum of all time') Min_all = gr.Textbox(placeholder="The Minimum price the stock has ever reached", label="Minimum of all time") with gr.Tab("Past year"): mp2 = gr.LinePlot(visible=False, label="Last year") with gr.Row(): Max_year = gr.Textbox(placeholder="The Maximum price for the last year", label='Maximum') Min_year = gr.Textbox(placeholder="The Minimum price for the last year", label="Minimum") with gr.Tab("Past few Days"): mp3 = gr.LinePlot(visible=False, label="Past few Days") with gr.Row(): Max_rec = gr.Textbox(placeholder="The Maximum price for the last few days", label='Recent Maximum') Min_rec = gr.Textbox(placeholder="The Minimum price for the last few days", label="Recent Minimum") gr.Markdown("

Predictive Analysis

") Next_day = gr.Textbox(placeholder="Predicted price for tomorrow", label="Predicted price for Tomorrow") Next_plot = gr.LinePlot(visible=False) Next_plot_all = gr.LinePlot(visible=False) Next_plot_year = gr.LinePlot(visible=False) btn.click(get_ans, inputs=Name_of_the_company, outputs= [mp,mp1,mp2,mp3, Max_all, Min_all,Max_year, Min_year, Max_rec, Min_rec, Next_day, Next_plot, Next_plot_all, Next_plot_year]) demo.launch(inline = False)