File size: 6,578 Bytes
e1ca29e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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'<a href="data:file/txt;base64,{b64}" download="{download_filename}">{download_link_text}</a>'



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()