-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprice_app.py
167 lines (141 loc) · 4.92 KB
/
price_app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
import streamlit as st
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# %matplotlib inline
from pandas.plotting import register_matplotlib_converters
from datetime import datetime, timedelta
import base64
from app import read_preprocess, predict_lstm, predict_linreg
import plotly.express as px
import plotly.graph_objects as go
from PIL import Image
from sklearn.metrics import mean_absolute_error
register_matplotlib_converters()
plt.style.use("default")
# constants
DAYS_BACK = 200
WIN_LEN = 30
ALL_FEATURES = ["high", "low", "open", "volumefrom", "volumeto", "close"]
TARGET_COL = "close"
st.set_page_config(layout="wide")
st.title("Currency Excange Rate Prediction App")
st.markdown(
"""
This app retrieves currency prices for Bitcoin, USD, EUR, RUB from **min-api crypto compare**
and predicts the close exchange rate for several days in the future.
"""
)
expander_bar = st.beta_expander("About")
expander_bar.write(
"""
* **Team:** Evgenii Munin, Ilya Avilov, Orkhan Gadzhily, Nikolai Diakin, Andrei Starikov
* **Git Perository:** https://github.com/EvgeniiMunin/made-ml-hw4
* **Python libraries:** scikit-learn, keras, base64, streamlit, plotly, pandas, numpy, requests, json
* **Data source:** Data resource API is available at [min-api crypto compare](https://min-api.cryptocompare.com/data/histoday?fsym=BTC&tsym=CAD&limit=500)
"""
)
# href = f'<a href="https://github.com/EvgeniiMunin/made-ml-hw4">Git Perository</a>'
# expander_bar.markdown(href, unsafe_allow_html=True)
# define left column sidebar
col1 = st.sidebar
# add logo
st.sidebar.image(image=Image.open("logo.jpeg"), width=200)
# select currency
col1.header("Input Options")
currency_price_unit = col1.selectbox(
"Select currency for predict",
(
"BTC EUR",
"BTC RUB",
"BTC USD",
"EUR BTC",
"EUR USD",
"RUB BTC",
"USD BTC",
"USD EUR",
),
)
incur = currency_price_unit.split()[0]
outcur = currency_price_unit.split()[1]
print("check price unit: ", currency_price_unit, incur, outcur)
# select period
pred_horizon = col1.slider("Prediction horizon, days", min_value=1, max_value=3)
print("check pred horizon: ", pred_horizon)
# select calendar date
predict_from = col1.date_input("Predict from")
predict_from += timedelta(days=1)
print("check predict from: ", predict_from, type(predict_from))
# select model
model_choice = col1.selectbox("Select model", ("LSTM (slide win)", "Lin Reg (lags 40)"))
@st.cache
def download_data(time_back, incur, outcur, ALL_FEATURES):
return read_preprocess.parseData(time_back, incur, outcur, ALL_FEATURES)
# check target dates with pred_from+pred_horizon
time_back = DAYS_BACK + (datetime.now().date() - predict_from).days
df = download_data(time_back, incur, outcur, ALL_FEATURES)
dforig = read_preprocess.parseData(time_back, incur, outcur, ALL_FEATURES)
df = df[df.index < datetime(predict_from.year, predict_from.month, predict_from.day)]
# compute preds
if model_choice == "LSTM (slide win)":
preds, _, new_preds = predict_lstm.get_predict(df, incur, outcur, pred_horizon)
else:
preds, new_preds = predict_linreg.get_predict(df, incur, outcur, pred_horizon)
print("check")
print(preds)
print(preds.to_frame())
dfhist = dforig[
(dforig.index >= preds.index.min()) & (dforig.index <= new_preds.index.max())
]
preds = preds.to_frame()
preds.columns = ["hist preds"]
# plots. fill in bewteen max min
fig = px.line(preds)
fig.add_trace(go.Scatter(x=dfhist.index, y=dfhist["close"], mode="lines", name="hist"))
fig.add_trace(
go.Scatter(
x=dfhist.index,
y=dfhist["high"],
marker=dict(color="#444"),
line=dict(width=0),
mode="lines",
fillcolor="rgba(68, 68, 68, 0.3)",
fill="tonexty",
showlegend=False,
name="upper bound",
)
)
fig.add_trace(
go.Scatter(
x=dfhist.index,
y=dfhist["low"],
marker=dict(color="#444"),
line=dict(width=0),
mode="lines",
fillcolor="rgba(68, 68, 68, 0.3)",
fill="tonexty",
showlegend=False,
name="lower bound",
)
)
fig.add_trace(
go.Scatter(x=new_preds.index, y=new_preds, mode="markers", name="new preds")
)
st.plotly_chart(fig, use_container_width=True)
# Download CSV data
def filedownload(df):
csv = df.to_csv(index=False)
b64 = base64.b64encode(csv.encode()).decode() # strings <-> bytes conversions
href = f'<a href="data:file/csv;base64,{b64}" download="crypto.csv">Download CSV File</a>'
return href
# show metrics
mae = mean_absolute_error(dfhist.iloc[-5:]["close"], preds[-6:-1])
if mae > 0.01:
st.markdown("Last 5 days MAE: {}".format(round(mae, 2)))
else:
st.markdown("Last 5 days MAE: {}".format(mae))
st.header("Prediction")
new_preds_df = new_preds.to_frame(name="Closed price").applymap('{:,.1f}'.format)
new_preds_df.index = new_preds_df.index.strftime('%Y-%m-%d')
st.dataframe(new_preds_df.T)
st.markdown(filedownload(df), unsafe_allow_html=True)