Path: blob/master/lessons/lesson_15/rolling_PCA.R
1904 views
library(readr)1library(dplyr)2library(xts)34## Set working directory5setwd("~/ga/repos/lesson-15")67## Read in data8df = read_csv('financial_indicators2.csv', na = "#N/A")910# Exclude Nulls11df <- df[complete.cases(df),]1213#Converto to XTS and Scale14df_xts <- as.xts(df %>%15select(-DATE) %>%16scale(center=TRUE, scale=TRUE),17order.by = df$DATE)1819## Function to extract the rolling variance explained by the first PC20roll_var<-function(x){21output<-prcomp(x)$sdev^222return(output[1]/sum(output))23}2425## Run the function26rolling_var<-rollapply(df_xts, 90, roll_var, by.column=FALSE)2728## Convert to df for plotting29plotting_df <- tbl_df(data.frame(date=index(rolling_var), var = coredata(rolling_var)))3031## Plot32ggplot(plotting_df, aes(x=date, y=var)) +33geom_line() +34theme_bw() +35ggtitle('90 Day Rolling Variance Explained')363738