ibrahim yıldız commited on
Commit
a575745
·
verified ·
1 Parent(s): f5e4a33

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +68 -0
  2. requirements.txt +0 -0
app.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pandas as pd
3
+ import streamlit as st
4
+ import plotly.express as px
5
+ from sklearn.model_selection import train_test_split
6
+ from sklearn import preprocessing
7
+ import yfinance as yf
8
+ from sklearn.linear_model import LinearRegression
9
+
10
+ # Streamlit app
11
+ st.title('CUSTOM Stock Price Prediction 💰')
12
+ st.write('This model predicts upon trends. It will not perform well in volatile history. setting the time frame "max" is recommended. Your predicted days value can not exceed the time frame days. Have fun!')
13
+ # Input widgets
14
+ stock = st.text_input('Stock tag', value='NVDA')
15
+ daysago = st.text_input('Time frame in days (write "max" for max time)', value='365')
16
+ forecast_out = st.number_input('Predicted days', value=180,min_value=1)
17
+ forecast_col = 'Close'
18
+
19
+ def prepare_data(df,forecast_col,forecast_out):
20
+ label = df[forecast_col].shift(-forecast_out) #creating new column called label with the last 5 rows are nan
21
+ X = np.array(df[[forecast_col]]) #creating the feature array
22
+ X = preprocessing.scale(X) #processing the feature array
23
+ X_lately = X[-forecast_out:] #creating the column i want to use later in the predicting method
24
+ X = X[:-forecast_out] # X that will contain the training and testing
25
+ label.dropna(inplace=True) #dropping na values
26
+ y = np.array(label) # assigning Y
27
+ X_train, X_test, Y_train, Y_test = train_test_split(X, y, test_size=0.2, random_state=42) #cross validation
28
+
29
+ response = [X_train,X_test , Y_train, Y_test , X_lately]
30
+ return response
31
+
32
+ # Button to trigger model generation and prediction
33
+ if st.button('Generate'):
34
+ # Fetch stock data
35
+ if daysago != 'max':
36
+ daysago = str(daysago) + 'd'
37
+
38
+ ticker = yf.Ticker(stock)
39
+ data = ticker.history(period=daysago)
40
+
41
+ X_train, X_test, Y_train, Y_test , X_lately =prepare_data(data,forecast_col,forecast_out); #calling the method were the cross validation and data preperation is in
42
+
43
+ # Model Generation
44
+ learner = LinearRegression()
45
+ learner.fit(X_train, Y_train)
46
+ score = learner.score(X_test, Y_test)
47
+ forecast = learner.predict(X_lately)
48
+ #st.write('Used Model:', selected_algorithm)
49
+ st.write('Accuracy Score:', score)
50
+
51
+ #GRAPH
52
+ # Create a DataFrame with future dates and predicted values
53
+ future_dates = pd.date_range(start=data.index[-1] + pd.Timedelta(days=1), periods=forecast_out, freq='D')
54
+ predicted_data = pd.DataFrame({'Date': future_dates, 'Predicted Close': forecast})
55
+
56
+ # Concatenate original data and predicted data
57
+ combined_data = pd.concat([data.rename(columns={'Close': 'Actual Close'}), predicted_data.set_index('Date')], axis=1)
58
+
59
+ # Plot original and predicted stock prices
60
+ fig = px.line(combined_data, x=combined_data.index, y=['Actual Close', 'Predicted Close'], title=f'Predicted {stock} Stock Prices')
61
+ fig.update_layout(xaxis_title='Date',yaxis_title='Price',legend_title_text='')
62
+
63
+ # Set line colors
64
+ fig.data[1].line.color = 'orange'
65
+
66
+ st.plotly_chart(fig)
67
+
68
+ st.write('Findings: I tried using pycaret.regression to model, interestingly the r2 score of KNeighborsRegressor() was always the highest, with 96%, but it clearly gave a wrong output. Methods other than Ridge, Lasso and Linear Regression seem to always fail so I decied to stick with Linear Regression despite its 88% acc. score. It is not always correct, if the stock price has lots of ups and downs, it wont be able to give a good estimate as the accuracy score often goes below 50%. The discrepancy can be understood by the disconnection between the lines actual close and predicted close. It needs deep learning to go ruther.')
requirements.txt ADDED
File without changes