Here is a function to calculate the systemic risk in a stock – the stock's beta times the standard deviation of the market returns. It also provides the stock's total standard deviation for reference.

By default the regression includes an intercept (the stock's alpha). You can set the intercept to 0 if you choose by setting the 'through.origin' option to TRUE.

``````library(quantmod)

sys.risk <- function(ticker, start.date, through.origin = F){
stk <-   getSymbols(ticker, from = start.date, auto.assign=F)
mkt <-   getSymbols('^GSPC', from = start.date, auto.assign=F)
stk <- as.vector(Delt(stk[,6])[-1])
mkt <- as.vector(Delt(mkt[,6])[-1])
X <- cbind(1, mkt)
if (!through.origin)
{
beta <- as.vector(solve(t(X)%*%X)%*%(t(X)%*%stk)) }
else {
beta <- solve(t(mkt)%*%mkt)%*%(t(mkt)%*%stk) }
cat("The daily systemic risk is:", beta*sd(mkt)*100, "% \n")
cat("The yearly systemic risk is:", beta*sd(mkt)*sqrt(252)*100, "% \n")
cat("The yearly total risk in", ticker, "is:", sd(stk)*sqrt(252)*100, "% \n")
}
``````

Paste the above into R and you can then use the function like:

``````sys.risk('TSLA', start.date = '2015-01-01')
``````
``````## The daily systemic risk is: 1.026354 %
## The yearly systemic risk is: 16.29287 %
## The yearly total risk in TSLA is: 35.81308 %
``````
``````sys.risk('TSLA', start.date = '2015-01-01', through.origin = TRUE)
``````
``````## The daily systemic risk is: 1.014056 %
## The yearly systemic risk is: 16.09764 %
## The yearly total risk in TSLA is: 35.81308 %
``````