Calculate Autocorrelation

I'm trying to calculate Autocorrelation.
I want this formula to work, but it is not accepted series
Correl(1, 250, (Close(0)/Close(1)-1)*100, (Close(1)/Close(2)-1)*100 )

I tried the more advanced way, but I can't get it to work. Not sure if it's my syntax or a P123 limitation with the formulas.

@AvgX:LoopAvg("((close(CTR)/close(CTR+1)-1)*100)",250)
@AvgY:LoopAvg("((close(CTR+1)/close(CTR+2)-1)*100)",250)
@Demeaning:LoopSum("(((close(CTR)/close(CTR+1)-1)100)-@AvgX)(((close(CTR+1)/close(CTR+2)-1)*100)-@AvgY)", 250)
@Norm:Pow(LoopSum("Pow((((close(CTR)/close(CTR+1)-1)*100)-@AvgX),2)", 250)*LoopSum("Pow((((close(CTR+1)/close(CTR+2)-1)*100)-@AvgY),2)", 250),0.5)
@Auto:@Demeaning/@Norm

This should work;

@AvgX:LoopAvg("((close(CTR)/close(CTR+1)-1)*100)",250)
@AvgY:LoopAvg("((close(CTR+1)/close(CTR+2)-1)*100)",250)
@Demeaning:LoopSum("(((close(CTR)/close(CTR+1)-1)*100)-@AvgX)*(((close(CTR+1)/close(CTR+2)-1)*100)-@AvgY)", 250)
@Norm:Pow(LoopSum("Pow((((close(CTR)/close(CTR+1)-1)*100)-@AvgX),2)", 250)*LoopSum("Pow((((close(CTR+1)/close(CTR+2)-1)*100)-@AvgY),2)", 250),0.5)
@Auto:(@Demeaning/@Norm)

And here's Alphanaut's explanation;
These rules compute the 250‑day lag‑1 autocorrelation of daily returns(correlation between today’s return and yesterday’s return). They don’t inherently “go long” by themselves unless you later add a condition like @Auto > 0.

Syntax used

  • Close(n): close price n bars ago (Close(0) most recent).
  • CTR: loop counter inside LoopAvg/LoopSum (iterates 0…249 here).
  • LoopAvg("formula(CTR)", 250): average of the formula over 250 iterations.
  • LoopSum("formula(CTR)", 250): sum over 250 iterations.
  • Pow(x, 0.5): square root.
  • @VarName:: in a Screen, this assigns a named variable you can reuse in later rules.

What each rule does

  1. @AvgX: average of daily return (%) over last 250 days, where
    X = (Close(CTR)/Close(CTR+1)-1)*100.
  2. @AvgY: average of lagged daily return (%) over last 250 days, where
    Y = (Close(CTR+1)/Close(CTR+2)-1)*100 (yesterday’s return).
  3. @Demeaning: computes the sum of demeaned cross-products:
    Σ (X-AvgX)*(Y-AvgY) → proportional to covariance between X and Y.
  4. @Norm: computes the normalization term:
    sqrt( Σ(X-AvgX)^2 * Σ(Y-AvgY)^2 ) → product of standard deviations (without the 1/N factor).
  5. @Auto: @Demeaning/@Norm = Pearson correlation(X, Y) → the autocorrelation (range ~[-1, +1]).
1 Like

A slightly easier to read version;

@AvgX:LoopAvg("%(Close(CTR), Close(CTR+1))", 250)
@AvgY:LoopAvg("%(Close(CTR+1), Close(CTR+2))", 250)
@Demeaning:LoopSum("(%(Close(CTR), Close(CTR+1)) - @AvgX) * (%(Close(CTR+1), Close(CTR+2)) - @AvgY)", 250)
@Norm:Pow(LoopSum("Pow(%(Close(CTR), Close(CTR+1)) - @AvgX, 2)", 250) * LoopSum("Pow(%(Close(CTR+1), Close(CTR+2)) - @AvgY, 2)", 250), 0.5)
@Auto:(@Demeaning/@Norm)
1 Like