Sofi1606 commited on
Commit
af5cbb1
1 Parent(s): 2f4c716

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +125 -0
app.py CHANGED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import numpy as np
4
+ import optuna
5
+ import plotly.express as px
6
+ import requests
7
+ import io
8
+
9
+ st.title("Portfolio weights calculator")
10
+
11
+ help_string = "NOTA: Para su información los datos utilizados se extrajeron de GOOGLEFINANCE."
12
+
13
+ api_url = "https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&apikey=QVQGE7YPO68S403J&datatype=csv"
14
+ symbols = ['AMZN', 'MELI', 'ETSY']
15
+
16
+ option = st.selectbox("Selecciona la fuente de datos:", ("API Alpha Vantage", "Subir archivo propio", "Usar archivo predeterminado"))
17
+
18
+ if option == "API Alpha Vantage":
19
+ for symbol in symbols:
20
+ st.subheader(symbol)
21
+ response = requests.get(f"{api_url}&symbol={symbol}")
22
+ if response.status_code == 200:
23
+ data = pd.read_csv(io.BytesIO(response.content))
24
+ st.write(f"Datos de la acción {symbol}:")
25
+ st.write(data.head())
26
+ else:
27
+ st.write(f"Error al obtener los datos de la acción {symbol}. Código de estado:", response.status_code)
28
+ elif option == "Subir archivo propio":
29
+ uploaded_file = st.file_uploader("Sube aquí tu archivo de excel", type=[".xls", ".xlsx", ".csv"], help=help_string)
30
+ if uploaded_file is not None:
31
+ # Cargar y procesar el archivo subido
32
+ if file_name[-3:] == "csv":
33
+ df = pd.read_csv(uploaded_file)
34
+ else:
35
+ df = pd.read_excel(uploaded_file)
36
+ # Resto del procesamiento del archivo ...
37
+ elif option == "Usar archivo predeterminado":
38
+ uploaded_file = "STOCKS - Hoja 1.csv" # Opcional: proporciona la ruta al archivo predeterminado
39
+ # Cargar y procesar el archivo predeterminado
40
+ # Resto del procesamiento del archivo ...
41
+
42
+ if uploaded_file is not None:
43
+ if file_name[-3:] == "csv":
44
+ df = pd.read_csv(uploaded_file)
45
+ else:
46
+ df = pd.read_excel(uploaded_file)
47
+
48
+ df = df.drop(0, axis=0)
49
+ df = df.drop("Unnamed: 2", axis=1).drop("Unnamed: 4", axis=1).rename({"Unnamed: 0": "Date"}, axis=1)
50
+
51
+ df['Date'] = pd.to_datetime(df['Date'], format="%d/%m/%Y %H:%M:%S")
52
+
53
+ stocks = list(df.columns)[-3:]
54
+ stocks_rets = []
55
+
56
+ for i in stocks:
57
+ stocks_rets.append(i+"_ret")
58
+ df[i] = df[i].astype(float)
59
+ df[i+"_ret"] = (df[i] - df[i].shift(1)) / df[i].shift(1)
60
+
61
+ st.write(df[["Date"] + stocks_rets])
62
+
63
+ fig = px.line(df, x=df.Date, y=stocks, labels={'value': 'Value', 'variable': 'Series'}, title='Time Series Plot')
64
+ fig.update_layout(xaxis_title='Date', yaxis_title='Value')
65
+
66
+ st.plotly_chart(fig)
67
+
68
+ ret_list = df[stocks_rets].mean().to_numpy().reshape(-1, 1)
69
+ cov_matrix = df[stocks_rets].cov().to_numpy()
70
+
71
+ optim_choice = st.selectbox("Elige la forma de optomizar :", ("max returns", "min variance", "max returns - variance"))
72
+
73
+ def portfolio_variance(weights, covariance_matrix):
74
+ return np.dot(weights.T, np.dot(covariance_matrix, weights))
75
+
76
+ def portfolio_returns(weights, expected_returns):
77
+ return np.dot(weights.T, expected_returns)
78
+
79
+ if optim_choice == "max returns":
80
+ def objective(trial):
81
+ w1 = trial.suggest_uniform('w1', 0, 1)
82
+ w2 = trial.suggest_uniform('w2', 0, 1)
83
+ w3 = 1 - w1 - w2
84
+ weights = np.array([w1, w2, w3]).reshape(-1, 1)
85
+ return np.dot(weights.T, ret_list)
86
+
87
+ study = optuna.create_study(direction="maximize")
88
+ study.optimize(objective, n_trials=100, show_progress_bar=True)
89
+
90
+ elif optim_choice == "min variance":
91
+ def objective(trial):
92
+ w1 = trial.suggest_uniform('w1', 0, 1)
93
+ w2 = trial.suggest_uniform('w2', 0, 1)
94
+ w3 = 1 - w1 - w2
95
+ weights = np.array([w1, w2, w3]).reshape(-1, 1)
96
+ return np.dot(weights.T, np.dot(cov_matrix, weights))
97
+
98
+ study = optuna.create_study(direction="minimize")
99
+ study.optimize(objective, n_trials=100, show_progress_bar=True)
100
+
101
+ else:
102
+ def objective(trial):
103
+ w1 = trial.suggest_uniform('w1', 0, 1)
104
+ w2 = trial.suggest_uniform('w2', 0, 1)
105
+ w3 = 1 - w1 - w2
106
+ weights = np.array([w1, w2, w3]).reshape(-1, 1)
107
+ return np.dot(weights.T, ret_list) - np.dot(weights.T, np.dot(cov_matrix, weights))
108
+
109
+ study = optuna.create_study(direction="maximize")
110
+ study.optimize(objective, n_trials=100, show_progress_bar=True)
111
+
112
+ w1 = study.best_params['w1']
113
+ w2 = study.best_params['w2']
114
+ w3 = 1- w1 - w2
115
+
116
+ weights = np.array([w1, w2, w3]).reshape(-1, 1)
117
+
118
+ yearly_returns = (1 + np.dot(weights.T, ret_list)[0, 0]) ** 252 - 1
119
+ yearly_variance = np.dot(weights.T, np.dot(cov_matrix, weights))[0, 0] * 252
120
+
121
+ st.write(f"Los pesos son: :green[{stocks[0]} -> {w1:,.4f}], :green[{stocks[1]} -> {w2:,.4f}], :green[{stocks[2]} -> {w3:,.4f}]")
122
+ st.write(f"El retorno anualizado del portafolio es: :green[{yearly_returns:,.4f}]")
123
+ st.write(f"La varianza anualizado del portafolio es: :green[{yearly_variance:,.4f}]")
124
+
125
+