AriaEs39 commited on
Commit
793d7fc
1 Parent(s): 4b9f775

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +81 -0
app.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import numpy as np
4
+ import requests
5
+ import matplotlib.pyplot as plt
6
+ import io
7
+
8
+ st.title("Portfolio weights calculator")
9
+
10
+ help_string = "NOTA: El formato utilizado aquí es llamando cada columna de GOOGLEFINANCE."
11
+
12
+ check_box = st.checkbox("¿Deseas usar el archivo precargado?")
13
+
14
+ if check_box:
15
+ uploaded_file = "Stocks - Sheet1.csv"
16
+ file_name = uploaded_file
17
+ else:
18
+ uploaded_file = st.file_uploader("Sube aquí tu archivo de excel", type=[".xls", ".xlsx", ".csv"], help=help_string)
19
+ file_name = uploaded_file.name if uploaded_file is not None else None
20
+
21
+ if uploaded_file is not None:
22
+ if file_name[-3:] == "csv":
23
+ df = pd.read_csv(uploaded_file)
24
+ else:
25
+ df = pd.read_excel(uploaded_file)
26
+
27
+ df = df.drop(0, axis=0)
28
+ df = df.drop("Unnamed: 2", axis=1).drop("Unnamed: 4", axis=1).rename({"Unnamed: 0": "Date"}, axis=1)
29
+
30
+ df['Date'] = pd.to_datetime(df['Date']).dt.date
31
+
32
+ stocks = list(df.columns)[-3:]
33
+ stocks_rets = []
34
+
35
+ for i in stocks:
36
+ stocks_rets.append(i+"_ret")
37
+ df[i] = df[i].astype(float)
38
+ df[i+"_ret"] = (df[i] - df[i].shift(1)) / df[i].shift(1)
39
+
40
+ st.write(df[["Date"] + stocks_rets])
41
+
42
+ for stock in stocks:
43
+ plt.plot(df["Date"], df[stock], label=stock)
44
+
45
+ plt.xlabel('Date')
46
+ plt.ylabel('Value')
47
+ plt.title('Time Series Plot')
48
+ plt.legend()
49
+ plt.xticks(rotation=45)
50
+ st.pyplot(plt)
51
+
52
+ ret_list = df[stocks_rets].mean().to_numpy().reshape(-1, 1)
53
+ cov_matrix = df[stocks_rets].cov().to_numpy()
54
+
55
+ # Cálculo de los pesos del portafolio
56
+ n = len(stocks)
57
+ weights = np.ones((n, 1)) / n
58
+
59
+ yearly_returns = np.dot(weights.T, ret_list)[0, 0] * 252
60
+ yearly_variance = np.dot(weights.T, np.dot(cov_matrix, weights))[0, 0] * 252
61
+
62
+ st.write("Los pesos son:", ", ".join([f"{stocks[i]} -> {weights[i,0]:.4f}" for i in range(n)]))
63
+ st.write(f"El retorno anualizado del portafolio es: {yearly_returns:.4f}")
64
+ st.write(f"La varianza anualizada del portafolio es: {yearly_variance:.4f}")
65
+
66
+ # Define api_url dentro del bloque donde estableces la conexión a la API Alpha Vantage
67
+ api_url = "https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&apikey=QVQGE7YPO68S403J&datatype=csv"
68
+
69
+ # Stock symbols
70
+ symbols = ['AMZN', 'MELI', 'ETSY']
71
+
72
+ # Fetch and display data for each stock
73
+ for symbol in symbols:
74
+ st.subheader(symbol)
75
+ response = requests.get(f"{api_url}&symbol={symbol}")
76
+ if response.status_code == 200:
77
+ data = pd.read_csv(io.BytesIO(response.content))
78
+ st.write(f"Datos de la acción {symbol}:")
79
+ st.write(data.head())
80
+ else:
81
+ st.write(f"Error al obtener los datos de la acción {symbol}. Código de estado:", response.status_code)