簡體   English   中英

計算R中不同股票的每日收益

[英]Calculating the daily return for different stocks in R

我正在嘗試使用常用的對數差分方法計算 R 中數據集的對數收益。

我當前的每日收盤價列表如下所示:

在此處輸入圖像描述

總的來說,我有一個涵蓋一年期間的 4,000 只股票的數據集。

這是試用數據:

日期 <- c(01.11.2019、04.11.2019、05.11.2019、06.11.2019、07.11.2019、08.11.2019)

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)

我想在 R 中計算這個。

通常該公式用於計算回報。

回報 =(新價格 - 舊價格)/舊價格 [百分比] 其中“新價格 = t”和“舊價格 = t-1”

我嘗試了以下代碼:

# First upload the financial data in R
library(readxl)
Closing_Prices_2020 <- read_excel("Closing_Prices_2020.xlsx")

然后我嘗試了兩個選項:

第一次嘗試:

Returns_2020 <- Return.calculate(Daily_Returns_2020, method="log")

第二次嘗試:

CalculateReturns(Closing_Prices_2020$ACCR.PK, method = c("discrete", "log"))

他們都不適合我。 有人幫助計算每日回報嗎? 謝謝!

這是使用tidyquant的方法。

加載數據:

library(tidyverse)
library(tidyquant)

df <- tibble(
  Date = c(
    '01.11.2019',
    '04.11.2019',
    '05.11.2019',
    '06.11.2019',
    '07.11.2019',
    '08.11.2019'
  ),
  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)
) %>% 
  mutate(Date = Date %>% 
           as.Date(format = "%d.%m.%Y"))

計算每只證券的每日回報

df %>% 
  pivot_longer(-Date, names_to = "ticker", values_to = "price") %>% 
  group_by(ticker) %>% 
  tq_mutate(select = price, 
            mutate_fun = periodReturn, 
            period = "daily", 
            col_rename = "daily_return") 

# A tibble: 18 × 4
# Groups:   ticker [3]
   ticker  Date         price daily_return
   <chr>   <date>       <dbl>        <dbl>
 1 ACCR.PK 2019-11-01  0.0035      0      
 2 ACCR.PK 2019-11-04  0.003      -0.143  
 3 ACCR.PK 2019-11-05  0.0035      0.167  
 4 ACCR.PK 2019-11-06  0.0057      0.629  
 5 ACCR.PK 2019-11-07  0.0032     -0.439  
 6 ACCR.PK 2019-11-08  0.0032      0      
 7 SWGI.PK 2019-11-01  0.51        0      
 8 SWGI.PK 2019-11-04  0.51        0      
 9 SWGI.PK 2019-11-05  0.51        0      
10 SWGI.PK 2019-11-06  0.51        0      
11 SWGI.PK 2019-11-07  0.51        0      
12 SWGI.PK 2019-11-08  0.51        0      
13 HURC.OQ 2019-11-01 35.5         0      
14 HURC.OQ 2019-11-04 35.6         0.00253
15 HURC.OQ 2019-11-05 35.8         0.00393
16 HURC.OQ 2019-11-06 35.5        -0.00671
17 HURC.OQ 2019-11-07 35.6         0.00225
18 HURC.OQ 2019-11-08 36           0.0112 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM