How Do I Obtain Some Stock Returns Using the Quantmod Package in R

38 views Asked by At

I want to obtain some returns of the closing prices (like daily, weekly, monthly, or yearly) on a particular stock, let's say, Apple stock. I have obtained the closing price using the below R code:

# import data
library(quantmod)
getSymbols("AAPL", src ="yahoo", from=Sys.Date()- 365, to=Sys.Date())
#View(AAPL)
APPLE <- AAPL$AAPL.Close
head(APPLE)
#                AAPL.Close
# 2023-03-13     150.47
# 2023-03-14     152.59
# 2023-03-15     152.99
# 2023-03-16     155.85
# 2023-03-17     155.00
# 2023-03-20     157.40

Please show me how to obtain the stock return of Apple stock most conveniently using a function like the sample below.

APPLE_ret <- return()
1

There are 1 answers

2
山の平和 On BEST ANSWER

If you want to use the same library in R then:

# Calculate daily returns with Delt
apple_returns_delt <- Delt(APPLE)
head(apple_returns_delt)

This returns the percentage change from one period to the next, if you want to change different time intervals you can adjust its parameters:

# Convert the daily closing prices into monthly prices (last of each month)
monthly_prices <- to.monthly(APPLE, indexAt = "lastof", OHLC = FALSE)

# Now, calculate the monthly returns using delt()
monthly_returns <- delt(Cl(monthly_prices))
head(monthly_returns)