File size: 2,859 Bytes
793d7fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import streamlit as st
import pandas as pd
import numpy as np
import requests
import matplotlib.pyplot as plt
import io

st.title("Portfolio weights calculator")

help_string = "NOTA: El formato utilizado aqu铆 es llamando cada columna de GOOGLEFINANCE."

check_box = st.checkbox("驴Deseas usar el archivo precargado?")

if check_box:
    uploaded_file = "Stocks - Sheet1.csv"
    file_name = uploaded_file
else:
    uploaded_file = st.file_uploader("Sube aqu铆 tu archivo de excel", type=[".xls", ".xlsx", ".csv"], help=help_string)
    file_name = uploaded_file.name if uploaded_file is not None else None

if uploaded_file is not None:
    if file_name[-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']).dt.date 
    
    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])
    
    for stock in stocks:
        plt.plot(df["Date"], df[stock], label=stock)
    
    plt.xlabel('Date')
    plt.ylabel('Value')
    plt.title('Time Series Plot')
    plt.legend()
    plt.xticks(rotation=45)
    st.pyplot(plt)
    
    ret_list = df[stocks_rets].mean().to_numpy().reshape(-1, 1)
    cov_matrix = df[stocks_rets].cov().to_numpy()
    
    # C谩lculo de los pesos del portafolio
    n = len(stocks)
    weights = np.ones((n, 1)) / n
    
    yearly_returns = np.dot(weights.T, ret_list)[0, 0] * 252
    yearly_variance = np.dot(weights.T, np.dot(cov_matrix, weights))[0, 0] * 252
        
    st.write("Los pesos son:", ", ".join([f"{stocks[i]} -> {weights[i,0]:.4f}" for i in range(n)]))
    st.write(f"El retorno anualizado del portafolio es: {yearly_returns:.4f}")
    st.write(f"La varianza anualizada del portafolio es: {yearly_variance:.4f}")

    # Define api_url dentro del bloque donde estableces la conexi贸n a la API Alpha Vantage
    api_url = "https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&apikey=QVQGE7YPO68S403J&datatype=csv"

    # Stock symbols
    symbols = ['AMZN', 'MELI', 'ETSY']

    # Fetch and display data for each stock
    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)