Learn R Programming

PortfolioTesteR (version 0.1.4)

calc_rolling_correlation: Rolling correlation of each symbol to a benchmark

Description

Computes rolling correlations between each symbol and a benchmark series (e.g., SPY) using simple returns over a fixed lookback window.

Usage

calc_rolling_correlation(
  data,
  benchmark_symbol = "SPY",
  lookback = 60,
  min_periods = NULL,
  method = c("pearson", "spearman")
)

Value

A data.table with Date and one column per non-benchmark symbol, containing rolling correlations. Insufficient data yields NAs.

Arguments

data

A data.frame or data.table with a Date column and one column per symbol containing prices. Must include benchmark_symbol.

benchmark_symbol

Character, the benchmark column name (default "SPY").

lookback

Integer window size (>= 2) for rolling correlations.

min_periods

Minimum number of valid observations within the window to compute a correlation. Default is ceiling(lookback * 0.67).

method

Correlation method, "pearson" (default) or "spearman".

Details

Returns are computed as simple returns \((P_t - P_{t-1})/P_{t-1}\). Windows with fewer than min_periods valid pairs are marked NA.

See Also

calc_momentum(), calc_rolling_volatility()

Examples

Run this code
data(sample_prices_weekly)
corr <- calc_rolling_correlation(
  data = sample_prices_weekly,
  benchmark_symbol = "SPY",
  lookback = 20
)
head(corr)

Run the code above in your browser using DataLab