Sofi1606 commited on
Commit
21e09ce
1 Parent(s): 82403e9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +68 -80
app.py CHANGED
@@ -13,6 +13,8 @@ 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
  option = st.selectbox("Selecciona la fuente de datos:", ("Usar archivo predeterminado", "API Alpha Vantage", "Subir archivo propio"))
17
 
18
  if option == "Usar archivo predeterminado":
@@ -44,84 +46,70 @@ elif option == "Subir archivo propio":
44
  df = pd.read_excel(uploaded_file)
45
  # Resto del procesamiento del archivo ...
46
 
47
- if uploaded_file is not None:
48
- if uploaded_file[-3:] == "csv":
49
- df = pd.read_csv(uploaded_file)
50
- else:
51
- df = pd.read_excel(uploaded_file)
52
- df = df.drop(0, axis=0)
53
- df = df.drop("Unnamed: 2", axis=1).drop("Unnamed: 4", axis=1).rename({"Unnamed: 0": "Date"}, axis=1)
54
-
55
- df['Date'] = pd.to_datetime(df['Date'], format="%d/%m/%Y %H:%M:%S")
56
-
57
- stocks = list(df.columns)[-3:]
58
- stocks_rets = []
59
-
60
- for i in stocks:
61
- stocks_rets.append(i+"_ret")
62
- df[i] = df[i].astype(float)
63
- df[i+"_ret"] = (df[i] - df[i].shift(1)) / df[i].shift(1)
64
-
65
- st.write(df[["Date"] + stocks_rets])
66
-
67
- fig = px.line(df, x=df.Date, y=stocks, labels={'value': 'Value', 'variable': 'Series'}, title='Time Series Plot')
68
- fig.update_layout(xaxis_title='Date', yaxis_title='Value')
69
-
70
- st.plotly_chart(fig)
71
-
72
- ret_list = df[stocks_rets].mean().to_numpy().reshape(-1, 1)
73
- cov_matrix = df[stocks_rets].cov().to_numpy()
74
-
75
- optim_choice = st.selectbox("Elige la forma de optomizar :", ("max returns", "min variance", "max returns - variance"))
76
-
77
- def portfolio_variance(weights, covariance_matrix):
78
- return np.dot(weights.T, np.dot(covariance_matrix, weights))
79
-
80
- def portfolio_returns(weights, expected_returns):
81
- return np.dot(weights.T, expected_returns)
82
-
83
- if optim_choice == "max returns":
84
- def objective(trial):
85
- w1 = trial.suggest_uniform('w1', 0, 1)
86
- w2 = trial.suggest_uniform('w2', 0, 1)
87
- w3 = 1 - w1 - w2
88
- weights = np.array([w1, w2, w3]).reshape(-1, 1)
89
- return np.dot(weights.T, ret_list)
90
-
91
- study = optuna.create_study(direction="maximize")
92
- study.optimize(objective, n_trials=100, show_progress_bar=True)
93
-
94
- elif optim_choice == "min variance":
95
- def objective(trial):
96
- w1 = trial.suggest_uniform('w1', 0, 1)
97
- w2 = trial.suggest_uniform('w2', 0, 1)
98
- w3 = 1 - w1 - w2
99
- weights = np.array([w1, w2, w3]).reshape(-1, 1)
100
- return np.dot(weights.T, np.dot(cov_matrix, weights))
101
-
102
- study = optuna.create_study(direction="minimize")
103
- study.optimize(objective, n_trials=100, show_progress_bar=True)
104
-
105
  else:
106
- def objective(trial):
107
- w1 = trial.suggest_uniform('w1', 0, 1)
108
- w2 = trial.suggest_uniform('w2', 0, 1)
109
- w3 = 1 - w1 - w2
110
- weights = np.array([w1, w2, w3]).reshape(-1, 1)
111
- return np.dot(weights.T, ret_list) - np.dot(weights.T, np.dot(cov_matrix, weights))
112
-
113
- study = optuna.create_study(direction="maximize")
114
- study.optimize(objective, n_trials=100, show_progress_bar=True)
115
-
116
- w1 = study.best_params['w1']
117
- w2 = study.best_params['w2']
118
- w3 = 1- w1 - w2
119
-
120
- weights = np.array([w1, w2, w3]).reshape(-1, 1)
121
-
122
- yearly_returns = (1 + np.dot(weights.T, ret_list)[0, 0]) ** 252 - 1
123
- yearly_variance = np.dot(weights.T, np.dot(cov_matrix, weights))[0, 0] * 252
124
-
125
- st.write(f"Los pesos son: :green[{stocks[0]} -> {w1:,.4f}], :green[{stocks[1]} -> {w2:,.4f}], :green[{stocks[2]} -> {w3:,.4f}]")
126
- st.write(f"El retorno anualizado del portafolio es: :green[{yearly_returns:,.4f}]")
127
- st.write(f"La varianza anualizado del portafolio es: :green[{yearly_variance:,.4f}]")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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":
 
46
  df = pd.read_excel(uploaded_file)
47
  # Resto del procesamiento del archivo ...
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
+ # Resto del código de procesamiento del archivo subido ...
53
+ pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
  else:
55
+ # Resto del código de procesamiento de los datos del API ...
56
+ pass
57
+
58
+ # Código para mostrar gráficas y varianzas ...
59
+ if 'df' in locals():
60
+ df = df.drop(0, axis=0)
61
+ df = df.drop("Unnamed: 2", axis=1).drop("Unnamed: 4", axis=1).rename({"Unnamed: 0": "Date"}, axis=1)
62
+ df['Date'] = pd.to_datetime(df['Date'], format="%d/%m/%Y %H:%M:%S")
63
+ stocks = list(df.columns)[-3:]
64
+ stocks_rets = []
65
+ for i in stocks:
66
+ stocks_rets.append(i+"_ret")
67
+ df[i] = df[i].astype(float)
68
+ df[i+"_ret"] = (df[i] - df[i].shift(1)) / df[i].shift(1)
69
+ st.write(df[["Date"] + stocks_rets])
70
+ fig = px.line(df, x=df.Date, y=stocks, labels={'value': 'Value', 'variable': 'Series'}, title='Time Series Plot')
71
+ fig.update_layout(xaxis_title='Date', yaxis_title='Value')
72
+ st.plotly_chart(fig)
73
+ ret_list = df[stocks_rets].mean().to_numpy().reshape(-1, 1)
74
+ cov_matrix = df[stocks_rets].cov().to_numpy()
75
+ optim_choice = st.selectbox("Elige la forma de optimizar:", ("max returns", "min variance", "max returns - variance"))
76
+ def portfolio_variance(weights, covariance_matrix):
77
+ return np.dot(weights.T, np.dot(covariance_matrix, weights))
78
+ def portfolio_returns(weights, expected_returns):
79
+ return np.dot(weights.T, expected_returns)
80
+ if optim_choice == "max returns":
81
+ def objective(trial):
82
+ w1 = trial.suggest_uniform('w1', 0, 1)
83
+ w2 = trial.suggest_uniform('w2', 0, 1)
84
+ w3 = 1 - w1 - w2
85
+ weights = np.array([w1, w2, w3]).reshape(-1, 1)
86
+ return np.dot(weights.T, ret_list)
87
+ study = optuna.create_study(direction="maximize")
88
+ study.optimize(objective, n_trials=100, show_progress_bar=True)
89
+ elif optim_choice == "min variance":
90
+ def objective(trial):
91
+ w1 = trial.suggest_uniform('w1', 0, 1)
92
+ w2 = trial.suggest_uniform('w2', 0, 1)
93
+ w3 = 1 - w1 - w2
94
+ weights = np.array([w1, w2, w3]).reshape(-1, 1)
95
+ return np.dot(weights.T, np.dot(cov_matrix, weights))
96
+ study = optuna.create_study(direction="minimize")
97
+ study.optimize(objective, n_trials=100, show_progress_bar=True)
98
+ else:
99
+ def objective(trial):
100
+ w1 = trial.suggest_uniform('w1', 0, 1)
101
+ w2 = trial.suggest_uniform('w2', 0, 1)
102
+ w3 = 1 - w1 - w2
103
+ weights = np.array([w1, w2, w3]).reshape(-1, 1)
104
+ return np.dot(weights.T, ret_list) - np.dot(weights.T, np.dot(cov_matrix, weights))
105
+ study = optuna.create_study(direction="maximize")
106
+ study.optimize(objective, n_trials=100, show_progress_bar=True)
107
+ w1 = study.best_params['w1']
108
+ w2 = study.best_params['w2']
109
+ w3 = 1- w1 - w2
110
+ weights = np.array([w1, w2, w3]).reshape(-1, 1)
111
+ yearly_returns = (1 + np.dot(weights.T, ret_list)[0, 0]) ** 252 - 1
112
+ yearly_variance = np.dot(weights.T, np.dot(cov_matrix, weights))[0, 0] * 252
113
+ st.write(f"Los pesos son: :green[{stocks[0]} -> {w1:,.4f}], :green[{stocks[1]} -> {w2:,.4f}], :green[{stocks[2]} -> {w3:,.4f}]")
114
+ st.write(f"El retorno anualizado del portafolio es: :green[{yearly_returns:,.4f}]")
115
+ st.write(f"La varianza anualizada del portafolio es: :green[{yearly_variance:,.4f}]")