import streamlit as st import numpy as np import pandas as pd import matplotlib.pyplot as plt import random # Configuring the page st.set_page_config(page_title="Historical Statistics Calculator") # Streamlit app layout st.header("Calculate Statistics from Historical Data") with st.expander("Data Generation Settings"): N = st.number_input("Define the number of elements for each data list:", min_value=10, max_value=1000, step=1, value=100) # Button to generate the numbers generate_button = st.button("Generate Data") if generate_button: # Generate two lists of N random numbers each within a defined range x = [random.randint(0, 20) for _ in range(N)] y = [random.randint(0, 20) for _ in range(N)] st.session_state['x'] = x st.session_state['y'] = y # Check if data is available in the session state if 'x' in st.session_state and 'y' in st.session_state: x = st.session_state['x'] y = st.session_state['y'] # Calculate statistics x_bar = np.mean(x) y_bar = np.mean(y) st.subheader("Summary Statistics") col1, col2 = st.columns(2) with col1: st.metric("E(x)", f"{x_bar:.2f}") st.metric("var(x)", f"{np.var(x):.2f}") with col2: st.metric("E(y)", f"{y_bar:.2f}") st.metric("var(y)", f"{np.var(y):.2f}") # Correlation cov_xy = np.corrcoef(x, y)[0, 1] st.metric("Correlation (x, y)", f"{cov_xy:.2f}") # Plots fig, ax = plt.subplots() ax.scatter(x, y) ax.set_title("Scatter Plot of x vs y") ax.set_xlabel("x values") ax.set_ylabel("y values") st.pyplot(fig) # Plot of returns fig2, ax2 = plt.subplots() ax2.plot(np.arange(len(x)), x, label='x') ax2.plot(np.arange(len(y)), y, label='y') ax2.set_ylim(-10, 40) ax2.set_title("Time Series of Returns") ax2.set_xlabel("Time") ax2.set_ylabel("Returns") ax2.legend() st.pyplot(fig2) # Portfolio weights and returns calculation w_x = (x_bar - y_bar + np.var(y) - cov_xy * np.sqrt(np.var(x) * np.var(y))) / ( np.var(x) + np.var(y) - 2 * cov_xy * np.sqrt(np.var(x) * np.var(y)) ) w_y = 1 - w_x var_r = (w_x**2)*np.var(x) + (w_y**2)*np.var(y) + 2*w_x*w_y*cov_xy*np.sqrt(np.var(x) * np.var(y)) st.subheader("Portfolio Metrics") st.write("Assuming x and y represent portfolio returns:") st.write(f"Weight of x (w_x): {w_x:.2f}") st.write(f"Weight of y (w_y): {w_y:.2f}") st.write(f"Expected Portfolio Return (E(r)): {w_x*x_bar + w_y*y_bar:.2f}") st.write(f"Portfolio Variance (var(r)): {var_r:.2f}") else: st.warning("Please generate data to display results.")