Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -13,13 +13,10 @@ help_string = "NOTA: Para su información los datos utilizados se extrajeron de
|
|
13 |
api_url = "https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&apikey=QVQGE7YPO68S403J&datatype=csv"
|
14 |
symbols = ['META', 'AAPL', 'GOOG']
|
15 |
|
16 |
-
uploaded_file = None # Definir uploaded_file con un valor predeterminado
|
17 |
-
|
18 |
option = st.selectbox("Selecciona la fuente de datos:", ("Usar archivo predeterminado", "API Alpha Vantage", "Subir archivo propio"))
|
19 |
|
20 |
if option == "Usar archivo predeterminado":
|
21 |
-
uploaded_file = "STOCKS - Hoja 1.csv"
|
22 |
-
# Cargar y procesar el archivo predeterminado
|
23 |
if uploaded_file is not None:
|
24 |
if uploaded_file[-3:] == "csv":
|
25 |
df = pd.read_csv(uploaded_file)
|
@@ -44,71 +41,86 @@ elif option == "Subir archivo propio":
|
|
44 |
df = pd.read_csv(uploaded_file)
|
45 |
else:
|
46 |
df = pd.read_excel(uploaded_file)
|
47 |
-
|
48 |
-
|
49 |
-
# Bloque de código para procesar y mostrar gráficas y varianzas
|
50 |
-
if uploaded_file is not None or option == "API Alpha Vantage":
|
51 |
-
if uploaded_file is not None:
|
52 |
-
if uploaded_file.name[-3:] == "csv":
|
53 |
-
df = pd.read_csv(uploaded_file)
|
54 |
-
else:
|
55 |
-
df = pd.read_excel(uploaded_file)
|
56 |
|
57 |
-
|
58 |
-
if
|
59 |
-
df =
|
60 |
-
|
61 |
-
df
|
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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
13 |
api_url = "https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&apikey=QVQGE7YPO68S403J&datatype=csv"
|
14 |
symbols = ['META', 'AAPL', 'GOOG']
|
15 |
|
|
|
|
|
16 |
option = st.selectbox("Selecciona la fuente de datos:", ("Usar archivo predeterminado", "API Alpha Vantage", "Subir archivo propio"))
|
17 |
|
18 |
if option == "Usar archivo predeterminado":
|
19 |
+
uploaded_file = "STOCKS - Hoja 1.csv"
|
|
|
20 |
if uploaded_file is not None:
|
21 |
if uploaded_file[-3:] == "csv":
|
22 |
df = pd.read_csv(uploaded_file)
|
|
|
41 |
df = pd.read_csv(uploaded_file)
|
42 |
else:
|
43 |
df = pd.read_excel(uploaded_file)
|
44 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
45 |
|
46 |
+
if uploaded_file is not None:
|
47 |
+
if uploaded_file[-3:] == "csv":
|
48 |
+
df = pd.read_csv(uploaded_file)
|
49 |
+
else:
|
50 |
+
df = pd.read_excel(uploaded_file)
|
51 |
+
df = df.drop(0, axis=0)
|
52 |
+
df = df.drop("Unnamed: 2", axis=1).drop("Unnamed: 4", axis=1).rename({"Unnamed: 0": "Date"}, axis=1)
|
53 |
+
|
54 |
+
df['Date'] = pd.to_datetime(df['Date'], format="%d/%m/%Y %H:%M:%S")
|
55 |
+
|
56 |
+
stocks = list(df.columns)[-3:]
|
57 |
+
stocks_rets = []
|
58 |
+
|
59 |
+
for i in stocks:
|
60 |
+
stocks_rets.append(i+"_ret")
|
61 |
+
df[i] = df[i].astype(float)
|
62 |
+
df[i+"_ret"] = (df[i] - df[i].shift(1)) / df[i].shift(1)
|
63 |
+
|
64 |
+
st.write(df[["Date"] + stocks_rets])
|
65 |
+
|
66 |
+
fig = px.line(df, x=df.Date, y=stocks, labels={'value': 'Value', 'variable': 'Series'}, title='Time Series Plot')
|
67 |
+
fig.update_layout(xaxis_title='Date', yaxis_title='Value')
|
68 |
+
|
69 |
+
st.plotly_chart(fig)
|
70 |
+
|
71 |
+
ret_list = df[stocks_rets].mean().to_numpy().reshape(-1, 1)
|
72 |
+
cov_matrix = df[stocks_rets].cov().to_numpy()
|
73 |
+
|
74 |
+
optim_choice = st.selectbox("Elige la forma de optomizar :", ("max returns", "min variance", "max returns - variance"))
|
75 |
+
|
76 |
+
def portfolio_variance(weights, covariance_matrix):
|
77 |
+
return np.dot(weights.T, np.dot(covariance_matrix, weights))
|
78 |
+
|
79 |
+
def portfolio_returns(weights, expected_returns):
|
80 |
+
return np.dot(weights.T, expected_returns)
|
81 |
+
|
82 |
+
if optim_choice == "max returns":
|
83 |
+
def objective(trial):
|
84 |
+
w1 = trial.suggest_uniform('w1', 0, 1)
|
85 |
+
w2 = trial.suggest_uniform('w2', 0, 1)
|
86 |
+
w3 = 1 - w1 - w2
|
87 |
+
weights = np.array([w1, w2, w3]).reshape(-1, 1)
|
88 |
+
return np.dot(weights.T, ret_list)
|
89 |
+
|
90 |
+
study = optuna.create_study(direction="maximize")
|
91 |
+
study.optimize(objective, n_trials=100, show_progress_bar=True)
|
92 |
+
|
93 |
+
elif optim_choice == "min variance":
|
94 |
+
def objective(trial):
|
95 |
+
w1 = trial.suggest_uniform('w1', 0, 1)
|
96 |
+
w2 = trial.suggest_uniform('w2', 0, 1)
|
97 |
+
w3 = 1 - w1 - w2
|
98 |
+
weights = np.array([w1, w2, w3]).reshape(-1, 1)
|
99 |
+
return np.dot(weights.T, np.dot(cov_matrix, weights))
|
100 |
+
|
101 |
+
study = optuna.create_study(direction="minimize")
|
102 |
+
study.optimize(objective, n_trials=100, show_progress_bar=True)
|
103 |
+
|
104 |
+
else:
|
105 |
+
def objective(trial):
|
106 |
+
w1 = trial.suggest_uniform('w1', 0, 1)
|
107 |
+
w2 = trial.suggest_uniform('w2', 0, 1)
|
108 |
+
w3 = 1 - w1 - w2
|
109 |
+
weights = np.array([w1, w2, w3]).reshape(-1, 1)
|
110 |
+
return np.dot(weights.T, ret_list) - np.dot(weights.T, np.dot(cov_matrix, weights))
|
111 |
+
|
112 |
+
study = optuna.create_study(direction="maximize")
|
113 |
+
study.optimize(objective, n_trials=100, show_progress_bar=True)
|
114 |
+
|
115 |
+
w1 = study.best_params['w1']
|
116 |
+
w2 = study.best_params['w2']
|
117 |
+
w3 = 1- w1 - w2
|
118 |
+
|
119 |
+
weights = np.array([w1, w2, w3]).reshape(-1, 1)
|
120 |
+
|
121 |
+
yearly_returns = (1 + np.dot(weights.T, ret_list)[0, 0]) ** 252 - 1
|
122 |
+
yearly_variance = np.dot(weights.T, np.dot(cov_matrix, weights))[0, 0] * 252
|
123 |
+
|
124 |
+
st.write(f"Los pesos son: :green[{stocks[0]} -> {w1:,.4f}], :green[{stocks[1]} -> {w2:,.4f}], :green[{stocks[2]} -> {w3:,.4f}]")
|
125 |
+
st.write(f"El retorno anualizado del portafolio es: :green[{yearly_returns:,.4f}]")
|
126 |
+
st.write(f"La varianza anualizado del portafolio es: :green[{yearly_variance:,.4f}]")
|