问题
This might be an insignificant question but unfortunately I'm unable to solve it. I have a portfolio of stocks of 50 companies. I have the dates and the closing prices on that particular day for each of the companies. Data for each company varies with respect to the date from which the stock is being traded.
I used this code for calculating the daily returns:
return=matrix(NA,nrow(companies),ncol(companies)-1)
for (j in 2:52){
k=0
for (i in 1:nrow(companies)){
if (!is.na(companies[i,j]) & k==0) {
base= companies[i,j]
k=k+1
}
else {if ( k==1) {return[i,j-1] = ((companies[i,j]-base)/base)*100}
else {temp=0}
}
}
}
return[1:30,]
I now want to calculate the monthly returns for the same portfolio of companies. The formula I am using to calculate this is:
Return = [(Price on Last day of month) - (Price on other day)]*100/(Price on last day of month)
I want to repeat this process for 12 months in a year and for a period of 12 years (since that is the duration of data I have). I am planning to write a for loop to do this calculation. Could someone please help me out with this. Unfortunately, I cannot use the quantmod package since the stock prices are from the Indian Stock Exchange, from which quantmod can't read the prices.
回答1:
you should definitly use quantmod
, and you can. The quantmod
methods monthlyReturn, dailyReturn, ..., allReturns
require an xts
time series as input. So if you have daily data (e.g. close price) and the corresponding dates you can construct your time series and pass that to the desired quantmod
method.
Example:
library(package="quantmod")
prices <- c(7655.88, 7612.39, 7612.39, 7778.78, 7756.44, 7776.37)
dates <- as.Date(c("2012-12-26", "2012-12-27", "2012-12-30", "2013-01-01", "2013-01-02", "2013-01-03"))
ts <- xts(prices, dates)
dailyReturn(ts)
monthlyReturn(ts) # this will return bogus data because we don't have one month of data in this example
来源:https://stackoverflow.com/questions/14195059/calculating-monthly-returns-in-r