Last active
March 4, 2019 17:48
-
-
Save dodger487/889e6e6654b61557c095b6600ad41bbf to your computer and use it in GitHub Desktop.
This file contains 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
# Chris Riederer | |
# 2019-02-28 | |
# When should you invest your 401k? | |
library(quantmod) | |
library(dplyr) | |
library(ggplot2) | |
# Pull in S&P data from Yahoo Finance | |
getSymbols("^GSPC", src="yahoo") | |
# Convert to friendly dataframe | |
df <- as.data.frame(GSPC) %>% | |
mutate(date = rownames(.), | |
raw_change = GSPC.Close - GSPC.Open, | |
change = raw_change / GSPC.Open) | |
INVEST_AMOUNT = 19000 | |
month_prices <- df %>% | |
group_by(year = year(date), month = month(date)) %>% | |
top_n(-1, wt = date) %>% | |
select(date, price = GSPC.Close) %>% | |
ungroup() | |
end_prices <- df %>% | |
filter(month(date) == 12) %>% | |
group_by(year = year(date)) %>% | |
top_n(1, wt = date) %>% | |
select(date, price = GSPC.Close) %>% | |
ungroup() | |
dff <- data.frame() | |
for (i in 1:12) { | |
tmp_df <- month_prices %>% | |
group_by(year = year(date)) %>% | |
top_n(-i, wt = date) %>% | |
ungroup() | |
tmp_df <- mutate(tmp_df, strat = i) | |
dff <- rbind(dff, tmp_df) | |
} | |
avg_price <- dff %>% | |
group_by(year, strat) %>% | |
summarize(avg_price = mean(price)) | |
foo <- inner_join(avg_price, end_prices, by = "year") %>% | |
mutate(growth = price / avg_price - 1) | |
# Line plots, by year | |
foo %>% | |
ggplot(aes(x=as.factor(strat), y=growth, color=as.factor(year), | |
group=year)) + | |
geom_point() + | |
geom_line() + | |
scale_y_continuous(labels = scales::percent) + | |
scale_x_discrete("Invest in X first months") | |
# Box plots | |
foo %>% | |
ggplot(aes(x=as.factor(strat), y=growth)) + | |
geom_boxplot() + | |
scale_y_continuous(labels = scales::percent) + | |
scale_x_discrete("Invest in X first months") | |
# Line plots, by strat | |
foo %>% | |
ggplot(aes(x=as.factor(year), y=growth, color=as.factor(strat), | |
group=strat)) + | |
geom_point() + | |
# geom_line() + | |
scale_y_continuous(labels = scales::percent) + | |
scale_x_discrete("Invest in X first months") + | |
theme(axis.text.x = element_text(angle = 45, hjust = 1)) | |
# Averages | |
foo %>% | |
group_by(strat) %>% | |
summarize(avg_growth = mean(growth)) %>% | |
ggplot(aes(x=as.factor(strat), y=avg_growth)) + | |
geom_point() + | |
scale_y_continuous(labels = scales::percent) + | |
scale_x_discrete("Invest in X first months") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment