I am going to expand this post to further discussion -> "How to calculate the equity beta in R"
But, before doing so, it is important to understand the volatility concept. Volatility is a standard deviation of stock returns in a given period. One of the golden rule in investment community says that "Low risk low return, and High risk high return." When we refer to "risk," it means the standard deviation of the return. It is important for investors to have this information when they are about to make portfolio. They want the certain return, but they also want to know what is the level of risk that the portfolio has. One could lose a lot of money in a bad time if his portfolio is too risky.
I am going to look into the volatility of Apple stock in 2015. Luckily, you don't need to get stock information from the internet. There is a great library, which allows you to have the information of stocks with simple commands.
Just like LIBOR case, you need to install a package for this, if you don't have.
install.packages("tseries")
[Source code]
library(tseries)
#Getting data from server
data <- get.hist.quote("AAPL", #Tick mark
start="2015-01-01", #Start date YYYY-MM-DD
end="2015-12-31" #End date YYYY-MM-DD
)
#We only take into account "Closing price", the price when the market closes
yesterdayprice <- data$Close
#This is a unique feature of R better than Excel
#I need to calculate everyday return
#The stock return is defined as (today price - yesterday price)/today price
todayprice <- lag(yesterday price) #Lag = Pushback one day in time series
rets <- (todayprice - yesterdayprice)/todayprice
#Annualized and percentage, sd=standard deviation of that collection
vol <- sd(rets) * sqrt(length(todayprice)) * 100
#Draw the histogram on the return
hist(rets, xlab="Return", ylab="Frequency", main="Histogram of Apple stock in 2015")
#String concatenation
output <- paste("Volitility: ", vol, sep="")
output <- paste(output, "%", sep="")
print(output)
[Output]
> source('~/Documents/FinanceInR/stockvolatility.R')
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0100 1893 0 1893 0 0 14903 0 --:--:-- --:--:-- --:--:-- 14905100 18323 0 18323 0 0 107k 0 --:--:-- --:--:-- --:--:-- 107k
time series starts 2015-01-02
[1] "Volitility: 26.7574299862969%"
No comments:
Post a Comment