JPBianchi commited on
Commit
9bfd9bf
1 Parent(s): b312ced

Initialization

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