Created
August 28, 2024 19:48
-
-
Save quantra-go-algo/6b66474c8bbda363a3c966d4f84dabf6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Set tickers | |
tickers <- c('MSFT', 'AAPL', 'TSLA', 'NFLX', 'META', 'AMZN','GOOGL') | |
# Set start and end dates | |
start = "1990-01-01" | |
end = "2024-08-01" | |
df <- new.env() | |
# Import the data | |
getSymbols(tickers,src='yahoo',env = df, from=start,to=end,auto.assign=TRUE) | |
# Create dataframe for stock close prices using the Apple date column | |
df2 <- data.frame(date = index(df[[ls(df)[1]]])) | |
# Loop to join all the stock close price data in a single dataframe | |
for (ticker in tickers) { | |
# Save the adjusted close price in a temporary dataframe called temp_df | |
temp_df <- data.frame(coredata(fortify.zoo(Ad(df[[ticker]])))) | |
# Rename the columns | |
colnames(temp_df) <- c('date',ticker) | |
# Save the adjusted close price in df2 | |
df2 <- left_join(df2, temp_df[c('date',ticker)], by=c("date")) | |
} | |
# Drop the NaN values | |
df2 <- na.omit(df2) | |
# Create the returns dataframe | |
var_data <- data.frame(date=df2$date[-1]) | |
# Loop to create the log returns | |
for(ticker in tickers) { | |
# Compute the log returns for each asset | |
var_data[[ticker]] <- log(df2[[ticker]][-1]/df2[[ticker]][-length(df2[[ticker]])]) | |
} | |
# Create a dataframe to select the returns and not the date column | |
data <- var_data[,match(tickers,colnames(var_data))] | |
# Convert the dataframe into a matrix for estimation purposes | |
tvp_var_data <- as.matrix(var_data[,2:8]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment