Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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()

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading