$begingroup$
I’m testing the randomness of the stock market, and want to do a runs test on the logarithmic returns. Now, financial returns can be either negative, zero, or positive. The standard runs test is executed on a dichotomic variable. Is there a way to make a runs test with the three categories in R?
$endgroup$
0
$begingroup$
One way would be to do it manually:
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")
But I would like to know if there’s a built-in or easier way to do it.
$endgroup$