-
Notifications
You must be signed in to change notification settings - Fork 0
/
sovdb_web.py
384 lines (331 loc) · 12.9 KB
/
sovdb_web.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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
import streamlit as st
import matplotlib
import matplotlib.pyplot as plt
import pandas as pd
import psycopg2 as ps
import datetime
from datetime import date
#from datetime import datetime
from io import BytesIO
import io
import numpy as np
st.set_page_config(page_title="Main",layout="centered")
conn = ps.connect(database = "sovdb",
user = "mike",
host= '185.26.120.148',
password = "mikesovdb13",
port = 5432)
def to_excel(df):
output = BytesIO()
writer = pd.ExcelWriter(output, engine='xlsxwriter')
df.to_excel(writer, index=False, sheet_name='Sheet1')
workbook = writer.book
worksheet = writer.sheets['Sheet1']
format1 = workbook.add_format({'num_format': '0.00'})
worksheet.set_column('A:A', None, format1)
writer.save()
processed_data = output.getvalue()
return processed_data
def decum(df,FREQ):
de_cum = []
dates = []
for i in range(0, len(df)):
dates.append(df.index[i])
if FREQ == "M":
if df.index[i].month == 1:
de_cum.append(df[i])
else:
de_cum.append(df[i]-df[i-1])
df = pd.DataFrame({'Date':dates, 'Value':de_cum})
df = pd.DataFrame(df).set_index('Date')
df = df.squeeze()
#st.write(df)
return df
mymap = ['#0051CA', '#F8AC27', '#3F863F', '#C6DBA1', '#FDD65F', '#FBEEBD', '#50766E'];
#st.sidebar.success("Select a demo above.")
cols=st.columns(4)
with cols[0]:
st.write("Available data: [link](https://docs.google.com/spreadsheets/d/15xyVYbzi04rBfxX4c9wfemcV-BD0pjvb6oCO-2KPGnM/edit#gid=0)")
st.write("Test Mac1")
with cols[1]:
st.write("Countries shorts: [link](https://docs.google.com/spreadsheets/d/1G1nJ0Nyp9nkj5znIAx0dcB3-nZsiXiyPDAvqMZvrC9E/edit?usp=sharing)")
st.subheader('1. Set time period')
cols=st.columns(2)
with cols[0]:
Start_date = st.date_input("Start: ", datetime.date(2022, 1, 1))
with cols[1]:
End_date = st.date_input("End: ", date.today())
st.subheader('2. 1st indicator')
cols=st.columns(2)
with cols[0]:
ticker = st.text_input('Ticker', 'FX_RUBUSD_CBR')
with cols[1]:
field = st.selectbox("Field",("Value","Yield_Close", "Price_Close","Close","Volume"), index=0)
cols=st.columns(7)
with cols[0]:
freq = st.selectbox("FREQ",("none","D","M", "Q", "Y"), index=None)
with cols[1]:
method = st.selectbox("METH",("none","EOP", "AVG","SUM","DECUM"), index=None)
with cols[2]:
trans = st.selectbox("Transform",("none","mom", "qoq","yoy"), index=None)
with cols[3]:
func = st.selectbox("Function",("none","sum","std", "cmlt","avg"), index=None)
with cols[4]:
window_num = st.number_input('Window')
with cols[5]:
bool_y = st.checkbox('Y')
with cols[6]:
y_level = st.number_input('level')
query = "SELECT * FROM sovdb_schema.\""+ticker+"\"";
cur = conn.cursor()
cur.execute(query);
rows = cur.fetchall()
colnames = [desc[0] for desc in cur.description]
#st.write(colnames)
df = pd.DataFrame(rows,columns=colnames)
df = pd.DataFrame(df).set_index('Date')
df = df.sort_index()
df = df[field]
df.index = pd.to_datetime(df.index)
df = df[(df.index >= Start_date.strftime('%Y-%m-%d')) & (df.index <= End_date.strftime('%Y-%m-%d'))]
#st.write(df)
if freq=="M":
if method=="EOP":
df = df.resample(freq).last()
elif method=="AVG":
df = df.resample(freq).mean()
elif method=="SUM":
df = df.resample(freq).sum()
elif method=="DECUM":
df = decum(df,freq)
elif freq=="Q":
if method=="EOP":
df = df.resample('Q').last()
elif method=="AVG":
df = df.resample('Q').mean()
elif method=="SUM":
df = df.resample('Q').sum()
elif freq=="Y":
if method=="EOP":
df = df.resample('Y').last()
elif method=="AVG":
df = df.resample('Y').mean()
elif method=="SUM":
df = df.resample('Y').sum()
if freq=="D":
if trans=="mom":
df.pct_change(periods=20) * 100
elif trans=="qoq":
df = df.pct_change(periods=3*20) * 100
elif trans=="yoy":
df = df.pct_change(periods=252) * 100
elif freq=="M":
if trans=="mom":
df = df.pct_change(periods=1) * 100
elif trans=="qoq":
df = df.pct_change(periods=4) * 100
elif trans=="yoy":
df = df.pct_change(periods=12) * 100
elif freq=="Q":
if trans=="qoq":
df = df.pct_change(periods=1) * 100
elif trans=="yoy":
df = df.pct_change(periods=4) * 100
elif freq=="Y":
if trans=="yoy":
df = df.pct_change(periods=1) * 100
if func=="avg":
df = df.rolling(window=int(window_num)).mean()
elif func=="sum":
df = df.rolling(int(window_num)).sum()
elif func=="std":
df = df.rolling(int(window_num)).std().shift()
elif func=="cmlt":
df = (1 + df/100).cumprod() - 1
st.subheader('3. 2st indicator')
st.subheader('4. Calc returns')
#period change
cols=st.columns(4)
Start_val = 0
End_val = 0;
period_calc=''
with cols[0]:
bool_c = st.checkbox('Calculate returns')
with cols[1]:
Start_date_c = st.date_input("From: ", datetime.date(2022, 1, 1))
if bool_c:
try:
Start_val = round(df.loc[pd.DatetimeIndex([Start_date_c])].values[0],2)
st.write(Start_val)
period_calc = Start_val
except:
a=1
with cols[2]:
End_date_c = st.date_input("To: ", date.today())
if bool_c:
try:
End_val = round(df.loc[pd.DatetimeIndex([End_date_c])].values[0],2)
st.write(End_val)
period_calc = period_calc+" "+End_val
except:
a=1
with cols[3]:
if bool_c and Start_val*End_val:
period_ret = (End_val/Start_val-1)*100
annula_ret = ((1+period_ret/100)**(365.25/(End_date_c - Start_date_c).days)-1)*100
years = (End_date_c - Start_date_c).days/365.25
st.write("abs: "+str(round(End_val-Start_val,2))+"; pct: "+str(round(period_ret,2))+"%")
st.write("ann ret: "+str(round(annula_ret,2))+"% ("+str(round(years,1))+"Y)")
def click_button_update_add(UPDATE, Update_date,Update_number):
if (UPDATE):
#st.write(Update_number)
query = "UPDATE sovdb_schema.\""+ticker+"\" SET \"""Value\""" = '"+str(Update_number)+"' WHERE \"""Date\""" = '"+Update_date.strftime('%d-%b-%Y')+"'"
#st.write(query)
cur.execute(query)
conn.commit()
#update dates
query = "SELECT * FROM sovdb_schema.""macro_indicators"" WHERE \"""ticker\""" = '"+ticker+"'"
#cur = conn.cursor()
cur.execute(query);
rows = cur.fetchall()
rows = np.array([*rows])
macro =1
if rows.size==0:
macro = 0
else:
macro = 1
if macro:
query = "UPDATE sovdb_schema.""macro_indicators"" SET \"""end_date\""" = '"+str(Update_date.strftime('%d-%b-%Y'))+"', \"""update_date\""" = '"+str(date.today().strftime('%d-%b-%Y'))+"' WHERE \"""ticker\""" = '"+ticker+"'"
cur.execute(query)
conn.commit()
st.warning("UPDATES: "+ticker+": "+Update_date.strftime('%d-%b-%Y')+" FROM "+str(Update_number)+" TO ->")
else:
#addquery = "INSERT INTO sovdb_schema."""+ticker(i)+""" (""Date"", ""Value"") VALUES ('"+date+"'::date, "+Value+"::double precision) returning ""Date"";";
query = "INSERT INTO sovdb_schema.\""+ticker+"\" (\"""Date\""", \"""Value\""") VALUES ('"+Update_date.strftime('%d-%b-%Y')+"'::date, '"+str(Update_number)+"':: double precision) returning \"""Date\""""
#st.write(query)
cur.execute(query)
conn.commit()
st.warning("ADDED: "+ticker+": "+Update_date.strftime('%d-%b-%Y')+" - "+str(Update_number))
st.session_state.clicked = True
def click_button_del(DELETE, Delete_date):
deletequery = "DELETE FROM sovdb_schema.\""+ticker+"\" WHERE \"""Date\""" = '"+Delete_date.strftime('%d-%b-%Y')+"'"
# deletequery = "DELETE FROM users WHERE id=5;";
cur.execute(deletequery)
conn.commit()
#st.warning("DELETED"+ticker+": "+Delete_date.strftime('%d-%b-%Y')+" - "+str(Update_number))
st.warning("DELETED: "+ticker+": "+Delete_date.strftime('%d-%b-%Y'))
st.session_state.clicked = True
st.subheader('Edit 1st indicator')
### - 22 - 92.4387 21 '92.349
#Edit data
cols=st.columns(4)
with cols[0]:
Update_date = st.date_input("Edit date: ", date.today())
if Update_date.strftime('%Y-%m-%d') in df.index.strftime('%Y-%m-%d').values:
Update_val = df.loc[Update_date.strftime('%Y-%m-%d')]
UPDATE = 1
#st.write(df)
else:
Update_val = 0.0
UPDATE = 0
with cols[1]:
Update_number = st.number_input('Value (0 if not exists)',value=Update_val,format="%.5f",step=0.00001)
with cols[2]:
st.button('Update/Add', on_click=click_button_update_add, args=(UPDATE, Update_date,Update_number))
with cols[3]:
DELETE = 1
st.button('Delete', on_click=click_button_del, args=(DELETE, Update_date))
fig, ax = plt.subplots()
Lastdate = df.index[-1].strftime('%Y-%m-%d')
#st.write(colnames)
ax.plot(df, color=mymap[0], label='d',linewidth=0.8)
#st.write(type(df))
ax.text(df.index[-1], df[-1], round(df[-1],2), fontsize=8,color=mymap[0]);
if bool_y:
ax.axhline(y=y_level, color=(0.15, 0.15, 0.15), linestyle='-',linewidth=0.75)
#if bool_c and period_calc != 'no start value' and period_calc != 'no end value':
if bool_c and Start_val*End_val:
ax.plot(Start_date_c, Start_val, marker=5,color=(1,0,0))
ax.plot(End_date_c, End_val, marker=4,color=(1,0,0))
plt.title(ticker+", "+Lastdate)
#plt.legend()
formatter = matplotlib.dates.DateFormatter('%Y')
ax.xaxis.set_major_formatter(formatter)
plt.show()
st.pyplot(fig)
cols=st.columns(3)
with cols[0]:
buffer = io.BytesIO()
with pd.ExcelWriter(buffer, engine='xlsxwriter') as writer:
df.to_excel(writer, sheet_name='Sheet1', index=True)
download2 = st.download_button(
label="Excel",
data=buffer,
file_name=ticker+".xlsx",
mime='application/vnd.ms-excel'
)
with cols[1]:
# @st.cache
def convert_df(df):
# IMPORTANT: Cache the conversion to prevent computation on every rerun
return df.to_csv().encode('utf-8')
csv = convert_df(df)
st.download_button(
label="CSV",
data=csv,
file_name=ticker+".csv",
mime='text/csv',
)
with cols[2]:
fn = ticker+".png"
plt.savefig(fn)
with open(fn, "rb") as img:
btn = st.download_button(
label="JPG",
data=img,
file_name=fn,
mime="image/png"
)
query = "SELECT * FROM sovdb_schema.countries"
cur = conn.cursor()
cur.execute(query);
rows = cur.fetchall()
colnames = [desc[0] for desc in cur.description]
df = pd.DataFrame(rows,columns=colnames)
count_sel = df.name
#query2 = "SELECT * FROM sovdb_schema.macro_indicators";
#st.write(query2)
#cur = conn.cursor()
#cur.execute(query2);
#rows = cur.fetchall()
#colnames = [desc[0] for desc in cur.description]
#df = pd.DataFrame(rows,columns=colnames)
#groups = df.group.unique()
#budget - DROP
groups = ['real','external','fiscal','popul','market','eco','covid','finance','institute','budget','all']
tot_str = "("
for i in range(0,len(groups)-1):
tot_str = tot_str+"'"+groups[i]+"', "
tot_str = tot_str[:-2]
tot_str = tot_str+")"
st.subheader('5. Find indicator')
cols=st.columns(2)
with cols[0]:
countr = st.selectbox("Country",(count_sel), index=203)
with cols[1]:
mgroup = st.selectbox("Group",(groups), index=0)
#query2 = "SELECT * FROM sovdb_schema.macro_indicators WHERE country = '"+countr+"' AND group = public"
#query2 = "SELECT * FROM sovdb_schema.""macro_indicators"" WHERE ""country"" = '"+countr+"' AND group = '"+groupm+"'"
if mgroup == 'all':
query2 = "SELECT * FROM sovdb_schema.""macro_indicators"" WHERE ""country"" = '"+countr+"' AND ""mgroup"" IN "+tot_str
#query2 = "SELECT * FROM sovdb_schema.""macro_indicators"" WHERE ""country"" = '"+countr+"' AND ""mgroup"" IN ('real','external')"
else:
query2 = "SELECT * FROM sovdb_schema.""macro_indicators"" WHERE ""country"" = '"+countr+"' AND ""mgroup"" = '"+mgroup+"'"
#st.write(query2)
#st.write(len(groupm))
cur = conn.cursor()
cur.execute(query2);
rows = cur.fetchall()
colnames = [desc[0] for desc in cur.description]
df = pd.DataFrame(rows,columns=colnames)
st.table(df[['ticker', 'full_name','freq','metric','mgroup']])