library(PerformanceAnalytics)
library(quantmod)
library(dygraphs)

# Function to calculate monthly returns on a stock
monthly_stock_returns <- function(ticker, start_year) {
# Download the data from Yahoo finance
symbol <- getSymbols(ticker, src = 'yahoo', auto.assign = FALSE, warnings = FALSE)
# Tranform it to monthly returns using the periodReturn function from quantmod
data <- periodReturn(symbol, period = 'monthly', subset=paste(start_year, "::", sep = ""),
type = 'log')

# Let's rename the column of returns to something intuitive because the column name is what
# will eventually be displayed on the time series graph.
colnames(data) <- as.character(ticker)

# We want to be able to work with the xts objects that result from this function
# so let's explicitly put them to the global environment with an easy to use
# name, the stock ticker.
assign(ticker, data, .GlobalEnv)
}