本文介绍了计算R的月度回报的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 这可能是一个微不足道的问题,但不幸的是我无法解决它。我有一个50家公司的股票组合。我有每个公司的特定日期和收盘价。每家公司的数据根据​​交易日期的不同而不同。 我用这个代码计算每日回报: return =(矩阵(NA,nrow(公司),ncol(公司)-1) (j 2:52){k = 0 我在1:nrow(companies)){ if(!is.na(companies [i,j])& k == 0){ase = 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,] pre> 我现在想计算相同公司组合的月度回报。我用来计算的公式是: Return = [(每月最后一天价格) - (其他天))* 100 /(每月最后一天的价格) 我想重复这个过程一年12个月,12年(因为这是我所拥有的数据的持续时间)。我打算写一个for循环来做这个计算。有人可以帮我解决这个问题吗?不幸的是,我不能使用quantmod软件包,因为股票价格来自印度证券交易所,quantmod无法读取价格。 解决方案你应该明确地使用 quantmod ,你可以。 quantmod 方法 monthlyReturn,dailyReturn,...,allReturns 需要 xts 时间序列作为输入。所以,如果你有每日数据(如收盘价)和相应的日期,你可以构建你的时间序列,并将其传递给所需的 quantmod 方法。 示例: library(package =quantmod) 价格日期 ts dailyReturn(ts) monthlyReturn(ts)#这将返回假数据,因为我们在这个例子中没有一个月的数据 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. 解决方案 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 这篇关于计算R的月度回报的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-01 06:49