import streamlit as st import pandas as pd import numpy as np import requests import matplotlib.pyplot as plt import io # Función para obtener los datos de una acción utilizando Alpha Vantage def get_stock_data(symbol): api_key = "QVQGE7YPO68S403J" url = f"https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&symbol={symbol}&apikey={api_key}&datatype=csv" response = requests.get(url) data = pd.read_csv(io.StringIO(response.text)) data['Date'] = pd.to_datetime(data['Date']) return data 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}") # Integración con Alpha Vantage st.write("\n\n**Datos de las acciones obtenidos de Alpha Vantage:**") stocks_symbols = ["AMZN", "MELI", "ETSY"] # Descargar datos de acciones stocks_data = {symbol: get_stock_data(symbol) for symbol in stocks_symbols} # Crear DataFrame combinado con los datos de las acciones df = pd.concat([data.set_index('Date')['close'].rename(symbol) for symbol, data in stocks_data.items()], axis=1) # Calcular rendimientos diarios returns = df.pct_change() # Eliminar primera fila con NaN returns = returns.dropna() # Mostrar tabla con los rendimientos diarios st.write("Rendimientos diarios:") st.write(returns.head()) # Gráfico de series temporales st.write("Gráfico de series temporales:") plt.figure(figsize=(10, 6)) for symbol in stocks_symbols: plt.plot(df.index, df[symbol], label=symbol) plt.xlabel('Fecha') plt.ylabel('Valor') plt.title('Gráfico de Series Temporales') plt.legend() st.pyplot(plt) # Calcular rendimientos anuales y varianza weights = np.ones((len(stocks_symbols), 1)) / len(stocks_symbols) annual_returns = returns.mean() * 252 annual_variance = np.dot(weights.T, np.dot(returns.cov() * 252, weights)) # Mostrar resultados st.write("Los pesos son:") for i, symbol in enumerate(stocks_symbols): st.write(f"{symbol} -> {weights[i, 0]:.4f}") st.write(f"El retorno anualizado del portafolio es: {annual_returns.sum():.4f}") st.write(f"La varianza anualizada del portafolio es: {annual_variance[0, 0]:.4f}")