Spaces:
Configuration error
Configuration error
| #!/usr/bin/env python3 | |
| # -*- coding: utf-8 -*- | |
| """ | |
| Created on Tue Sep 21 11:53:13 2021 | |
| @author: benjaminull | |
| """ | |
| import numpy as np | |
| import streamlit as st | |
| import plotly.express as px | |
| import pandas as pd | |
| import scipy.stats as stats | |
| import plotly.express as px | |
| import scipy.stats as stats | |
| import plotly.graph_objects as go | |
| from sqlalchemy import create_engine | |
| import pybase64 as base64 | |
| import io | |
| import matplotlib.pyplot as plt | |
| from io import StringIO | |
| import pandas as pd | |
| def read_excel(path): | |
| df = pd.read_excel(path) | |
| return df | |
| def read_excel2(path): | |
| df = pd.read_excel(path) | |
| return df | |
| def explorar_data(): | |
| df = read_excel('base_personas.xlsx') | |
| df2 = read_excel2('base_personas.xlsx') | |
| data = df.copy() | |
| data2 = df2.copy() | |
| l=[] | |
| variable = st.selectbox(" ",list(data.columns)) | |
| for i in list(data2.columns): | |
| if i not in ["FE", "EDAD", variable]: | |
| try: | |
| data2[i] = data2[i]* data2["FE"] | |
| except: | |
| pass | |
| col1, col2 = st.beta_columns(2) | |
| minim = col1.number_input("Edad minima", min_value=0, max_value=105) | |
| maxim = col2.number_input("Edad maxima", min_value=0, max_value=105, value=105) | |
| data = data[data["EDAD"] < maxim] | |
| data = data[data["EDAD"] > minim] | |
| data2 = data2[data2["EDAD"] < maxim] | |
| data2 = data2[data2["EDAD"] > minim] | |
| pond = st.checkbox("Ponderar por FE") | |
| import plotly.graph_objects as go | |
| if pond: | |
| data_f3 = data2.groupby([ variable, "EDAD"]).sum() | |
| data_f3 = data_f3.loc[:,data_f3.columns[0]].unstack(level=1).replace(np.nan, 0) | |
| st.write(data_f3) | |
| fig = go.Figure() | |
| for i in list(data_f3.index): | |
| fig.add_trace(go.Scatter( | |
| x=list(data_f3.columns), y=list(data_f3.loc[i,:]), | |
| mode='lines', | |
| line=dict(width=0.5), | |
| stackgroup='one', | |
| groupnorm='percent' # sets the normalization for the sum of the stackgroup | |
| )) | |
| fig.update_layout( | |
| showlegend=True, | |
| xaxis_type='category', | |
| yaxis=dict( | |
| type='linear', | |
| range=[1, 100], | |
| ticksuffix='%')) | |
| st.plotly_chart(fig, use_container_width=True) | |
| else: | |
| data_f = data.groupby([ variable, "EDAD"]).count() | |
| data_f2 = data_f.loc[:,data_f.columns[0]].unstack(level=1).replace(np.nan, 0) | |
| st.write(data_f2) | |
| fig = go.Figure() | |
| for i in list(data_f2.index): | |
| fig.add_trace(go.Scatter( | |
| x=list(data_f2.columns), y=list(data_f2.loc[i,:]), | |
| mode='lines', | |
| line=dict(width=0.5), | |
| stackgroup='one', | |
| groupnorm='percent' # sets the normalization for the sum of the stackgroup | |
| )) | |
| fig.update_layout( | |
| showlegend=True, | |
| xaxis_type='category', | |
| yaxis=dict( | |
| type='linear', | |
| range=[1, 100], | |
| ticksuffix='%')) | |
| st.plotly_chart(fig, use_container_width=True) | |
| # pr = data_f2.profile_report() | |
| # st_profile_report(data_f2) | |
| def transform_df(scraping_df): | |
| # Extract numbers from string | |
| # Change datatype | |
| # Add 'Comuna' and 'Regi贸n' | |
| scraping_df[["Comuna"]] = scraping_df[[ | |
| "direccion"]].applymap(lambda x: get_comuna(x)) | |
| # Scrap UF value for date | |
| #scraping_df[["Valor UF"]] = get_UF() | |
| return scraping_df | |
| def get_table_excel_link(df, name): | |
| towrite = io.BytesIO() | |
| downloaded_file = df.to_excel(towrite, encoding='utf-8', index=False, | |
| header=True) | |
| towrite.seek(0) # reset pointer | |
| file_name = 'Data' + name + '.xlsx' | |
| style = 'style="color:black;text-decoration: none; font-size:18px;"' | |
| name_mark = "Descargar " + name + ".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 get_comuna(direction): | |
| values = direction.split(',') | |
| return values[-2] | |
| def formatnum(numero): | |
| ''' | |
| Esta funci贸n permite dar formato a los montos de saldo y valor cuota en | |
| las cartolas. | |
| ''' | |
| return '{:,.0f}'.format(numero).replace(",", "@").replace(".", ",").replace("@", ".") | |
| def sim_norm(): | |
| with st.form(key='my_form'): | |
| col1, col2 = st.beta_columns(2) | |
| sim = col1.number_input("N潞 Simulaciones", min_value=1, value=100) | |
| vc = col2.number_input("Cuota inicial", min_value=100) | |
| col1, col2, col3 = st.beta_columns(3) | |
| mu = col1.number_input("碌 Fondo Arriesgado", value=0.1) | |
| sigma = col1.number_input("蟽 Fondo Arriesgado", value=0.1) | |
| mu2 = col2.number_input("碌 Fondo Intermedio ", value=0.05) | |
| sigma2 = col2.number_input("蟽 Fondo Intermedio", value=0.05) | |
| mu3 = col3.number_input("碌 Fondo Conservador", value=-0.01) | |
| sigma3 = col3.number_input("蟽 Fondo Conservador", value=0.03) | |
| # t= col1.number_input("Periodo", value=288) | |
| # t2 = col2.number_input("Periodo ", value=120) | |
| # t3 = col3.number_input("Periodo ", value=72) | |
| values = st.slider( | |
| 'Seleccione los a帽os de cambio de fondo', 0, 40, (33, 38)) | |
| with st.beta_expander("Ajustar par谩metros de distribucion de permanencia del cliente (gamma)"): | |
| col1, col2 = st.beta_columns(2) | |
| alpha = col1.number_input("alpha", value=1.5) | |
| beta = col2.number_input("lambda", value=71.1) | |
| submit_button = st.form_submit_button(label='Actualizar') | |
| if submit_button: | |
| t = values[0]*12 | |
| t2 = values[1]*12-t | |
| t3 = 480-t2-t | |
| mu = mu / 12 | |
| mu2 = mu2 / 12 | |
| mu3 = mu3 / 12 | |
| sigma = sigma / (12**(1/2)) | |
| sigma2 = sigma2 / (12**(1/2)) | |
| sigma3 = sigma3 / (12**(1/2)) | |
| var_al = np.random.normal(mu, sigma, size=(t, sim)) | |
| var_al2 = np.random.normal(mu2, sigma2, size=(t2, sim)) | |
| var_al3 = np.random.normal(mu3, sigma3, size=(t3, sim)) | |
| simulacion = np.zeros((t + t2 + t3, sim)) | |
| simulacion[0, :] = vc | |
| dist_gamma = stats.gamma.rvs(alpha, scale=beta, size=sim).astype(int)+1 | |
| for i in range(1, t): | |
| simulacion[i, :] = simulacion[i - 1, :] * (1 + var_al[i-1, :]) | |
| for i in range(t, t+t2): | |
| simulacion[i, :] = simulacion[i - 1, :] * (1 + var_al2[t-i-1, :]) | |
| for i in range(t+t2, t+t2+t3): | |
| simulacion[i, :] = simulacion[i - 1, :] * \ | |
| (1 + var_al3[t2+t-i-1, :]) | |
| retornos = np.zeros(sim) | |
| for j in range(sim): | |
| ingreso = 480-dist_gamma[j] | |
| simulacion[0:ingreso, j] = None | |
| simulacion[ingreso:480, j] = simulacion[ingreso:480, j] * \ | |
| vc/simulacion[ingreso, j] | |
| retorno = (simulacion[-1, j]/simulacion[ingreso, j] | |
| )**(1/(dist_gamma[j]/12))-1 | |
| retornos[j] = retorno | |
| df = pd.DataFrame(simulacion) | |
| df["meses"] = list(df.index) | |
| fig = px.line(df, x="meses", y=df.columns, | |
| title='Simulaciones') | |
| fig.layout.update(xaxis_rangeslider_visible=True) | |
| fig.add_vline(x=t, line_width=3, line_dash="dash", line_color="grey") | |
| fig.add_vline(x=t+t2, line_width=3, | |
| line_dash="dash", line_color="grey") | |
| fig.add_vrect(x0=0, x1=t, annotation_text="Arries", | |
| annotation_position="top", | |
| fillcolor="red", opacity=0.15, line_width=0) | |
| fig.add_vrect(x0=t, x1=t+t2, | |
| annotation_text="Inter", annotation_position="top", | |
| fillcolor="midnightblue", opacity=0.15, line_width=0) | |
| fig.add_vrect(x0=t + t2, x1=t + t2 + t3, | |
| annotation_text="Cons", annotation_position="top", | |
| fillcolor="seagreen", opacity=0.15, line_width=0) | |
| fig.update_layout(height=600, width=950) | |
| st.plotly_chart(fig, use_container_width=True) | |
| st.subheader("Distribuci贸n de duracion de clientes") | |
| df_in = pd.DataFrame(dist_gamma//12, columns=["ingreso"]) | |
| fig = px.histogram(df_in, x="ingreso", nbins=40) | |
| fig.add_vline(x=(dist_gamma//12).mean(), line_width=3, | |
| line_dash="dash", line_color="midnightblue") | |
| col1, col2 = st.beta_columns((3, 1)) | |
| col1.plotly_chart(fig, use_container_width=True) | |
| col2.title(" ") | |
| col2.header("碌 = "+str((dist_gamma//12).mean())[0:4] + " a帽os") | |
| col2.subheader("蟽 = "+str((dist_gamma//12).std())[0:4] + " a帽os") | |
| st.subheader("Distribuci贸n de retorno anual") | |
| col1, col2 = st.beta_columns((3, 1)) | |
| df_ret = pd.DataFrame(retornos, columns=["retornos"]) | |
| col2.title(" ") | |
| col2.header("碌 = "+str((retornos.mean()*100))[0:4] + "%") | |
| col2.subheader("蟽 = "+str((retornos.std())*100)[0:4] + "%") | |
| fig2 = px.histogram(df_ret, x="retornos", nbins=50) | |
| retorno_fc = (1.053)*(1.0312)-1 | |
| if retornos.mean() > 0.0312: | |
| posicion1 = "top right" | |
| posicion2 = "top left" | |
| else: | |
| posicion2 = "top right" | |
| posicion1 = "top left" | |
| fig2.add_vline(x=retornos.mean(), line_width=3, line_dash="dash", | |
| line_color="midnightblue", annotation_font_color="midnightblue", | |
| annotation_position=posicion1, | |
| annotation_text=str(round(retornos.mean()*100, 1))+"%") | |
| fig2.add_vline(x=0.0312, line_width=3, line_dash="dash", | |
| annotation_font_color="red", | |
| annotation_position=posicion2, | |
| line_color="red", annotation_text="3,12%") | |
| fig2.add_vline(x=retorno_fc, line_width=3, line_dash="dash", | |
| annotation_font_color="green", | |
| annotation_position=posicion2, | |
| line_color="green", annotation_text=str(round(retorno_fc, 2)*100)+"%") | |
| fig2.add_vline(x=0.00, line_width=3, line_dash="dash", | |
| line_color="yellow") | |
| col1.plotly_chart(fig2, use_container_width=True) | |
| col1, col2 = st.beta_columns((1, 8)) | |
| col2.write(str(round(sum(df_ret["retornos"] > 0.00)/len(df_ret)*100, 0)) + | |
| "%: Probabilidad de que un clientes tenga retorno mayor a 0%") | |
| col2.write(str(round(sum(df_ret["retornos"] > 0.0312)/len(df_ret)*100, 0)) + | |
| "%: Probabilidad de que un clientes tenga un retorno mayor a 3,12% (Inflaci贸n)") | |
| col2.write(str(round(sum(df_ret["retornos"] > retorno_fc)/len(df_ret)*100, 0)) + | |
| "%: Probabilidad de que un clientes tenga retorno mayor a "+str(round(retorno_fc, 2)*100)+"% (Fondo C)") | |
| def sim_2(): | |
| with st.form(key='my_form'): | |
| col1, col2 = st.beta_columns(2) | |
| sim = col1.number_input("N潞 Simulaciones", min_value=1, value=100) | |
| vc = col2.number_input("Cuota inicial", min_value=100) | |
| col1, col2, col3 = st.beta_columns(3) | |
| mu = col1.number_input("碌 Fondo Arriesgado", value=0.1) | |
| sigma = col1.number_input("蟽 Fondo Arriesgado", value=0.1) | |
| mu2 = col2.number_input("碌 Fondo Intermedio ", value=0.05) | |
| sigma2 = col2.number_input("蟽 Fondo Intermedio", value=0.05) | |
| mu3 = col3.number_input("碌 Fondo Conservador", value=-0.01) | |
| sigma3 = col3.number_input("蟽 Fondo Conservador", value=0.03) | |
| values = st.slider('Seleccione los a帽os de cambio de fondo', 0, 40, | |
| (33, 38)) | |
| with st.beta_expander("Ajustar par谩metros de distribucion de permanencia del cliente (gamma)"): | |
| col1, col2 = st.beta_columns(2) | |
| alpha = col1.number_input("alpha", value=1.5) | |
| beta = col2.number_input("lambda", value=71.1) | |
| submit_button = st.form_submit_button(label='Actualizar') | |
| if submit_button: | |
| t = values[0]*12 | |
| t2 = values[1]*12-t | |
| t3 = 480-t2-t | |
| mu = mu / 12 | |
| mu2 = mu2 / 12 | |
| mu3 = mu3 / 12 | |
| sigma = sigma / (12 ** (1/2)) | |
| sigma2 = sigma2 / (12 ** (1/2)) | |
| sigma3 = sigma3 / (12 ** (1/2)) | |
| var_al = np.random.normal(mu, sigma, size=(t, sim)) | |
| var_al2 = np.random.normal(mu2, sigma2, size=(t2, sim)) | |
| var_al3 = np.random.normal(mu3, sigma3, size=(t3, sim)) | |
| simulacion = np.zeros((t + t2 + t3, sim)) | |
| simulacion[0, :] = vc | |
| dist_gamma = stats.gamma.rvs(alpha, scale=beta, size=sim).astype(int)+1 | |
| for i in range(1, t): | |
| simulacion[i, :] = simulacion[i - 1, :] * (1 + var_al[i-1, :]) | |
| for i in range(t, t+t2): | |
| simulacion[i, :] = simulacion[i - 1, :] * (1 + var_al2[t-i-1, :]) | |
| for i in range(t+t2, t+t2+t3): | |
| simulacion[i, :] = simulacion[i - 1, :] * \ | |
| (1 + var_al3[t2+t-i-1, :]) | |
| retornos = np.zeros(sim) | |
| for j in range(sim): | |
| ingreso = 480-dist_gamma[j] | |
| simulacion[0:ingreso, j] = None | |
| simulacion[ingreso:480, j] = simulacion[ingreso:480, j] * \ | |
| vc/simulacion[ingreso, j] | |
| retorno = (simulacion[-1, j]/simulacion[ingreso, j] | |
| )**(1/(dist_gamma[j]/12))-1 | |
| retornos[j] = retorno | |
| df = pd.DataFrame(simulacion) | |
| df["meses"] = list(df.index) | |
| fig = px.line(df, x="meses", y=df.columns, | |
| title='Simulaciones') | |
| fig.layout.update(xaxis_rangeslider_visible=True) | |
| fig.add_vline(x=t, line_width=3, line_dash="dash", line_color="grey") | |
| fig.add_vline(x=t+t2, line_width=3, line_dash="dash", | |
| line_color="grey") | |
| fig.add_vrect(x0=0, x1=t, annotation_text="Arries", | |
| annotation_position="top", | |
| fillcolor="red", opacity=0.15, line_width=0) | |
| fig.add_vrect(x0=t, x1=t+t2, | |
| annotation_text="Inter", annotation_position="top", | |
| fillcolor="midnightblue", opacity=0.15, line_width=0) | |
| fig.add_vrect(x0=t + t2, x1=t + t2 + t3, | |
| annotation_text="Cons", annotation_position="top", | |
| fillcolor="seagreen", opacity=0.15, line_width=0) | |
| fig.update_layout(height=600, width=950) | |
| st.plotly_chart(fig, use_container_width=True) | |
| sigma_sim1 = np.random.normal(sigma, 0.009, size=480) | |
| sigma_sim2 = np.random.normal(sigma2, 0.004, size=480) | |
| sigma_sim3 = np.random.normal(sigma3, 0.001, size=480) | |
| sigma_comb = np.zeros(480) | |
| sigma_comb[0:t] = sigma_sim1[0:t] | |
| sigma_comb[t:t+t2] = sigma_sim2[t:t+t2] | |
| sigma_comb[t+t2:480] = sigma_sim3[t+t2:480] | |
| sigma_comb2 = np.zeros(480) | |
| retorno_comb = np.zeros(480) | |
| for i in range(t): | |
| sigma_comb2[i] = sigma_sim1[i] * (1-i/t) + sigma_sim2[i] * i/t | |
| retorno_comb[i] = mu * (1-i/t) + mu2 * i/t | |
| for j in range(480-t): | |
| sigma_comb2[t + j] = sigma_sim2[t + j] * \ | |
| (1-j/(480-t)) + sigma_sim3[t + j] * j/(480-t) | |
| retorno_comb[i] = mu2 * (1-j/(480-t)) + mu3 * j/(480-t) | |
| dfsig = pd.DataFrame(sigma_sim1, columns=["sig"]) | |
| dfsig["mes"] = list(dfsig.index) | |
| dfsig["sigma inter"] = sigma_sim2 | |
| dfsig["sigma cons"] = sigma_sim3 | |
| dfsig["sigma por periodos"] = sigma_comb | |
| dfsig["sigma combinacion lineal"] = sigma_comb2 | |
| dfsig["sigma combinacion lineal"] = dfsig["sigma combinacion lineal"].abs() | |
| var_al_comb = np.zeros(480) | |
| patr_al_comb = np.zeros(480) | |
| patr_al_comb[0] = vc | |
| for i in range(1, 480): | |
| var_al_comb[i] = np.random.normal( | |
| retorno_comb[i], | |
| dfsig["sigma combinacion lineal"].iloc[i], | |
| size=1) | |
| patr_al_comb[i] = patr_al_comb[i-1]*(1 + var_al_comb[i-1]) | |
| ingreso = 480-dist_gamma[0] | |
| data_comb = pd.DataFrame(patr_al_comb, columns=["Precio"]) | |
| data_comb["mes"] = list(data_comb.index) | |
| data_comb = data_comb[data_comb["mes"] >= ingreso] | |
| data_comb["Precio"] = data_comb["Precio"]/data_comb.iloc[0]["Precio"] | |
| fig2 = px.line(dfsig, x='mes', y=dfsig.columns, | |
| title='Simulaciones') | |
| st.plotly_chart(fig2) | |
| fig3 = px.line(data_comb, x='mes', y=data_comb.columns, | |
| title='Simulaciones') | |
| st.plotly_chart(fig3) | |
| def sim_inmob(): | |
| url = """postgresql://tbgxsndupdarfp:5578576bc884e31a4f7e117a66a9dad8b13917e6a5262d85ff20f1f69cb4bf49@ec2-52-205-45-219.compute-1.amazonaws.com:5432/db5ktai215krcv""" | |
| engine = create_engine(url, echo=False) | |
| data = pd.read_sql_query("SELECT * FROM Scraping_inmob", con=engine) | |
| data = transform_df(data) | |
| col1, col2 = st.beta_columns((0.65, 1)) | |
| placeholder = st.empty() | |
| placeholder2 = st.empty() | |
| placeholder3 = st.empty() | |
| placeholder4 = st.empty() | |
| dist_gamma = stats.gamma.rvs(1, scale=250000, size=2965) | |
| dist_norm = np.random.normal(734874, 1250, size=2965) | |
| data_hist = data[data["mercado"] == "venta"] | |
| data_hist = data_hist[data_hist["valor_peso"] | |
| < 400000000]["valor_peso"] * 0.2 | |
| fig2 = go.Figure() | |
| fig3 = go.Figure() | |
| fig4 = go.Figure() | |
| fig2.add_trace(go.Histogram(x=dist_norm, name='Dist Ingreso')) | |
| # fig2.add_vline(x=data_hist.mean(), line_width=3, line_dash="dash", line_color="darkred") | |
| # fig2.add_vline(x=dist_gamma.mean(), line_width=3, line_dash="dash", line_color="darkblue") | |
| fig3.add_trace(go.Histogram(x=data_hist, name='Data real')) | |
| a = sorted(data_hist) | |
| b = sorted(dist_norm) | |
| dist_periodo = [(x)/y for x, y in zip(a, b)] | |
| dist_periodo = [i for i in dist_periodo if i < 480] | |
| fig4.add_trace(go.Histogram(x=dist_periodo, name='Dist periodo')) | |
| # Overlay both histograms | |
| # fig2.update_layout(barmode='overlay') | |
| # Reduce opacity to see both histograms | |
| fig2.update_traces(opacity=0.75) | |
| #fig2 = px.histogram((data_hist), x='valor_peso', color_discrete_sequence=['indianred']) | |
| placeholder2.plotly_chart(fig2, use_container_width=True) | |
| placeholder.subheader("碌 Capacidad de ahorro: $" + | |
| formatnum(dist_norm.mean())) | |
| placeholder4.plotly_chart(fig3, use_container_width=True) | |
| placeholder3.subheader("碌 Pie vivienda: $" + formatnum(data_hist.mean())) | |
| st.plotly_chart(fig4, use_container_width=True) | |
| st.subheader("碌 Period: " + formatnum(np.array(dist_periodo).mean())) | |
| df = pd.DataFrame([a, b, dist_periodo]) | |
| df2 = df.T | |
| st.markdown(get_table_excel_link(df2[df2[2] < 480], "Distribucion"), | |
| unsafe_allow_html=True) | |
| data_hist = data[data["mercado"] == "venta"] | |
| data_hist = data_hist[data_hist["valor_peso"] > 40000000] | |
| data_hist = data_hist[data_hist["valor_peso"] | |
| < 1000000000]["valor_peso"] * 0.2 | |
| fig2 = px.histogram((data_hist), x='valor_peso') | |
| def sim_ingreso_clientes(): | |
| with st.form(key='my_form'): | |
| col1, col2 = st.beta_columns(2) | |
| clientes1 = col1.number_input("Clientes nuevos a帽o 1", value=1250) | |
| clientes2 = col2.number_input("Clientes nuevos a帽o 2", value=6750) | |
| clientes3 = col1.number_input("Clientes nuevos a帽o 3", value=17000) | |
| clientes4 = col2.number_input("Clientes nuevos a帽o 4", value=17000) | |
| clientes5 = col1.number_input("Clientes nuevos a帽o 5", value=8000) | |
| col1, col2 = st.beta_columns(2) | |
| cap_ahorro = col1.number_input("Capacidad de ahorro", 735000) | |
| de_cap = col2.number_input("Desviacion estandar C.A.", 1250) | |
| submit_button = st.form_submit_button(label='Actualizar') | |
| if submit_button: | |
| clientesm1 = clientes1/12 | |
| clientesm2 = clientes2/12 | |
| clientesm3 = clientes3/12 | |
| clientesm4 = clientes4/12 | |
| clientesm5 = clientes5/12 | |
| porc_mult = 0.46 | |
| porc_cp = 0.19 | |
| porc_lp = 0.35 | |
| inmob = np.zeros(60) | |
| a = np.zeros(60) | |
| b = np.zeros(60) | |
| c = np.zeros(60) | |
| cp = np.zeros(60) | |
| lp = np.zeros(60) | |
| inmob[0] = int(clientesm1 * porc_mult) | |
| cp[0] = int(clientesm1 * porc_cp) | |
| lp[0] = int(clientesm1 * porc_lp) | |
| for i in range(1, 60): | |
| if i < 12: | |
| inmob[i] =int( clientesm1 * porc_mult + inmob[i-1]) | |
| cp[i] = int(clientesm1 * porc_cp + cp[i-1]) | |
| lp[i] = int(clientesm1 * porc_lp + lp[i-1]) | |
| a[i] = cp[i] | |
| b[i] = lp[i] | |
| c[i] = inmob[i] | |
| elif i < 24: | |
| inmob[i] = int(clientesm2 * porc_mult + inmob[i-1]) | |
| cp[i] = int(clientesm2 * porc_cp + cp[i-1]) + clientesm1 * porc_cp*0.8 | |
| lp[i] = int(clientesm2 * porc_lp + lp[i-1]) | |
| a[i] = cp[i] | |
| b[i] = lp[i] + c[i-12] | |
| c[i] = inmob[i] - c[i-12] | |
| elif i < 36: | |
| inmob[i] = int(clientesm3 * porc_mult + inmob[i-1]) | |
| cp[i] = int(clientesm3 * porc_cp + cp[i-1]) + clientesm2 * porc_cp*0.8 | |
| lp[i] = int(clientesm3 * porc_lp + lp[i-1]) | |
| a[i] = cp[i] | |
| b[i] = lp[i] + c[i-24] + c[i-12] | |
| c[i] = inmob[i] - c[i-24] - c[i-12] | |
| elif i < 48: | |
| inmob[i] = int(clientesm4 * porc_mult + inmob[i-1]) | |
| cp[i] = int(clientesm4 * porc_cp + cp[i-1]) - clientesm3 * porc_cp*0.8 | |
| lp[i] = int(clientesm4 * porc_lp + lp[i-1]) | |
| a[i] = cp[i] + c[i-36] | |
| b[i] = lp[i] + c[i-24] + c[i-12] | |
| c[i] = inmob[i] - c[i-24] - c[i-12] - c[i-36] | |
| elif i < 60: | |
| inmob[i] = int(clientesm5 * porc_mult + inmob[i-1]) | |
| cp[i] = int(clientesm5 * porc_cp + cp[i-1]) + clientesm4 * porc_cp*0.8 | |
| lp[i] = int(clientesm5 * porc_lp + lp[i-1]) | |
| a[i] = cp[i] + c[i-36] | |
| b[i] = lp[i] + c[i-24] + c[i-12] | |
| c[i] = inmob[i] - c[i-24] - c[i-12] - c[i-36] - c[i-48] | |
| inmob_res = np.zeros(60) | |
| cp_res = np.zeros(60) | |
| lp_res = np.zeros(60) | |
| a_res = np.zeros(60) | |
| b_res = np.zeros(60) | |
| c_res = np.zeros(60) | |
| for i in range(1, 60): | |
| if i<12: | |
| pass | |
| elif i < 24: | |
| cp_res[i] = - clientes1 * porc_cp*0.2 | |
| b_res[i] = clientes1 * porc_mult | |
| c_res[i] = -clientes1 * porc_mult | |
| elif i < 36: | |
| cp_res[i] = - clientes2 * porc_cp * 0.2 | |
| b_res[i] = clientes2 * porc_mult | |
| c_res[i] = -clientes2 * porc_mult | |
| elif i < 48: | |
| cp_res[i] = - clientes3 * porc_cp * 0.2 | |
| a_res[i] = clientes1 * porc_mult * 3 | |
| b_res[i] = clientes3 * porc_mult - clientes1 * 3 * porc_mult | |
| c_res[i] = -clientes3 * porc_mult | |
| elif i < 60: | |
| cp_res[i] = - clientes4 * porc_mult * 0.2 | |
| a_res[i] = clientes2 * 3 *porc_mult | |
| b_res[i] = clientes3 * porc_mult - clientes2 * 3 *porc_mult | |
| c_res[i] = -clientes3 * porc_mult | |
| st.write(cp-cp_res) | |
| inmob[0] = int(clientesm1 * porc_mult) | |
| cp[0] = int(clientesm1 * porc_cp) | |
| lp[0] = int(clientesm1 * porc_lp) | |
| anual = np.zeros((5,4)) | |
| anual_aum = np.zeros((5,4)) | |
| for i in range(5): | |
| anual[i, 0] = int(sum(a[i*12:(i+1)*12])) | |
| anual[i, 1] = int(sum(b[i*12:(i+1)*12])) | |
| anual[i, 2] = int((sum(c[i*12:(i+1)*12]))) | |
| anual[:,3] = anual[:,0] + anual[:,1] + anual[:,2] | |
| for i in range(5): | |
| anual_aum[i, 0] = sum(((a - a_res)*cap_ahorro)[0:(i+1)*12]) | |
| anual_aum[i, 1] = sum(((b - b_res)*cap_ahorro)[0:(i+1)*12]) | |
| anual_aum[i, 2] = sum(((c - c_res)*cap_ahorro)[0:(i+1)*12]) | |
| anual_aum[:,3] = anual_aum[:,0] + anual_aum[:,1] + anual_aum[:,2] | |
| data = pd.DataFrame([cp, lp, inmob, (cp - cp_res)*cap_ahorro, lp*cap_ahorro, | |
| (inmob - inmob_res)*cap_ahorro]) | |
| anual[:,3] = anual[:,0] + anual[:,1] + anual[:,2] | |
| cambios = np.zeros(5) | |
| cambios[0] = 0 | |
| cambios[1] = int(clientes1 * porc_mult) | |
| cambios[2] = int(clientes2* porc_mult) | |
| cambios[3] = int((clientes3 + clientes1)* porc_mult) | |
| cambios[4] = int((clientes2 + clientes4) * porc_mult) | |
| retiros = np.zeros(5) | |
| retiros[0] = 0 | |
| retiros[1] = int(clientes1 * porc_cp) | |
| retiros[2] = int(clientes2 * porc_cp) | |
| retiros[3] = int(clientes3 * porc_cp) | |
| retiros[4] = int(clientes4 * porc_cp +clientes1 * porc_cp*porc_mult) | |
| clientes_a = np.zeros(5) | |
| clientes_b = np.zeros(5) | |
| clientes_c = np.zeros(5) | |
| clientes_a[0] = int(clientes1 * porc_cp) | |
| clientes_b[0] = int(clientes1 * porc_lp) | |
| clientes_c[0] = int(clientes1 * porc_mult) | |
| clientes_a[1] = int(clientes2 * porc_cp + clientes1 * porc_cp * 0.8) | |
| clientes_b[1] = int(clientes1 * porc_lp + clientes2 * porc_lp + clientes1 * porc_mult) | |
| clientes_c[1] = int(clientes2 * porc_mult) | |
| clientes_a[2] = int(clientes3 * porc_cp + clientes2 * porc_cp * 0.8 + clientes1 * porc_cp * 0.8) | |
| clientes_b[2] = int(clientes_b[1] + clientes2 * porc_mult + clientes3 * porc_lp ) | |
| clientes_c[2] = int(clientes3 * porc_mult) | |
| clientes_a[3] = int(clientes4 * porc_cp + clientes1 * porc_mult + clientes2 * porc_cp * 0.8 + clientes1 * porc_cp * 0.8 + clientes3 * porc_cp * 0.8) | |
| clientes_b[3] = int(clientes_b[2] - clientes1 * porc_mult + clientes3 * porc_mult + clientes4 * porc_lp) | |
| clientes_c[3] = int(clientes4 * porc_mult) | |
| clientes_a[4] = int(clientes5 * porc_cp + clientes1 * porc_mult + clientes2 * porc_mult + clientes4 *0.8* porc_cp + clientes2 * porc_cp * 0.8 + clientes1 * porc_cp * 0.8 + clientes3 * porc_cp * 0.8) | |
| clientes_b[4] = int(clientes_b[3] - clientes2 * porc_mult + clientes4 * porc_mult + clientes5 * porc_lp ) | |
| clientes_c[4] = int(clientes5 * porc_mult) | |
| data2 = pd.DataFrame(anual, columns = ["Depositos a", "Depositos b", "Depositos c", "Dep Total"]) | |
| data3 = pd.DataFrame(anual_aum, columns = ["a AUM", "b AUM", "c Aum", "Aum Total"]) | |
| data4 = pd.DataFrame([a,b,c]) | |
| st.write(data4) | |
| data = data.T | |
| data4 = data4.T | |
| data4.columns = ["Fondo A", "Fondo B", "Fondo C"] | |
| data3["Cambios"] = cambios | |
| data3["Retiros"] = retiros | |
| data3["Clientes a"] = clientes_a | |
| data3["Clientes b"] = clientes_b | |
| data3["Clientes c"] = clientes_c | |
| data3["Dep totales"] = data2["Dep Total"] | |
| fig = px.line(data4, x=data4.index, y=data4._) | |
| st.plotly_chart(fig, use_container_width=True) | |
| st.write(data3.T) | |
| st.markdown(get_table_excel_link(data3.T, "Estimaci贸n demanda"), | |
| unsafe_allow_html=True) | |
| import matplotlib.pyplot as plt | |
| import numpy as np | |
| import streamlit as st | |
| import time | |
| import statistics | |
| def simulacion_final(): | |
| import altair as alt | |
| from altair import datum | |
| with st.form("Form"): | |
| cols = st.columns(3) | |
| capital_inicial = cols[0].number_input("Capital inicial", value=1000000, format="%d") | |
| cap_ahorro = cols[1].number_input("Capacidad de ahorro", value=750000, format='%d') | |
| objetivo = cols[2].number_input("Objetivo", value=40000000, format="%u") | |
| button_2 = st.form_submit_button("Comenzar simulacion") | |
| my_bar = st.sidebar.progress(0) | |
| progress = 0 | |
| periodo = int(objetivo/cap_ahorro)+1 | |
| periodo_cambio = int(periodo*3/5) | |
| periodo_cambio = int(periodo*3/5) | |
| periodo_cambio2 = int(periodo*4/5) | |
| l_1=[capital_inicial] | |
| l_2=[0] | |
| l_3 = [] | |
| l_4 = [] | |
| l_5 = [] | |
| l_6 = [] | |
| volatilidad = [] | |
| drawdown = False | |
| corte_antes = False | |
| cambio = 0 | |
| lista2=l_1+l_2+l_3 | |
| chart_row = st.empty() | |
| if button_2: | |
| for j in range(1,periodo+4): | |
| lista =np.array(l_1+l_3+l_5) | |
| if lista[-1] > objetivo: | |
| corte_antes = True | |
| corte = j | |
| periodo = j | |
| break | |
| else: | |
| if j <= 12: | |
| volatilidad.append(0) | |
| # elif j < 12 and j >3: | |
| # volatilidad.append(statistics.stdev((lista[1:j]/lista[0:j-1]))) | |
| else: | |
| retornos = ((lista[j-11:j]-cap_ahorro)/lista[j-12:j-1]) | |
| volatilidad.append(statistics.stdev(retornos)) | |
| if statistics.stdev(retornos) > 0.13 and j==periodo_cambio: | |
| drawdown=True | |
| cambio =+ 6 | |
| if j < periodo_cambio: | |
| sig = abs(np.random.normal(0.04,0.1)) | |
| a = np.random.normal(0.018,sig) | |
| elif j < periodo_cambio2 and not drawdown: | |
| sig = abs(np.random.normal(0.03,0.04)) | |
| a = np.random.normal(0.01,sig) | |
| elif j < periodo_cambio2 and drawdown: | |
| sig = abs(np.random.normal(0.04,0.1)) | |
| a = np.random.normal(0.018,sig) | |
| drawdown=False | |
| else: | |
| sig = abs(np.random.normal(0.005,0.01)) | |
| a = np.random.normal(0,sig) | |
| if j < (periodo_cambio + cambio): | |
| l_1.append(l_1[j-1]*(1+a) + cap_ahorro ) | |
| l_2.append(j) | |
| if j >= (periodo_cambio + cambio) and j <periodo_cambio2: | |
| if (periodo_cambio + cambio) == j: | |
| l_3.append(l_1[j-1]) | |
| l_4.append(j-1) | |
| l_3.append(l_3[j- periodo_cambio- cambio]*(1+a) + cap_ahorro ) | |
| l_4.append(j) | |
| if j >= periodo_cambio2: | |
| if periodo_cambio2 == j: | |
| l_5.append(l_3[j - periodo_cambio - cambio]) | |
| l_6.append(j-1) | |
| l_5.append(l_5[j- periodo_cambio2]*(1+a) + cap_ahorro ) | |
| l_6.append(j) | |
| vol =pd.DataFrame(volatilidad) | |
| cols = st.columns(3) | |
| col1, col2 = st.columns(2) | |
| #st.line_chart(vol) | |
| mas_tmpo = False | |
| if lista[-1] < objetivo: | |
| delta = objetivo-l_5[-1] | |
| t_extra = int(delta/cap_ahorro)+1 | |
| periodo_ant=periodo | |
| mas_tmpo=True | |
| periodo = periodo + t_extra | |
| for i in range(t_extra): | |
| l_5.append(l_5[-1]+ cap_ahorro) | |
| l_6.append(l_6[-1]+ 1) | |
| lista =np.array(l_1+l_3+l_5) | |
| col1.subheader("Analista") | |
| col2.subheader("Cliente") | |
| for i in range(periodo+2): | |
| time.sleep(0.01) | |
| if mas_tmpo==True and i == periodo_ant: | |
| st.write(t_extra) | |
| col2.error("Mes " + str(i) +": Te faltan " + str(t_extra) + " meses para la meta") | |
| time.sleep(3) | |
| if corte_antes==True and i == corte: | |
| col2.success("Mes " + str(i) +": Felcidiades llegaste antes a la meta") | |
| time.sleep(3) | |
| if cambio == 6 and i==(periodo_cambio): | |
| col1.error("Mes " + str(i) +": Estas en drawdown se recomienda esperar 6 meses m谩s") | |
| col2.warning("Mes " + str(i) +": Debes esperar 6 mes mas para cambiarte") | |
| time.sleep(3) | |
| df = pd.DataFrame() | |
| df2 = pd.DataFrame() | |
| df3 = pd.DataFrame() | |
| df["Mes"]=l_2[0:i+1] | |
| df["Valor"]=l_1[0:i+1] | |
| if i >= (periodo_cambio+cambio): | |
| df2["Mes"]=l_4[0:i-periodo_cambio - cambio+1] | |
| df2["Valor"] =l_3[0:i-periodo_cambio - cambio+1] | |
| if i >= periodo_cambio2: | |
| df3["Mes"]=l_6[0:i-periodo_cambio2+2] | |
| df3["Valor"] =l_5[0:i-periodo_cambio2+2] | |
| df["Fondo"] = ["Fondo Arriesgado"]*len(df) | |
| df2["Fondo"] = ["Fondo Intermedio"]*len(df2) | |
| df3["Fondo"] = ["Fondo Conservador"]*len(df3) | |
| df_f = pd.concat([df,df2, df3]) | |
| df_f["Ahorro"] = df_f["Mes"]*cap_ahorro + capital_inicial | |
| if i == (periodo_cambio+cambio): | |
| col2.success("Mes " + str(i) +": Debes cambiarte al Fondo Intermedio") | |
| time.sleep(3) | |
| if i == periodo_cambio2: | |
| col2.success("Mes " + str(i) +": Debes cambiarte al Fondo Conservador") | |
| time.sleep(3) | |
| fig = alt.Chart(df_f).mark_area(opacity=0.6).encode( | |
| x=alt.X('Mes', | |
| scale=alt.Scale(domain=(0, periodo - 1)) | |
| ), | |
| y=alt.X('Valor', | |
| scale=alt.Scale(domain=(0, max(lista)*1.1)) | |
| ), | |
| color=alt.Color("Fondo", scale=alt.Scale(scheme='pastel1')) | |
| ) | |
| bar = fig.mark_bar().encode(y='Ahorro') | |
| chart_row.altair_chart(bar + fig, use_container_width=True) | |
| my_bar.empty() | |
| # from st_card import st_card | |
| # with cols[0]: | |
| # st_card('Capital proyectado', value=df_f.iloc[-1]["Valor"], show_progress=True) | |
| # with cols[1]: | |
| # st_card('Ganancia proyectada', value = df_f.iloc[-1]["Valor"] - df_f.iloc[-1]["Ahorro"], | |
| # delta=round((df_f.iloc[-1]["Valor"]/df_f.iloc[-1]["Ahorro"]-1)*100,0) , | |
| # use_percentage_delta=True, delta_description='de retorno') | |
| # with cols[2]: | |
| # st_card('Meses', value=int(df_f.iloc[-1]["Mes"]), delta=periodo_cambio, delta_description='En el Fondo Arriesgado') | |
| # st.write(df_f) | |
| import streamlit.components.v1 as components | |
| def candidatos(): | |
| html_str =""" | |
| <!DOCTYPE html> | |
| <html lang="es"> | |
| <head> | |
| <title>D3.js - Mapas</title> | |
| <meta charset="utf-8"/> | |
| <!-- d3 馃槏--> | |
| <script src="https://d3js.org/d3.v7.min.js"></script> | |
| <!--nuestro estilo --> | |
| <link type="text/css" rel="stylesheet" href="style.css"/> | |
| </head> | |
| <body> | |
| <h1> | |
| Mapa por regi贸n de votos a Gabriel Boric | |
| </h1> | |
| <p> | |
| <u>Fuente: https://www.futuro.cl/2021/11/elecciones-presidenciales-chile-2021-resultados-region-por-region-en-vivo/</u> | |
| </p> | |
| <div> | |
| <div id="viz1", style = "width:50%"> | |
| <svg id="geoOrthographic1"></svg> | |
| </div> | |
| <script> | |
| //Nos sirve para poder cargar los archivos y luego ejecutar createMap | |
| Promise | |
| .all([ | |
| d3.json('chile.geojson'), | |
| d3.json('chile.geojson') | |
| ]) | |
| .then(resolve => { | |
| createMap1(resolve[1]); | |
| createMap2(resolve[0]); | |
| }); | |
| //creamos el mapa2 | |
| function createMap1(countries) { | |
| const viz1 = d3.select("#viz1"); | |
| const ancho = viz1.style("width").substring(0, viz1.style("width").length - 2) - 10; | |
| console.log("Ancho: " + ancho); | |
| //como proyectamos lo que vamos a dibujar | |
| //https://github.com/d3/d3-geo/blob/master/README.md#d3-geo | |
| //https://github.com/d3/d3-geo-projection#geoConicEqualArea | |
| const projection = d3.geoMercator() | |
| //que tan cercano | |
| .scale(550) | |
| // .translate([ancho / 2, 250]) | |
| //desde el centro, lo podemos mover | |
| .center([-55.6, -40]); | |
| //definimos nuestro geoPath, lo que queremos dibujar | |
| const geoPath = d3.geoPath().projection(projection); | |
| //solo datos | |
| const poblacion = [ | |
| {comuna: "Puente Alto", cantidad: 31.07}, | |
| {comuna: "R铆o Ib谩帽ez", cantidad: 25}, | |
| {comuna: "Tocopilla", cantidad: 20.67}, | |
| {comuna: "Juan Fern谩ndez", cantidad: 28.12}, | |
| {comuna: "Caldera", cantidad: 19.24}, | |
| {comuna: "Castro", cantidad: 20.43}, | |
| {comuna: "Ca帽ete", cantidad: 19.09}, | |
| {comuna: "La Uni贸n", cantidad: 23.05}, | |
| {comuna: "Iquique", cantidad: 18.27}, | |
| {comuna: "San Esteban", cantidad: 28.12}, | |
| {comuna: "Putre", cantidad: 17.79}, | |
| {comuna: "R铆o Hurtado", cantidad: 25.92}, | |
| {comuna: "Torres del Paine", cantidad: 30.64}, | |
| {comuna: "Carahue", cantidad: 16.58}, | |
| {comuna: "Pelluhue", cantidad: 19.58}, | |
| {comuna: "Malloa", cantidad: 24.14}, | |
| ]; | |
| //geoArea nos da el area dado un GeoJson | |
| //extent nos devuelve el minimo y maximo valor | |
| const realFeatureSize = d3.extent(poblacion, function (d) { | |
| return +d.cantidad | |
| }); | |
| console.log("M铆nimo y M谩ximo: "); | |
| console.log(realFeatureSize); | |
| //hacemos un escala para los colores | |
| //veamos cual es el rango | |
| //https://github.com/d3/d3-scale#scaleQuantize | |
| const newFeatureColor = d3.scaleQuantize() | |
| .domain(realFeatureSize) | |
| .range(['#fee0d2','#fc9272','#de2d26']); | |
| //Nada nuevo, aqui hacemos el dibujo | |
| d3.select("#geoOrthographic1").selectAll("path") | |
| .data(countries.features).enter() | |
| .append("path") | |
| .attr("d", geoPath) | |
| .attr("id", d => d.id) | |
| .attr("class", "countries") | |
| .style("fill", d => { | |
| //comentar la linea de abajo para ver que hace el resto | |
| //return "grey" | |
| console.log(d.properties.NOM_COM); | |
| let poblacionEncontrada; | |
| poblacion.forEach(function (e) { | |
| console.log(d.properties.NOM_COM); | |
| console.log(e.comuna); | |
| if (e.comuna === d.properties.NOM_COM) { | |
| poblacionEncontrada = e.cantidad; | |
| } | |
| }); | |
| return newFeatureColor(poblacionEncontrada) | |
| }) | |
| .style("stroke", d => d3.rgb(newFeatureColor(d3.geoArea(d))).darker()); | |
| // //generamos la "grilla" | |
| // const graticule = d3.geoGraticule(); | |
| // | |
| // //dibujamos la grilla | |
| // d3.select("#geoOrthographic1").insert("path", "path.countries") | |
| // .datum(graticule) | |
| // .attr("class", "graticule line") | |
| // .attr("d", geoPath); | |
| const zoom = d3.zoom() | |
| .scaleExtent([1, 8]) | |
| .on('zoom', function (event) { | |
| d3.select("#geoOrthographic1").selectAll('path') | |
| .attr('transform', event.transform); | |
| }); | |
| d3.select("#geoOrthographic1").call(zoom); | |
| } | |
| //creamos el mapa | |
| //Nos sirve para poder cargar los archivos y luego ejecutar createMap | |
| //creamos el mapa2 | |
| function createMap2(countries) { | |
| const viz1 = d3.select("#viz2"); | |
| const ancho = viz1.style("width").substring(0, viz1.style("width").length - 2) - 10; | |
| console.log("Ancho: " + ancho); | |
| //como proyectamos lo que vamos a dibujar | |
| //https://github.com/d3/d3-geo/blob/master/README.md#d3-geo | |
| //https://github.com/d3/d3-geo-projection#geoConicEqualArea | |
| const projection = d3.geoMercator() | |
| //que tan cercano | |
| .scale(550) | |
| // .translate([ancho / 2, 250]) | |
| //desde el centro, lo podemos mover | |
| .center([-55.6, -40]); | |
| //definimos nuestro geoPath, lo que queremos dibujar | |
| const geoPath = d3.geoPath().projection(projection); | |
| //solo datos | |
| const poblacion = [ | |
| {comuna: "Puente Alto", cantidad: 31.07}, | |
| {comuna: "R铆o Ib谩帽ez", cantidad: 25}, | |
| {comuna: "Tocopilla", cantidad: 20.67}, | |
| {comuna: "Juan Fern谩ndez", cantidad: 28.12}, | |
| {comuna: "Caldera", cantidad: 19.24}, | |
| {comuna: "Castro", cantidad: 20.43}, | |
| {comuna: "Ca帽ete", cantidad: 19.09}, | |
| {comuna: "La Uni贸n", cantidad: 23.05}, | |
| {comuna: "Iquique", cantidad: 18.27}, | |
| {comuna: "San Esteban", cantidad: 28.12}, | |
| {comuna: "Putre", cantidad: 17.79}, | |
| {comuna: "R铆o Hurtado", cantidad: 25.92}, | |
| {comuna: "Torres del Paine", cantidad: 30.64}, | |
| {comuna: "Carahue", cantidad: 16.58}, | |
| {comuna: "Pelluhue", cantidad: 19.58}, | |
| {comuna: "Malloa", cantidad: 24.14}, | |
| ]; | |
| //geoArea nos da el area dado un GeoJson | |
| //extent nos devuelve el minimo y maximo valor | |
| const realFeatureSize = d3.extent(poblacion, function (d) { | |
| return +d.cantidad | |
| }); | |
| console.log("M铆nimo y M谩ximo: "); | |
| console.log(realFeatureSize); | |
| //hacemos un escala para los colores | |
| //veamos cual es el rango | |
| //https://github.com/d3/d3-scale#scaleQuantize | |
| const newFeatureColor = d3.scaleQuantize() | |
| .domain(realFeatureSize) | |
| .range(['#fee0d2','#fc9272','#de2d26']); | |
| //Nada nuevo, aqui hacemos el dibujo | |
| d3.select("#geoOrthographic2").selectAll("path") | |
| .data(countries.features).enter() | |
| .append("path") | |
| .attr("d", geoPath) | |
| .attr("id", d => d.id) | |
| .attr("class", "countries") | |
| .style("fill", d => { | |
| //comentar la linea de abajo para ver que hace el resto | |
| //return "grey" | |
| console.log(d.properties.NOM_COM); | |
| let poblacionEncontrada; | |
| poblacion.forEach(function (e) { | |
| console.log(d.properties.NOM_COM); | |
| console.log(e.comuna); | |
| if (e.comuna === d.properties.NOM_COM) { | |
| poblacionEncontrada = e.cantidad; | |
| } | |
| }); | |
| return newFeatureColor(poblacionEncontrada) | |
| }) | |
| .style("stroke", d => d3.rgb(newFeatureColor(d3.geoArea(d))).darker()); | |
| // //generamos la "grilla" | |
| // const graticule = d3.geoGraticule(); | |
| // | |
| // //dibujamos la grilla | |
| // d3.select("#geoOrthographic1").insert("path", "path.countries") | |
| // .datum(graticule) | |
| // .attr("class", "graticule line") | |
| // .attr("d", geoPath); | |
| const zoom = d3.zoom() | |
| .scaleExtent([1, 8]) | |
| .on('zoom', function (event) { | |
| d3.select("#geoOrthographic2").selectAll('path') | |
| .attr('transform', event.transform); | |
| }); | |
| d3.select("#geoOrthographic2").call(zoom); | |
| } | |
| //creamos el mapa1 | |
| </script> | |
| </div> | |
| </body> | |
| </html> | |
| """ | |
| components.html(html_str, height=1000) | |
| # def simulacion_final(): | |
| # import altair as alt | |
| # from altair import datum | |
| # with st.form("Form"): | |
| # cols = st.beta_columns(3) | |
| # capital_inicial = cols[0].number_input("Objetivo", value=1000000, format="%d") | |
| # cap_ahorro = cols[1].number_input("Capacidad de ahorro", value=750000, format='%d') | |
| # objetivo = cols[2].number_input("Objetivo", value=40000000, format="%u") | |
| # button_2 = st.form_submit_button("Comenzar simulacion") | |
| # l_1=[capital_inicial] | |
| # l_2=[0] | |
| # l_3=[np.nan] | |
| # l_4=[np.nan] | |
| # text=[] | |
| # chart_row = st.empty() | |
| # if button_2: | |
| # my_bar = st.sidebar.progress(0) | |
| # progress = 0 | |
| # periodo = int(objetivo/cap_ahorro)+1 | |
| # periodo_cambio = int(periodo*3/5) | |
| # periodo_cambio2 = int(periodo*4/5) | |
| # for j in range(1,periodo): | |
| # a = np.random.normal(0.03,0.10) | |
| # if j <periodo_cambio: | |
| # l_1.append(l_1[j-1]*(1+a) + cap_ahorro ) | |
| # l_3.append(np.nan) | |
| # l_4.append(np.nan) | |
| # text.append("") | |
| # elif j ==periodo_cambio: | |
| # l_1.append(l_1[j-1]*(1+a) + cap_ahorro ) | |
| # l_3.append(l_1[j-1]*(1+a) + cap_ahorro ) | |
| # l_4.append(np.nan) | |
| # text.append("") | |
| # elif j > periodo_cambio and j < periodo_cambio2 : | |
| # a = a/3 | |
| # l_1.append(np.nan) | |
| # l_3.append(l_3[j-1]*(1+a) + cap_ahorro) | |
| # l_4.append(np.nan) | |
| # text.append("") | |
| # elif j == periodo_cambio2: | |
| # a = a/3 | |
| # l_1.append(np.nan) | |
| # l_3.append(l_3[j-1]*(1+a) + cap_ahorro) | |
| # l_4.append(l_3[j-1]*(1+a) + cap_ahorro) | |
| # text.append("") | |
| # else: | |
| # a = a/5 | |
| # l_1.append(np.nan) | |
| # l_3.append(np.nan) | |
| # l_4.append(l_4[j-1]*(1+a) + cap_ahorro) | |
| # text.append("") | |
| # l_2.append(j) | |
| # drawd =[] | |
| # for k in range(2,len(l_1)): | |
| # if (l_1[k] - l_1[k-1])/(l_1[k]) < -0.01: | |
| # periodo_cambio1_2 = periodo_cambio + 1 | |
| # drawd.append(k) | |
| # else: | |
| # periodo_cambio1_2=periodo_cambio | |
| # for i in range(periodo): | |
| # progress = (i/periodo) | |
| # my_bar = my_bar.progress(progress) | |
| # time.sleep(0.001) | |
| # df = pd.DataFrame() | |
| # df["Mes"]=l_2[0:i+1]+l_2[0:i+1] + l_2[0:i+1] | |
| # df["Valor"]=l_1[0:i+1]+l_3[0:i+1] + l_4[0:i+1] | |
| # if i <= periodo_cambio: | |
| # df["Fondo"]=["Fondo Arriesgado"]*len(df) | |
| # if i in drawd: | |
| # st.warning("Drawdown") | |
| # time.sleep(2) | |
| # elif i > periodo_cambio and i <= periodo_cambio2: | |
| # df["Fondo"]=["Fondo Arriesgado"]*(periodo_cambio+1) + ["Fondo Intermedio"]*(i-periodo_cambio) + ["Fondo Arriesgado"]*(periodo_cambio + 1) + ["Fondo Intermedio"]*(i-periodo_cambio) + ["Fondo Arriesgado"]*(periodo_cambio+1) + ["Fondo Intermedio"]*(i-periodo_cambio) | |
| # else: | |
| # a = ["Fondo Arriesgado"] * periodo_cambio | |
| # b = ["Fondo Intermedio"] * (periodo_cambio2 - periodo_cambio-1) | |
| # c = ["Fondo Conservador"] * (i-periodo_cambio2) | |
| # d = ["Fondo Arriesgado"] * (periodo_cambio+2) | |
| # e = ["Fondo Intermedio"] * (periodo_cambio2 - (periodo_cambio+2)) | |
| # f = ["Fondo Conservador"]*(i-periodo_cambio2+2) | |
| # df["Fondo"]= a + b + c + d + e + f + d + e + f | |
| # df = df.dropna() | |
| # if i == periodo_cambio: | |
| # placeholder=st.empty() | |
| # placeholder.info("Debes cambiarte al fondo intermedio") | |
| # time.sleep(3) | |
| # placeholder.empty() | |
| # if i == periodo_cambio2: | |
| # placeholder=st.empty() | |
| # placeholder.info("Debes cambiarte al fondo conservador") | |
| # time.sleep(3) | |
| # placeholder.empty() | |
| # # df=df.dropna() | |
| # fig = alt.Chart(df).mark_area(opacity=0.6).encode( | |
| # x=alt.X('Mes', | |
| # scale=alt.Scale(domain=(0, periodo - 1)) | |
| # ), | |
| # y=alt.X('Valor', | |
| # scale=alt.Scale(domain=(0, max(l_1+l_3+l_4)*1.1)) | |
| # ), | |
| # color=alt.Color("Fondo", scale=alt.Scale(scheme='category20')) | |
| # ) | |
| # if i > periodo_cambio and i <= periodo_cambio2: | |
| # df["Cambio"]="Cambiate al fondo intermedio" | |
| # text = ( | |
| # alt.Chart(df[df["Mes"]==periodo_cambio]) | |
| # .mark_text(dy=-25, color="black") | |
| # .encode(x=alt.X("Mes"), y=alt.Y("Valor"), text="Cambio") | |
| # ) | |
| # chart_row.altair_chart(fig + text, use_container_width=True) | |
| # if i > periodo_cambio2: | |
| # df["Cambio"]="Cambiate al fondo conservador" | |
| # text = ( | |
| # alt.Chart(df[df["Mes"]==periodo_cambio2]) | |
| # .mark_text(dy=-25, color="black") | |
| # .encode(x=alt.X("Mes"), y=alt.Y("Valor"), text="Cambio") | |
| # ) | |
| # chart_row.altair_chart(fig, use_container_width=True) | |
| # else: | |
| # chart_row.altair_chart(fig, use_container_width=True) | |
| # cols = st.columns(3) | |
| # ganancia=value=l_3[-1] - cap_ahorro * l_2[-1] | |
| # my_bar.empty() | |
| # # with cols[0]: | |
| # # st_card('Capital proyectado', value=l_3[-1], show_progress=True) | |
| # # with cols[1]: | |
| # # st_card('Ganancia proyectada', value=ganancia, delta=round(ganancia/(cap_ahorro * l_2[-1])*100,0) , | |
| # # use_percentage_delta=True, delta_description='de retorno') | |
| # # with cols[2]: | |
| # # st_card('Meses', value=l_2[-1], delta=periodo_cambio, delta_description='En el Fondo Arriesgado') | |
| # st.write(df) | |
| def prototipo_simulacion(): | |
| # import streamlit as st | |
| # import time | |
| # import numpy as np | |
| # progress_bar = st.sidebar.progress(0) | |
| # status_text = st.sidebar.empty() | |
| # last_rows = np.random.randn(1, 1) | |
| # chart = st.line_chart(last_rows) | |
| # for i in range(1, 101): | |
| # new_rows = last_rows[-1, :] + np.random.randn(50, 1).cumsum(axis=0) | |
| # status_text.text("%i%% Complete" % i) | |
| # chart.add_rows(new_rows) | |
| # progress_bar.progress(i) | |
| # last_rows = new_rows | |
| # time.sleep(0.001) | |
| # progress_bar.empty() | |
| # # Streamlit widgets automatically run the script from top to bottom. Since | |
| # # this button is not connected to any other logic, it just causes a plain | |
| # # rerun. | |
| # st.button("Re-run") | |
| # import numpy as np | |
| # import matplotlib.pyplot as plt | |
| # import matplotlib.animation as animation | |
| # import streamlit as st | |
| # import streamlit.components.v1 as components | |
| # def update_line(num, data, line): | |
| # line.set_data(data[..., :num]) | |
| # return line, | |
| # fig = plt.figure() | |
| # # Fixing random state for reproducibility | |
| # np.random.seed(19680801) | |
| # data = np.random.rand(2, 25) | |
| # l, = plt.plot([], [], 'r-') | |
| # plt.xlim(0, 1) | |
| # plt.ylim(0, 1) | |
| # plt.xlabel('x') | |
| # plt.title('test') | |
| # line_ani = animation.FuncAnimation(fig, update_line, 25, fargs=(data, l), interval=50, blit=True) | |
| # st.title("Embed Matplotlib animation in Streamlit") | |
| # st.markdown("https://matplotlib.org/gallery/animation/basic_example.html") | |
| # components.html(line_ani.to_jshtml(), height=1000) | |
| # import matplotlib.pyplot as plt | |
| # import numpy as np | |
| # import streamlit as st | |
| # import time | |
| # fig, ax = plt.subplots() | |
| # max_x = 5 | |
| # max_rand = 10 | |
| # x = np.arange(0, max_x) | |
| # ax.set_ylim(0, max_rand) | |
| # line, = ax.plot(x, np.random.randint(0, max_rand, max_x)) | |
| # the_plot = st.pyplot(plt) | |
| # def init(): # give a clean slate to start | |
| # line.set_ydata([np.nan] * len(x)) | |
| # def animate(i): # update the y values (every 1000ms) | |
| # line.set_ydata(np.random.randint(0, max_rand, max_x)) | |
| # the_plot.pyplot(plt) | |
| # init() | |
| # for i in range(100): | |
| # animate(i) | |
| # time.sleep(0.1) | |
| import plotly.express as px | |
| from datetime import date | |
| from datetime import timedelta | |
| import numpy as np | |
| df = px.data.gapminder() | |
| cap_ahorro = 750000 | |
| Data = pd.DataFrame() | |
| today =date.today() | |
| l=[] | |
| l2=[] | |
| l3=[] | |
| l4=[] | |
| for i in range(53): | |
| for j in range(53): | |
| l.append(i) | |
| l2.append(j) | |
| if j<=i: | |
| l3.append(cap_ahorro*j) | |
| else: | |
| l3.append(0) | |
| if j<40: | |
| l4.append("Arriesgado") | |
| elif j<47: | |
| l4.append("Intermedio") | |
| else: | |
| l4.append("Conservador") | |
| l5 = [] | |
| l6 = [] | |
| Data["Mes"] = l | |
| Data["Ahorro"] = l2 | |
| Data["Total"] = l3 | |
| Data["Fondo"] = l4 | |
| fig = px.bar(Data, x="Ahorro", y="Total", color="Fondo", | |
| animation_frame="Mes") | |
| fig.update_yaxes(range=[0, 50000000]) | |
| fig.update_xaxes(range=[0, 53]) | |
| st.plotly_chart(fig) | |
| button = st.button("Activar") | |
| if button: | |
| chart_data = pd.DataFrame() | |
| chart = st.area_chart(chart_data) | |
| for i in range(100): | |
| if i<70: | |
| chart.add_rows(pd.DataFrame([[i*cap_ahorro,0, 0]], columns=['Fondo 1', 'Fondo 2', 'Fondo 3'])) | |
| elif i==70: | |
| chart.add_rows(pd.DataFrame([[i*cap_ahorro,i*cap_ahorro,0]], columns=['Fondo 1', 'Fondo 2', 'Fondo 3'])) | |
| st.success("Debes cambiarte al fondo intermedio") | |
| elif i<85: | |
| chart.add_rows(pd.DataFrame([[0,i*cap_ahorro,0]], columns=['Fondo 1', 'Fondo 2', 'Fondo 3'])) | |
| elif i==85: | |
| chart.add_rows(pd.DataFrame([[0,i*cap_ahorro,i*cap_ahorro]], columns=['Fondo 1', 'Fondo 2', 'Fondo 3'])) | |
| st.success("Debes cambiarte al fondo arriesgado") | |
| else: | |
| chart.add_rows(pd.DataFrame([[0,0, i*cap_ahorro]], columns=['Fondo 1', 'Fondo 2', 'Fondo 3'])) | |
| time.sleep(0.1) | |
| cap_ahorro = 750000 | |
| from plotly.subplots import make_subplots | |
| import plotly.graph_objects as go | |
| import numpy as np | |
| import plotly.graph_objects as go | |
| Frames=[] | |
| Frames2 =[] | |
| l_1=[] | |
| l_2=[] | |
| l_3=[] | |
| text=[] | |
| fig = make_subplots(rows=1, cols=1, subplot_titles = ('Subplot (1,1)')) | |
| for i in range(53): | |
| if i <40: | |
| l_1.append(cap_ahorro*i) | |
| l_3.append(np.nan) | |
| text.append("") | |
| elif i ==40: | |
| l_1.append(cap_ahorro*i) | |
| l_3.append(cap_ahorro*i) | |
| text.append("") | |
| else: | |
| l_1.append(np.nan) | |
| l_3.append(cap_ahorro*i) | |
| text.append("") | |
| l_2.append(i) | |
| Frames.append(go.Scatter(x=l_2, y=l_1, | |
| mode="lines+text", | |
| text=text, | |
| textposition="bottom center", | |
| textsrc="bottom center", | |
| textfont=dict( | |
| family="sans serif", | |
| size=10, | |
| color="Black" | |
| ), fill='tozeroy')) | |
| Frames2.append(go.Scatter(x=l_2, y=l_3, fill='tozeroy')) | |
| go.Annotations | |
| Frames_finales=[Frames, Frames2] | |
| fig.add_trace(go.Scatter( | |
| x= [0], | |
| y= [0], | |
| mode = 'lines', | |
| hoverinfo='name', | |
| legendgroup= 'Fondo Arriesgado', | |
| line_color= 'rgb(255, 79, 38)', | |
| name= 'Fondo Arriesgado', | |
| showlegend= True), row=1, col=1) | |
| fig.add_trace(go.Scatter( | |
| x= [0], | |
| y= [0], | |
| mode = 'lines', | |
| hoverinfo='name', | |
| legendgroup= 'Fondo Conservador', | |
| line_color= 'rgb(79, 38, 255)', | |
| name= 'Fondo Conservador', | |
| showlegend= True), row=1, col=1) | |
| frames =[dict(name = k, | |
| data = [Frames[k],Frames2[k]], | |
| traces=[0,1]) for k in range(53) | |
| ] | |
| updatemenus=[dict( | |
| type="buttons", | |
| buttons=[dict(label="Play", | |
| method="animate", | |
| args=[None])])] | |
| fig.update_yaxes(range=[0, 50000000]) | |
| fig.update_xaxes(range=[0, 53]) | |
| annotations1 = [dict( | |
| x=40, | |
| y=40*cap_ahorro, | |
| text=text, | |
| xanchor='auto', | |
| yanchor='bottom', | |
| showarrow=False, | |
| )] | |
| fig.update(frames=frames), | |
| fig.update_layout(updatemenus=updatemenus) | |
| st.plotly_chart(fig) | |
| import altair as alt | |
| from altair import datum | |
| l_1=[] | |
| l_2=[] | |
| l_3=[] | |
| for i in range(51): | |
| if i <41: | |
| l_1.append(cap_ahorro*i) | |
| l_3.append(np.nan) | |
| text.append("") | |
| elif i ==41: | |
| l_1.append(cap_ahorro*i) | |
| l_3.append(cap_ahorro*i) | |
| text.append("") | |
| else: | |
| l_1.append(np.nan) | |
| l_3.append(cap_ahorro*i) | |
| text.append("") | |
| l_2.append(i) | |
| chart_row = st.empty() | |
| button_2 = st.button("Comenzar simulaci贸") | |
| if button_2: | |
| for i in range(51): | |
| time.sleep(0.1) | |
| df = pd.DataFrame() | |
| df["Mes"]=l_2[0:i+1]+l_2[0:i+1] | |
| print(df["Mes"]) | |
| df["Valor"]=l_1[0:i+1]+l_3[0:i+1] | |
| if i <= 41: | |
| df["Fondo"]=["Fondo Arriesgado"]*len(df) | |
| else: | |
| df["Fondo"]=["Fondo Arriesgado"]*41 + ["Fondo Conservador"]*(i-41) + ["Fondo Arriesgado"]*43 + ["Fondo Conservador"]*(i-41) | |
| if i == 41: | |
| st.success("Debes cambiarte al fondo conservador") | |
| time.sleep(1) | |
| df=df.dropna() | |
| fig = alt.Chart(df).mark_area(opacity=0.6).encode( | |
| x=alt.X('Mes', | |
| scale=alt.Scale(domain=(0, 50)) | |
| ), | |
| y=alt.X('Valor', | |
| scale=alt.Scale(domain=(0, max(l_1+l_3)*1.1)) | |
| ), | |
| color=alt.Color("Fondo", scale=alt.Scale(scheme='category20')) | |
| ) | |
| if i > 41: | |
| df["Cambio"]="Cambiate al fondo conservador" | |
| text = ( | |
| alt.Chart(df[df["Mes"]==41]) | |
| .mark_text(dy=-25, color="black") | |
| .encode(x=alt.X("Mes"), y=alt.Y("Valor"), text="Cambio") | |
| ) | |
| chart_row.altair_chart(fig + text, use_container_width=True) | |
| else: | |
| chart_row.altair_chart(fig, use_container_width=True) | |