from distutils.command.build_scripts import first_line_re import streamlit as st import pandas as pd import altair as alt import datetime as dt from datetime import timedelta from datetime import datetime import pytz from pymongo import MongoClient import base64 def download_link(object_to_download, download_filename, download_link_text): if isinstance(object_to_download,pd.DataFrame): object_to_download = object_to_download.to_csv(index=True) b64 = base64.b64encode(object_to_download.encode()).decode() return f'{download_link_text}' def main(): st.set_page_config( # Alternate names: setup_page, page, layout layout="wide", # Can be "centered" or "wide". In the future also "dashboard", etc. initial_sidebar_state="auto", # Can be "auto", "expanded", "collapsed" page_title="Ratio de Bonos v2", # String or None. Strings get appended with "• Streamlit". page_icon=None, # String, anything supported by st.image, or None. ) st.title("Ratio de bonos v2") today = datetime.today().astimezone(pytz.timezone('America/Argentina/Buenos_Aires')).replace(hour=0,minute=0,second= 0) # conexion a bd broker_bd = client = MongoClient("mongodb+srv://diaznicolasandres:diaznicolasandres941231@cluster0.azraf.mongodb.net/broker?retryWrites=true&w=majority") db = client.get_database('broker') bonds_table = db.bond lista_nombre_bonos_1 = ["AL30", "AL29", "GD30", "GD29"] lista_nombre_bonos_2 = ["GD30","AL30","AL29", "GD29"] add_selectbox_bono1 = st.sidebar.selectbox( 'Seleccionar bono 1 ', lista_nombre_bonos_1 ) add_selectbox_bono2 = st.sidebar.selectbox( 'Seleccionar bono 2', lista_nombre_bonos_2 ) cantidad_dias = st.sidebar.selectbox("Cant dias", [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]) if(add_selectbox_bono1 is not None and add_selectbox_bono2 is not None): especie1 = '_'+add_selectbox_bono1 especie2 = '_'+add_selectbox_bono2 if(especie1 == especie2): especie2 = especie2+"2" bonos1_found = bonds_table.find({'ticker': add_selectbox_bono1, "date": {"$gt": today - timedelta(days= cantidad_dias-1)}}) bonos2_found = bonds_table.find({'ticker': add_selectbox_bono2, "date": {"$gt": today - timedelta(days= cantidad_dias-1)}}) dataframe1 = pd.DataFrame(bonos1_found , columns = ['lastPrice', 'buyPrice','sellPrice', 'date']) dataframe2 = pd.DataFrame(bonos2_found , columns = ['lastPrice', 'buyPrice','sellPrice', 'date']) dataframe1 = dataframe1.rename(columns = {'date': 'index'}).set_index('index') dataframe1.drop_duplicates(keep='first') dataframe2 = dataframe2.rename(columns = {'date': 'index'}).set_index('index') dataframe2.drop_duplicates(keep='first') dataframe1 = dataframe1.loc[(dataframe1['lastPrice']!= '-' ) & (dataframe1['buyPrice']!= '-' ) & (dataframe1['sellPrice']!= '-' ) ] dataframe2 = dataframe2.loc[(dataframe2['lastPrice']!= '-' ) & (dataframe2['buyPrice']!= '-' ) & (dataframe2['sellPrice']!= '-' ) ] dataframe1 = dataframe1.rename(columns={'lastPrice': 'UltimoPrecio'+especie1, 'buyPrice': 'PrecioCompra'+especie1, 'sellPrice': 'PrecioVenta'+especie1}) dataframe2 = dataframe2.rename(columns={'lastPrice': 'UltimoPrecio'+especie2, 'buyPrice': 'PrecioCompra'+especie2, 'sellPrice': 'PrecioVenta'+especie2}) df_combinado = dataframe1.join(dataframe2, on='index') df_combinado['Ratio'] = df_combinado['UltimoPrecio'+especie1].astype(float) / df_combinado['UltimoPrecio'+especie2].astype(float) argentina_timezone = 'America/Argentina/Buenos_Aires' df_combinado.index = df_combinado.index.tz_localize(pytz.utc).tz_convert(argentina_timezone) df_combinado = df_combinado[~df_combinado.index.duplicated(keep='first')] st.dataframe(df_combinado.style.highlight_max(color='green', axis=0)) # Graficar data if st.button("Graficar"): cust_data = df_combinado["Ratio"] line = alt.Chart(cust_data.reset_index()).mark_line( color='purple', size=3 ).transform_window( rolling_mean='mean(Ratio)' ).encode( x=alt.X('index'), y=alt.Y('rolling_mean:Q', scale=alt.Scale(zero=False)) ).properties(title=add_selectbox_bono1 + '/' + add_selectbox_bono2).interactive() points = alt.Chart(cust_data.reset_index()).mark_line().encode( x=alt.X('index', axis=alt.Axis(title='Fecha')), y=alt.Y('Ratio:Q', axis=alt.Axis(title='Ratio - Media'), scale=alt.Scale(zero=False)) ).interactive() chart = line + points chart = line + points st.altair_chart(chart, use_container_width=True) base1 = alt.Chart(df_combinado.reset_index()).encode(alt.X('index', axis = alt.Axis(title='Fecha'))) line_1 = base1.mark_line( color='purple', size=2 ).encode( y=alt.Y("UltimoPrecio" + especie1 + ':Q', scale=alt.Scale(zero=False), axis=alt.Axis(title='Ultimo precio', titleColor='black')) ).properties(title=add_selectbox_bono1).interactive() layer1 = alt.layer(line_1) st.altair_chart(layer1, use_container_width=True) line_2 = base1.mark_line( color='purple', size=2 ).encode( y=alt.Y("UltimoPrecio" + especie2 + ':Q', scale=alt.Scale(zero=False), axis=alt.Axis(title='Ultimo precio', titleColor='black')) ).properties(title=add_selectbox_bono2).interactive() layer2 = alt.layer(line_2) st.altair_chart(layer2, use_container_width=True) if st.button("Descargar"): # open('bonos.csv', 'w').write(df_ratio.to_csv()) tmp_download_link = download_link(df_combinado, 'bonos_' + especie1 + '_' + especie2 + '.csv', 'Presione para descargar el archivo') st.markdown(tmp_download_link, unsafe_allow_html=True) if __name__ == '__main__': main()