Spaces:
Sleeping
Sleeping
File size: 5,132 Bytes
c6989af 6777368 c6989af f911051 c6989af 795e94b c6989af 6777368 82403e9 9fcd1c6 c6989af 6777368 bcb80ce 6777368 66a2a3b 8c6e495 6777368 dae423b 6777368 66a2a3b 21e09ce 66a2a3b 3f487a5 66a2a3b 76ff76e 66a2a3b 76ff76e 66a2a3b 76ff76e f6062b4 66a2a3b 76ff76e 66a2a3b 76ff76e 66a2a3b f6062b4 66a2a3b 76ff76e f6062b4 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 |
import streamlit as st
import pandas as pd
import numpy as np
import optuna
import plotly.express as px
import requests
import io
st.title("Portfolio para calcular acciones ")
help_string = "NOTA: Para su informaci贸n los datos utilizados se extrajeron de GOOGLEFINANCE."
api_url = "https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&apikey=QVQGE7YPO68S403J&datatype=csv"
symbols = ['META', 'AAPL', 'GOOG']
uploaded_file = None
option = st.selectbox("Selecciona la fuente de datos:", ("Usar archivo predeterminado", "API Alpha Vantage", "Subir archivo propio"))
if option == "Usar archivo predeterminado":
uploaded_file = "STOCKS - Hoja 1.csv"
if uploaded_file is not None:
if uploaded_file[-3:] == "csv":
df = pd.read_csv(uploaded_file)
else:
df = pd.read_excel(uploaded_file)
# Resto del procesamiento del archivo ...
elif option == "API Alpha Vantage":
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)
elif option == "Subir archivo propio":
uploaded_file = st.file_uploader("Sube aqu铆 tu archivo de excel", type=[".xls", ".xlsx", ".csv"], help=help_string)
if uploaded_file is not None:
# Cargar y procesar el archivo subido
if uploaded_file.name[-3:] == "csv":
df = pd.read_csv(uploaded_file)
else:
df = pd.read_excel(uploaded_file)
if uploaded_file is not None:
if uploaded_file[-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'], format="%d/%m/%Y %H:%M:%S")
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])
fig = px.line(df, x=df.Date, y=stocks, labels={'value': 'Value', 'variable': 'Series'}, title='Serie de tiempo de las acciones')
fig.update_layout(xaxis_title='Date', yaxis_title='Value')
st.plotly_chart(fig)
ret_list = df[stocks_rets].mean().to_numpy().reshape(-1, 1)
cov_matrix = df[stocks_rets].cov().to_numpy()
optim_choice = st.selectbox("Elige la forma de optomizar :", ("max returns", "min variance", "max returns - variance"))
def portfolio_variance(weights, covariance_matrix):
return np.dot(weights.T, np.dot(covariance_matrix, weights))
def portfolio_returns(weights, expected_returns):
return np.dot(weights.T, expected_returns)
if optim_choice == "max returns":
def objective(trial):
a1 = trial.suggest_uniform('a1', 0, 1)
a2 = trial.suggest_uniform('a2', 0, 1)
a3 = 1 - a1 - a2
weights = np.array([a1, a2, a3]).reshape(-1, 1)
return np.dot(weights.T, ret_list)
study = optuna.create_study(direction="maximize")
study.optimize(objective, n_trials=100, show_progress_bar=True)
elif optim_choice == "min variance":
def objective(trial):
a1 = trial.suggest_uniform('a1', 0, 1)
a2 = trial.suggest_uniform('a2', 0, 1)
a3 = 1 - a1 - a2
weights = np.array([a1, a2, a3]).reshape(-1, 1)
return np.dot(weights.T, np.dot(cov_matrix, weights))
study = optuna.create_study(direction="minimize")
study.optimize(objective, n_trials=100, show_progress_bar=True)
else:
def objective(trial):
a1 = trial.suggest_uniform('a1', 0, 1)
a2 = trial.suggest_uniform('a2', 0, 1)
a3 = 1 - a1 - a2
weights = np.array([a1, a2, a3]).reshape(-1, 1)
return np.dot(weights.T, ret_list) - np.dot(weights.T, np.dot(cov_matrix, weights))
study = optuna.create_study(direction="maximize")
study.optimize(objective, n_trials=100, show_progress_bar=True)
a1 = study.best_params['a1']
a2 = study.best_params['a2']
a3 = 1- a1 - a2
weights = np.array([a1, a2, a3]).reshape(-1, 1)
retornos_anuales = (1 + np.dot(weights.T, ret_list)[0, 0]) ** 252 - 1
varianza_anual = np.dot(weights.T, np.dot(cov_matrix, weights))[0, 0] * 252
st.write(f"Los pesos son: :green[{stocks[0]} -> {a1:,.4f}], :green[{stocks[1]} -> {a2:,.4f}], :green[{stocks[2]} -> {a3:,.4f}]")
st.write(f"El retorno anualizado del portafolio es: :green[{retornos_anuales:,.4f}]")
st.write(f"La varianza anualizado del portafolio es: :green[{varianza_anual:,.4f}]") |