Demonstrating the Capital Asset Pricing Model (CAPM) in R Understanding CAPM

The Capital Asset Pricing Model (CAPM) is a model that describes the relationship between systematic risk and expected return for a financial asset. It’s often used to price assets and evaluate investment performance.  

R Code Implementation

library(quantmod)
## Ładowanie wymaganego pakietu: xts
## Ładowanie wymaganego pakietu: zoo
## 
## Dołączanie pakietu: 'zoo'
## Następujące obiekty zostały zakryte z 'package:base':
## 
##     as.Date, as.Date.numeric
## Ładowanie wymaganego pakietu: TTR
## Registered S3 method overwritten by 'quantmod':
##   method            from
##   as.zoo.data.frame zoo
library(PerformanceAnalytics)
## 
## Dołączanie pakietu: 'PerformanceAnalytics'
## Następujący obiekt został zakryty z 'package:graphics':
## 
##     legend

Get historical data for a stock and a market index (e.g., S&P 500)

getSymbols(c("AAPL", "^GSPC"), from = "2018-01-01", to = "2023-12-31")
## [1] "AAPL" "GSPC"

Calculate daily returns

stock_returns <- na.omit(ROC(AAPL[,6]))
market_returns <- na.omit(ROC(GSPC[,6]))

Calculate beta (systematic risk)

beta <- CAPM.beta(Ra = stock_returns, Rb = market_returns)

Assume a risk-free rate (e.g., 3-month Treasury bill rate)

risk_free_rate <- 0.03

Calculate the expected return using CAPM

expected_return <- risk_free_rate + beta * (mean(market_returns) - risk_free_rate)