Spaces:
Configuration error
Configuration error
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 | |
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 | |
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 | |
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 | |