Spaces:
Configuration error
Configuration error
File size: 14,238 Bytes
025632f |
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 |
import pandas as pd
from datetime import date
from plotly import graph_objs as go
import pybase64 as base64
import numpy as np
import investpy
import streamlit as st
import datetime as dt
import io
def get_table_excel_link(df, selected_stocks):
towrite = io.BytesIO()
downloaded_file = df.to_excel(towrite, encoding='utf-8', index=False,
header=True)
towrite.seek(0) # reset pointer
file_name = 'Data'+ selected_stocks + '.xlsx'
style = 'style="color:black;text-decoration: none; font-size:18px;"'
name_mark = "Descargar " + selected_stocks + ".xlsx"
b64 = base64.b64encode(towrite.read()).decode() # some strings
linko= f'<center><a href="data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,{b64}" '+style+'download="'+file_name+'"><button>'+name_mark+'</button></a></center>'
return linko
@st.cache
def tabla_commodity(stocks, TODAY):
tabla = pd.DataFrame()
year_ago = date.today() - dt.timedelta(days=365)
year_ago = year_ago.strftime("%d/%m/%Y")
for stock in stocks:
precios = investpy.commodities.get_commodity_historical_data(
commodity=stock,
from_date=year_ago,
to_date=TODAY)
precios = precios["Close"]
last_price = precios.iloc[-1]
oned = precios.iloc[-2]
onew = precios.iloc[-7]
onem = precios.iloc[-30]
oney = precios.iloc[0]
return1m = str(round((last_price/onem-1)*100, 2))+"%"
return1d = str(round((last_price/oned-1)*100, 2))+"%"
return1w = str(round((last_price/onew-1)*100, 2))+"%"
return1y = str(round((last_price/oney-1)*100, 2))+"%"
tabla = tabla.append([[return1d, return1w, return1m, return1y]])
tabla.columns = ["1d", "1w", "1m", "1y"]
tabla.index = stocks
return tabla
@st.cache
def tabla_indices(index, countries, TODAY):
tabla = pd.DataFrame()
year_ago = date.today() - dt.timedelta(days=365)
year_ago = year_ago.strftime("%d/%m/%Y")
for i in range(len(index)):
precios = investpy.get_index_historical_data(index=index[i],
country=countries[i],
from_date=year_ago,
to_date=TODAY)
precios = precios["Close"]
last_price = precios.iloc[-1]
oned = precios.iloc[-2]
onew = precios.iloc[-7]
onem = precios.iloc[-30]
oney = precios.iloc[0]
return1m = str(round((last_price/onem-1)*100, 2))+"%"
return1d = str(round((last_price/oned-1)*100, 2))+"%"
return1w = str(round((last_price/onew-1)*100, 2))+"%"
return1y = str(round((last_price/oney-1)*100, 2))+"%"
tabla = tabla.append([[return1d, return1w, return1m, return1y]])
tabla.columns = ["1d", "1w", "1m", "1y"]
tabla.index = index
return tabla
@st.cache
def tabla_bonos(stocks, TODAY):
tabla = pd.DataFrame()
year_ago = date.today() - dt.timedelta(days=365)
year_ago = year_ago.strftime("%d/%m/%Y")
for stock in stocks:
precios = investpy.get_bond_historical_data(bond=stock,
from_date=year_ago,
to_date=TODAY)
precios = precios["Close"]
last_price = precios.iloc[-1]
oned = precios.iloc[-2]
onew = precios.iloc[-7]
onem = precios.iloc[-30]
oney = precios.iloc[0]
return1m = str(round((last_price-onem)*100, 2))+"%"
return1d = str(round((last_price -oned)*100, 2))+"%"
return1w = str(round((last_price -onew)*100, 2))+"%"
return1y = str(round((last_price - oney)*100, 2))+"%"
tabla = tabla.append([[return1d, return1w, return1m, return1y]])
tabla.columns = ["1d", "1w", "1m", "1y"]
tabla.index = stocks
return tabla
def highlight_max(s):
if s.dtype == np.object:
is_neg = [False for _ in range(s.shape[0])]
else:
is_neg = s < 0
return ['color: red;' if cell else 'color:black' for cell in is_neg]
def button_style():
style_button = """
<style>
button {
display: inline-block;
background-color: #e8e8e8;
border-radius: 15px;
border: 4px #cccccc;
color: #4a4a4a;
text-align: center;
font-size: 12px;
padding: 2px;
width: 250px;
transition: all 0.5s;
cursor: pointer;
margin: 5px;
}
button span {
cursor: pointer;
display: inline-block;
position: relative;
transition: 0.5s;
}
button span:after {
content: '\00bb';
position: absolute;
opacity: 0;
top: 0;
right: -20px;
transition: 0.5s;
}
button:hover {
background-color: #bb1114;
color:#e8e8e8;
}
button:hover span {
padding-right: 25px;
}
button:hover span:after {
opacity: 1;
right: 0;
}
.stMarkdown{
margin-bottom:0px;}
</style>
"""
st.markdown(style_button, unsafe_allow_html=True)
def style_table():
# tr:hover {background-color: #E8E8E8;
# color:#BB1114;}
style_table = """
<style>
tr { line-height: 5px; }
thead {
background-color:#BB1114 ;
color: #E8E8E8;
}
tbody tr:nth-child(odd) {
background-color: #fff;
}
tbody tr:nth-child(even) {
background-color: #eee;
}
.css-1rcck9u{
padding:0.25rem;}
tbody tr:nth-child(odd)
stTable {
border-collapse: collapse;
background-color:red;
margin: 25px 0;
font-size: 0.9em;
min-width: 400px;
box-shadow: 0 0 20px rgba(0, 0, 0, 0.15);
}
table{
margin-top:0px;
font-size:9px;
padding:0px;
height:200px;}
.st-cc, .st-cb{
padding-top:5px;
padding-bottom:5px;}
h3, h1, h2, .svg-container {
animation-duration: 3s;
animation-name: slidein;
}
@keyframes slidein {
from {
margin-left: 100%;
width: 300%
}
to {
margin-left: 0%;
width: 100%;
}
}
</style>
"""
st.markdown(style_table, unsafe_allow_html=True)
def seleccionar_fecha(fecha_select):
if fecha_select == "1 week":
fec_in = date.today() - dt.timedelta(days=7)
elif fecha_select == "1 month":
fec_in = date.today() - dt.timedelta(days=30)
elif fecha_select == "3 month":
fec_in = date.today() - dt.timedelta(days=90)
elif fecha_select == "6 month":
fec_in = date.today() - dt.timedelta(days=180)
elif fecha_select == "1 year":
fec_in = date.today() - dt.timedelta(days=365)
elif fecha_select == "5 year":
fec_in = date.today() - dt.timedelta(days=365*5)
fec_in = fec_in.strftime("%d/%m/%Y")
return fec_in
def stock_price():
style_table()
button_style()
TODAY = date.today().strftime("%d/%m/%Y")
YDAY = date.today() - dt.timedelta(days=1)
YDAY = YDAY.strftime("%d/%m/%Y")
commodity = ["Copper", "Silver", "Gold", "Platinum", 'Brent Oil',
'Heating Oil']
# bonos = ["Brazil 10Y", "Mexico 10Y" , "Chile 10Y", "Colombia 10Y"
# , "Peru 10Y"]
bonds10y = ["Brazil 10Y", "Mexico 10Y", "Chile 10Y", "Colombia 10Y",
"Peru 10Y", "China 10Y"]
index = ["S&P CLX IPSA", "S&P Merval", "Bovespa", "S&P 500"]
countries = ["chile", "argentina", "brazil", "united states"]
col1, col2, col3 = st.beta_columns(3)
cols = st.beta_columns((3, 2, 3, 2, 3, 2))
col1.markdown('<center><h1 style="font-size:22px;">Principales bonos 10Y</h1><center>', unsafe_allow_html=True)
col2.markdown('<center><h1 style="font-size:22px;">Principales commodities</h1><center>', unsafe_allow_html=True)
col3.markdown('<center><h1 style="font-size:22px;">Principales indices</h1><center>', unsafe_allow_html=True)
selected_com = cols[2].selectbox(" ", commodity)
selected_index = cols[4].selectbox(" ", index)
selected_bonds = cols[0].selectbox(" ", bonds10y)
fecha_select = cols[3].selectbox(" ", ["1 year", "6 month", "3 month",
"1 month", "1 week"])
fecha_select2 = cols[5].selectbox(" ", ["1 year", "6 month", "3 month",
"1 month", "1 week"])
fecha_select3 = cols[1].selectbox(" ", ["1 year", "6 month", "3 month",
"1 month", "1 week"])
# fecha_select =cols[2].button("hola")
fec_in = seleccionar_fecha(fecha_select)
fec_in2 = seleccionar_fecha(fecha_select2)
fec_in3 = seleccionar_fecha(fecha_select3)
selected_country = countries[index.index(selected_index)]
data_bonds = investpy.get_bond_historical_data(bond=selected_bonds,
from_date=fec_in3,
to_date=TODAY)
data_com = investpy.commodities.get_commodity_historical_data(
commodity=selected_com,
from_date=fec_in,
to_date=TODAY)
data_index = investpy.get_index_historical_data(index=selected_index,
country=selected_country,
from_date=fec_in2,
to_date=TODAY)
def plot_raw_data(col, data, color, prefijo):
fig = go.Figure()
close_ = go.Scatter(x=data.index, y=data['Close'], name="stock_close",
line=dict(color=color), fill='tonexty')
fig.add_trace(close_)
fig.layout.update(title_text="", xaxis_rangeslider_visible=True,
width=300, height=200, margin_b=0, margin_t=0,
margin_r=0, margin_l=0)
fig.update_yaxes(range=[min(data['Close'])/1.05,
max(data['Close'])*1.05], tickprefix=prefijo)
col.plotly_chart(fig)
plot_raw_data(cols[0], data_bonds, 'seagreen', "")
plot_raw_data(cols[2], data_com, 'midnightblue', "$")
plot_raw_data(cols[4], data_index, 'dimgrey', "$")
col1, col2, col3 = st.beta_columns(3)
cols = st.beta_columns((3, 2, 3, 2, 3, 2))
last_price = data_bonds.iloc[-1]["Close"]
first_price = data_bonds.iloc[0]["Close"]
returns = round((last_price/first_price-1)*100, 2)
cols[0].markdown('<h4 style="font-size:12px; padding-left:15px; margin-bottom:0px;">'+"Precio"+"</h4>", unsafe_allow_html=True)
cols[0].markdown('<p style="font-size:25px; padding-left:30px;">'+"{:,}".format(last_price)+"%</p>", unsafe_allow_html=True)
if returns > 0:
cols[1].markdown('<p style="font-size:20px; padding-top:22px; color:green;">▲ '+str(returns)+" %</p>", unsafe_allow_html=True)
else:
cols[1].markdown('<p style="font-size:20px; padding-top:22px; color:red;">▼ '+str(returns)+" %</p>", unsafe_allow_html=True)
last_price2 = data_com.iloc[-1]["Close"]
first_price2 = data_com.iloc[0]["Close"]
returns2 = round((last_price2/first_price2-1)*100, 2)
cols[2].markdown('<h4 style="font-size:12px; padding-left:15px; margin-bottom:0px;">'+"Precio"+"</h4>", unsafe_allow_html=True)
cols[2].markdown('<p style="font-size:25px; padding-left:30px;">$'+"{:,}".format(last_price2)+"</p>", unsafe_allow_html=True)
if returns2 > 0:
cols[3].markdown('<p style="font-size:20px; padding-top:22px; color:green;">▲ '+str(returns2)+" %</p>", unsafe_allow_html=True)
else:
cols[3].markdown('<p style="font-size:20px; padding-top:22px; color:red;">▼ '+str(returns2)+" %</p>", unsafe_allow_html=True)
last_price3 = data_index.iloc[-1]["Close"]
first_price3 = data_index.iloc[0]["Close"]
returns3 = round((last_price3/first_price3-1)*100, 2)
cols[4].markdown('<h4 style="font-size:12px; padding-left:15px; margin-bottom:0px;">'+"Precio"+"</h4>", unsafe_allow_html=True)
cols[4].markdown('<p style="font-size:25px; padding-left:30px;">$'+"{:,}".format(last_price3)+"</p>", unsafe_allow_html=True)
if returns3 > 0:
cols[5].markdown('<p style="font-size:20px; padding-top:22px; color:green;">▲ '+str(returns3)+" %</p>", unsafe_allow_html=True)
else:
cols[5].markdown('<p style="font-size:20px; padding-top:22px; color:red;">▼ '+str(returns3)+" %</p>", unsafe_allow_html=True)
col1, col2, col3 = st.beta_columns(3)
col1.table(tabla_bonos(bonds10y, TODAY))
col2.table(tabla_commodity(commodity, TODAY))
col3.table(tabla_indices(index, countries, TODAY))
col1, col2, col3 = st.beta_columns(3)
col2.markdown(get_table_excel_link(data_com, selected_com),
unsafe_allow_html=True)
col3.markdown(get_table_excel_link(data_index, selected_index),
unsafe_allow_html=True)
col1.markdown(get_table_excel_link(data_bonds, selected_bonds),
unsafe_allow_html=True)
get_table_excel_link
|