Demo4 / app.py
Yorbely's picture
Update app.py
799383c verified
import streamlit as st
import numpy as np
import matplotlib.pyplot as plt
import random
def main():
st.title("Statistics for two historical lists🏦")
with st.form("my_form"):
N = st.number_input("Insert the total values for the lists:", step=1)
# Button to generate the numbers
if st.form_submit_button("Click to generate random numbers' lists"):
# Generate two lists of random numbers each
lista1 = [random.randint(0, 20) for _ in range(N)]
lista2 = [random.randint(0, 20) for _ in range(N)]
# Button to perform analysis
if len(lista1) != 0 and len(lista2) != 0:
analizar_inversiones(lista1, lista2)
else:
st.write(":red[Please, generate random numbers' lists]")
def analizar_inversiones(lista1, lista2):
# Convertir las listas en arrays numpy
array1 = np.array(lista1)
array2 = np.array(lista2)
# Calcular desviación estándar
std_dev1 = np.std(array1)
std_dev2 = np.std(array2)
# Calcular valor esperado
mean1 = np.mean(array1)
mean2 = np.mean(array2)
# Calcular correlación
correlation = np.corrcoef(array1, array2)[0, 1]
# Crear gráfica
fig, ax = plt.subplots()
ax.scatter(array1, array2)
ax.set_xlabel('Lista 1')
ax.set_ylabel('Lista 2')
ax.set_title('Investment graph')
ax.grid(True)
st.pyplot(fig)
# Decidir a cuál invertir más y a cuál menos
if mean1 > mean2:
invertir_mas = "List 1"
invertir_menos = "List 2"
else:
invertir_mas = "List 2"
invertir_menos = "List 1"
# Mostrar resultados con un formato agradable
st.write("Results of the Analysis:")
st.write(f"Standard deviation of list 1: {std_dev1}")
st.write(f"Standard deviation of list 2: {std_dev2}")
st.write(f"Estimated value list 1: {mean1}")
st.write(f"Estimated value list 2: {mean2}")
st.write(f"Correlation: {correlation}")
st.write(f"Invest more in: {invertir_mas}")
st.write(f"Invest less in: {invertir_menos}")
# Calculate weights and portfolio returns
x_bar = mean1
y_bar = mean2
var_x = std_dev1**2
var_y = std_dev2**2
cov_xy = np.cov(array1, array2)[0, 1]
w_x = (x_bar - y_bar + var_y - cov_xy * np.sqrt(var_x * var_y)) / (
var_x + var_y - 2 * cov_xy * np.sqrt(var_x * var_y)
)
w_y = 1 - w_x
var_r = (w_x**2)*var_x + (w_y**2)*var_y + 2*w_x*w_y*cov_xy*np.sqrt(var_x * var_y)
st.subheader("Weights and portfolio returns")
st.write("Assuming x and y represent returns of portfolios")
st.write(f"w_x = {w_x:,.2f}")
st.write(f"w_y = {w_y:,.2f}")
st.write(f"E(r) = {w_x*x_bar + w_y*y_bar:,.2f}")
st.write(f"var(r) = {var_r:,.2f}")
if __name__ == "__main__":
main()