You've successfully subscribed to MyPad Blog
Great! Next, complete checkout for full access to MyPad Blog
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.
Success! Your billing info is updated.
Billing info update failed.

Functional programming with R and Tidyverse - Try 20200222

Functional programming with R and Tidyverse - Try 20200222

In an attempt to get more comfortable with tidyverse and functional programming, here is a quick post to demonstrated the much sleeker and explainable code using these concepts.

This post is motivated by this awesome talk by Hadley Wickham: https://www.youtube.com/watch?v=bzUmK0Y07ck&feature=emb_title

library(tidyverse)
library(quantmod)

## Obtain symbol data
getSymbols(ticker, from="2010-01-01")

# apply functional programming concepts
# credit: https://speakerdeck.com/hadley/the-joy-of-functional-programming?slide=9
# credit: https://github.com/hadley/joy-of-fp

tickers <- c("FB", "AMZN", "AAPL", "NFLX", "GOOG", "SPY")

# get the data
map(tickers, ~ assign(.x, getSymbols(.x, env=.GlobalEnv)))

# this also works
# walk(tickers, ~ assign(.x, getSymbols(.x, env=.GlobalEnv)))

# plot all the charts
map(tickers, ~ plot(Cl(get(.x)), type = "l", main = .x)

# merge the data
stocks <- map(tickers, ~ Cl(get(.x)) %>% set_names(.x))
stocks <- do.call('cbind', stocks)
head(stocks)

plot.zoo(stocks, main = "All stocks")