You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R语言中计算多只股票的日收益率(含对数收益率)

在R中计算多只股票的日对数收益率解决方案

问题分析

你之前的尝试失败主要有几个原因:

  • 第一种方法中使用了未定义的对象Daily_Returns_2020(应为导入的Closing_Prices_2020),且未加载PerformanceAnalytics包(Return.calculate函数来自该包),同时未将数据转换为符合要求的时间序列格式。
  • 第二种方法的CalculateReturns(来自TTR包)参数错误:method不能同时传入两个选项,且仅针对单只股票计算,未实现批量处理多列数据。

解决方案

下面提供两种可靠的批量计算方法,适配你的4000只股票数据集:

方法1:使用PerformanceAnalytics包(专业金融分析工具)

该包的Return.calculate支持批量处理多只股票,原生支持对数收益率计算:

# 加载所需包
library(readxl)
library(PerformanceAnalytics)
library(xts)

# 导入数据并处理日期格式
Closing_Prices_2020 <- read_excel("Closing_Prices_2020.xlsx")
Closing_Prices_2020$Date <- as.Date(Closing_Prices_2020$Date, format = "%d.%m.%Y")

# 将数据转换为xts时间序列对象(必须以日期为索引)
price_xts <- xts(Closing_Prices_2020[, -1], order.by = Closing_Prices_2020$Date)

# 计算对数收益率
Returns_2020 <- Return.calculate(price_xts, method = "log")

# 查看结果(首行NA,因为无前置日期数据)
head(Returns_2020)

方法2:使用dplyr手动计算(轻量灵活,适合大数据)

如果不想依赖金融分析包,可以用对数收益率的核心公式log(price_t) - log(price_t-1)批量计算:

# 加载所需包
library(readxl)
library(dplyr)

# 导入数据并处理日期格式
Closing_Prices_2020 <- read_excel("Closing_Prices_2020.xlsx")
Closing_Prices_2020$Date <- as.Date(Closing_Prices_2020$Date, format = "%d.%m.%Y")

# 批量计算所有股票的对数收益率
Returns_2020 <- Closing_Prices_2020 %>%
  mutate(across(where(is.numeric), ~ log(.) - lag(.), .names = "{col}_log_return"))

# 查看结果
head(Returns_2020)

示例数据验证

用你提供的示例数据测试方法2,代码如下:

# 构造示例数据
Date <- as.Date(c("01.11.2019", "04.11.2019", "05.11.2019", "06.11.2019", "07.11.2019", "08.11.2019"), format = "%d.%m.%Y")
ACCR.PK <- c(0.0035, 0.003, 0.0035, 0.0057, 0.0032, 0.0032)
SWGI.PK <- c(0.51, 0.51, 0.51, 0.51, 0.51, 0.51)
HURC.OQ <- c(35.53, 35.62, 35.76, 35.52, 35.6, 36.07)
sample_data <- data.frame(Date, ACCR.PK, SWGI.PK, HURC.OQ)

# 计算对数收益率
sample_returns <- sample_data %>%
  mutate(across(where(is.numeric), ~ log(.) - lag(.), .names = "{col}_log_return"))

print(sample_returns)

运行后会得到每只股票的对数收益率列,其中SWGI.PK的收益率全为NA和0(因价格无波动),符合预期。


内容的提问来源于stack exchange,提问作者Li4991

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 13:34:39