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'
' 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 = """ """ st.markdown(style_button, unsafe_allow_html=True) def style_table(): # tr:hover {background-color: #E8E8E8; # color:#BB1114;} style_table = """ """ 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('

Principales bonos 10Y

', unsafe_allow_html=True) col2.markdown('

Principales commodities

', unsafe_allow_html=True) col3.markdown('

Principales indices

', 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('

'+"Precio"+"

", unsafe_allow_html=True) cols[0].markdown('

'+"{:,}".format(last_price)+"%

", unsafe_allow_html=True) if returns > 0: cols[1].markdown('

▲ '+str(returns)+" %

", unsafe_allow_html=True) else: cols[1].markdown('

▼ '+str(returns)+" %

", 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('

'+"Precio"+"

", unsafe_allow_html=True) cols[2].markdown('

$'+"{:,}".format(last_price2)+"

", unsafe_allow_html=True) if returns2 > 0: cols[3].markdown('

▲ '+str(returns2)+" %

", unsafe_allow_html=True) else: cols[3].markdown('

▼ '+str(returns2)+" %

", 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('

'+"Precio"+"

", unsafe_allow_html=True) cols[4].markdown('

$'+"{:,}".format(last_price3)+"

", unsafe_allow_html=True) if returns3 > 0: cols[5].markdown('

▲ '+str(returns3)+" %

", unsafe_allow_html=True) else: cols[5].markdown('

▼ '+str(returns3)+" %

", 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