import streamlit as st import pandas as pd import numpy as np import requests import matplotlib.pyplot as plt import io st.title("Portfolio weights calculator") help_string = "NOTA: El formato utilizado aquí es llamando cada columna de GOOGLEFINANCE." check_box = st.checkbox("¿Deseas usar el archivo precargado?") if check_box: uploaded_file = "Stocks - Sheet1.csv" file_name = uploaded_file else: uploaded_file = st.file_uploader("Sube aquí tu archivo de excel", type=[".xls", ".xlsx", ".csv"], help=help_string) file_name = uploaded_file.name if uploaded_file is not None else None if uploaded_file is not None: if file_name[-3:] == "csv": df = pd.read_csv(uploaded_file) else: df = pd.read_excel(uploaded_file) df = df.drop(0, axis=0) df = df.drop("Unnamed: 2", axis=1).drop("Unnamed: 4", axis=1).rename({"Unnamed: 0": "Date"}, axis=1) df['Date'] = pd.to_datetime(df['Date']).dt.date stocks = list(df.columns)[-3:] stocks_rets = [] for i in stocks: stocks_rets.append(i+"_ret") df[i] = df[i].astype(float) df[i+"_ret"] = (df[i] - df[i].shift(1)) / df[i].shift(1) st.write(df[["Date"] + stocks_rets]) for stock in stocks: plt.plot(df["Date"], df[stock], label=stock) plt.xlabel('Date') plt.ylabel('Value') plt.title('Time Series Plot') plt.legend() plt.xticks(rotation=45) st.pyplot(plt) ret_list = df[stocks_rets].mean().to_numpy().reshape(-1, 1) cov_matrix = df[stocks_rets].cov().to_numpy() # Cálculo de los pesos del portafolio n = len(stocks) weights = np.ones((n, 1)) / n yearly_returns = np.dot(weights.T, ret_list)[0, 0] * 252 yearly_variance = np.dot(weights.T, np.dot(cov_matrix, weights))[0, 0] * 252 st.write("Los pesos son:", ", ".join([f"{stocks[i]} -> {weights[i,0]:.4f}" for i in range(n)])) st.write(f"El retorno anualizado del portafolio es: {yearly_returns:.4f}") st.write(f"La varianza anualizada del portafolio es: {yearly_variance:.4f}") # Define api_url dentro del bloque donde estableces la conexión a la API Alpha Vantage api_url = "https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&apikey=QVQGE7YPO68S403J&datatype=csv" # Stock symbols symbols = ['AMZN', 'MELI', 'ETSY'] # Fetch and display data for each stock for symbol in symbols: st.subheader(symbol) response = requests.get(f"{api_url}&symbol={symbol}") if response.status_code == 200: data = pd.read_csv(io.BytesIO(response.content)) st.write(f"Datos de la acción {symbol}:") st.write(data.head()) else: st.write(f"Error al obtener los datos de la acción {symbol}. Código de estado:", response.status_code)