missbaj commited on
Commit
9c55c03
·
verified ·
1 Parent(s): 5ae1e74
Files changed (1) hide show
  1. app.py +166 -0
app.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import matplotlib.pyplot as plt
2
+ import streamlit as st
3
+ import pandas as pd
4
+ import numpy as np
5
+ import yfinance as yf
6
+ import plotly.express as px
7
+ import plotly.graph_objects as go
8
+
9
+ from sklearn.preprocessing import MinMaxScaler
10
+ from tensorflow.keras.models import Sequential
11
+ from tensorflow.keras.layers import Activation, Dense, Dropout, LSTM
12
+ from datetime import date, datetime, timedelta
13
+ from stocknews import StockNews
14
+
15
+
16
+
17
+ # --- SIDEBAR CODE
18
+ ticker = st.sidebar.selectbox('Select your Crypto', ["BTC-USD", "ETH-USD"])
19
+
20
+ start_date = st.sidebar.date_input('Start Date', date.today() - timedelta(days=365))
21
+ end_date = st.sidebar.date_input('End Date')
22
+
23
+
24
+ # --- MAIN PAGE
25
+ st.header('Cryptocurrency Prediction')
26
+
27
+ col1, col2, = st.columns([1,9])
28
+ with col1:
29
+ st.image('icons/'+ ticker +'.png', width=75)
30
+ with col2:
31
+ st.write(f" ## { ticker}")
32
+
33
+ ticker_obj = yf.Ticker(ticker)
34
+
35
+
36
+ # --- CODE
37
+
38
+ model_data = ticker_obj.history(interval='1h', start=start_date, end=end_date)
39
+
40
+ # Extract the 'close' column for prediction
41
+ target_data = model_data["Close"].values.reshape(-1, 1)
42
+
43
+ # Normalize the target data
44
+ scaler = MinMaxScaler()
45
+ target_data_normalized = scaler.fit_transform(target_data)
46
+
47
+ # Normalize the input features
48
+ input_features = ['Open', 'High', 'Low', 'Volume']
49
+ input_data = model_data[input_features].values
50
+ input_data_normalized = scaler.fit_transform(input_data)
51
+
52
+ def build_lstm_model(input_data, output_size, neurons, activ_func='linear', dropout=0.2, loss='mse', optimizer='adam'):
53
+ model = Sequential()
54
+ model.add(LSTM(neurons, input_shape=(input_data.shape[1], input_data.shape[2])))
55
+ model.add(Dropout(dropout))
56
+ model.add(Dense(units=output_size))
57
+ model.add(Activation(activ_func))
58
+
59
+ model.compile(loss=loss, optimizer=optimizer)
60
+
61
+ return model
62
+
63
+
64
+ # Hyperparameters
65
+ np.random.seed(245)
66
+ window_len = 10
67
+ split_ratio = 0.8 # Ratio of training set to total data
68
+ zero_base = True
69
+ lstm_neurons = 50
70
+ epochs = 100
71
+ batch_size = 128 #32
72
+ loss = 'mean_squared_error'
73
+ dropout = 0.24
74
+ optimizer = 'adam'
75
+
76
+ def extract_window_data(input_data, target_data, window_len):
77
+ X = []
78
+ y = []
79
+ for i in range(len(input_data) - window_len):
80
+ X.append(input_data[i : i + window_len])
81
+ y.append(target_data[i + window_len])
82
+ return np.array(X), np.array(y)
83
+
84
+ X, y = extract_window_data(input_data_normalized, target_data_normalized, window_len)
85
+
86
+
87
+ # Split the data into training and testing sets
88
+ split_ratio = 0.8 # Ratio of training set to total data
89
+ split_index = int(split_ratio * len(X))
90
+
91
+ X_train, X_test = X[:split_index], X[split_index:]
92
+ y_train, y_test = y[:split_index], y[split_index:]
93
+
94
+ # Creating model
95
+ model = build_lstm_model(X_train, output_size=1, neurons=lstm_neurons, dropout=dropout, loss=loss, optimizer=optimizer)
96
+
97
+ # Saved Weights
98
+ file_path = "./LSTM_" + ticker + "_weights.h5"
99
+
100
+ # Loads the weights
101
+ model.load_weights(file_path)
102
+
103
+ # Step 4: Make predictions
104
+ preds = model.predict(X_test)
105
+ y_test = y[split_index:]
106
+
107
+ # Normalize the target data
108
+ scaler = MinMaxScaler()
109
+ target_data_normalized = scaler.fit_transform(target_data)
110
+
111
+ # Inverse normalize the predictions
112
+ preds = preds.reshape(-1, 1)
113
+ y_test = y_test.reshape(-1, 1)
114
+ preds = scaler.inverse_transform(preds)
115
+ y_test = scaler.inverse_transform(y_test)
116
+
117
+ fig = px.line(x=model_data.index[-len(y_test):],
118
+ y=[y_test.flatten(), preds.flatten()])
119
+ newnames = {'wide_variable_0':'Real Values', 'wide_variable_1': 'Predictions'}
120
+ fig.for_each_trace(lambda t: t.update(name = newnames[t.name],
121
+ legendgroup = newnames[t.name],
122
+ hovertemplate = t.hovertemplate.replace(t.name, newnames[t.name])))
123
+ fig.update_layout(
124
+ xaxis_title="Date",
125
+ yaxis_title=ticker+" Price",
126
+ legend_title=" ")
127
+ st.write(fig)
128
+
129
+
130
+ # --- INFO BUBBLE
131
+
132
+ about_data, news = st.tabs(["About", "News"])
133
+
134
+ with about_data:
135
+ # Candlestick
136
+ raw_data = ticker_obj.history(start=start_date, end=end_date)
137
+ fig = go.Figure(data=[go.Candlestick(x=raw_data.index,
138
+ open=raw_data['Open'],
139
+ high=raw_data['High'],
140
+ low=raw_data['Low'],
141
+ close=raw_data['Close'])])
142
+ fig.update_layout(
143
+ title=ticker + " candlestick : Open, High, Low and Close",
144
+ yaxis_title=ticker + ' Price')
145
+ st.plotly_chart(fig)
146
+
147
+ # Table
148
+ history_data = raw_data.copy()
149
+
150
+ # Formating index Date
151
+ history_data.index = pd.to_datetime(history_data.index, format='%Y-%m-%d %H:%M:%S').date
152
+ history_data.index.name = "Date"
153
+ history_data.sort_values(by='Date', ascending=False, inplace=True)
154
+ st.write(history_data)
155
+
156
+
157
+ with news:
158
+ sNews = StockNews(ticker, save_news=False)
159
+ sNews_df = sNews.read_rss()
160
+
161
+ # Showing most recent news
162
+ for i in range(10):
163
+ st.subheader(f"{i+1} - {sNews_df['title'][i]}")
164
+ st.write(sNews_df['summary'][i])
165
+ date_object = datetime.strptime(sNews_df['published'][i], '%a, %d %b %Y %H:%M:%S %z')
166
+ st.write(f"_{date_object.strftime('%A')}, {date_object.date()}_")