对两个以上的分类变量运行测试(在 R 中)

问题描述 投票:0回答:1

我正在测试股票市场的随机性,并想对对数收益进行运行测试。现在,财务回报可以是负数、零或正数。标准游程检验是在二分变量上执行的。有没有办法用R中的三个类别进行运行测试?

r testing random statistics
1个回答
0
投票

一种方法是手动完成:

library(tidyverse)

# Assign signs to the log returns (positive = 1, zero = 0, negative = -1)
sp <- sp %>%
  mutate(sign_return = case_when(
    log_return > 0 ~ 1,
    log_return == 0 ~ 0,
    log_return < 0 ~ -1
  ))

# Count the total number of positive, zero, and negative returns
pos_count <- sum(sp$sign_return == 1)
zero_count <- sum(sp$sign_return == 0)
neg_count <- sum(sp$sign_return == -1)

# Identify the runs (change of signs)
runs <- sum(diff(sp$sign_return) != 0) + 1

# Expected number of runs (mean under null hypothesis of randomness)
n <- length(sp$sign_return)
expected_runs <- (2 * pos_count * neg_count + 2 * pos_count * zero_count + 2 * neg_count * zero_count) / n + 1

# Standard deviation of runs
std_runs <- sqrt((2 * pos_count * neg_count * (2 * pos_count * neg_count - n)) / (n^2 * (n - 1)))

# Z-score for the runs test
z_score <- (runs - expected_runs) / std_runs

# Print the results
cat("Number of runs:", runs, "\n")
cat("Expected number of runs:", expected_runs, "\n")
cat("Z-score:", z_score, "\n")

# Perform a two-tailed test based on the Z-score
p_value <- 2 * pnorm(-abs(z_score))
cat("P-value:", p_value, "\n")

但我想知道是否有内置或更简单的方法来做到这一点。

© www.soinside.com 2019 - 2024. All rights reserved.