Found a dumb bug in previous LRI/TSF scan which made all but the final day off a little. Absolutely final corrected version [which matches MSWIN to 4 dec places] follows. -Bob ------------ //Stepwise Linear regression // corrects previous use of a, not y as endpoint //input = "80k+vol.lst"; output = "swLR.lst"; //processms ="E:\Meta\swLR",msdata; integer i, N1, N2, Sx, Sx1, lrflag, bar, first, last; float div, Sxx, Sxy, Sy, Sxx1, Sxy1, Sy1; float a, b, LR1, LR2, pLR1, pLR2; // p denotes previous val // float a1, a2, pa1, pa2, b1, b2, pb1, pb2; debug only string lrstr; first := 0; // negative will back test last := 0; // ending bar N1 := 5; // Set len of short LR here ****************** N2 := 50; // Set len of long LR here ****************** lrflag := 0; // Set to 0 for LRI; 1 for TSF ******* if lrflag != 0 then lrflag:= 1; endif; // a precaution if lrflag = 0 then lrstr := "LRI: "; else lrstr := "TSF: "; endif; Daystoload = 100 + N2; DaysRequired = 100 + N2; for bar = first to last do // back testing loop // Nest all overall conditions using builtin indicators before LR, i.e., // if HasOptions = True then // if close(bar) > 5 and close(bar) < 60 then // if macd(day) > macdsignal(day) then // if macd(day-1) < macdsignal(day-1) then if bar = first then // just the first time!! Sx := 0; Sxx := 0; Sxy := 0; Sy := 0; for i = first -1 to first -N1 step -1 do // N1 bars Sx := Sx + i; Sy := Sy + close(i); Sxx := Sxx + i*i; Sxy := Sxy + i*close(i); next i; div := N1*Sxx - Sx*Sx; a := (Sxx*Sy -Sx*Sxy)/div; b := (N1*Sxy - Sx*Sy)/div; pLR1 := a + b*(bar -1 +lrflag); // +b if TSF Sx1 := Sx; Sy1 := Sy; Sxx1 := Sxx; Sxy1 := Sxy; // save for N1 for i = first -N1 -1 to first -N2 step -1 do // N2 total bars Sx := Sx + i; Sy := Sy + close(i); // keep at it Sxx := Sxx + i*i; Sxy := Sxy + i*close(i); next i; div := N2*Sxx - Sx*Sx; a := (Sxx*Sy -Sx*Sxy)/div; b := (N2*Sxy - Sx*Sy)/div; pLR2 := a + b*(bar -1 +lrflag); // +b if TSF endif; // the first time!! // Stepwise calculation of LR1 and LR2 i := bar -N2; // Replace N2 bar with current bar Sx := Sx +bar -i; Sy := Sy +close(bar) -close(i); Sxx := Sxx +bar*bar -i*i; Sxy := Sxy +bar*close(bar) -i*close(i); div := N2*Sxx - Sx*Sx; a := (Sxx*Sy -Sx*Sxy)/div; b := (N2*Sxy - Sx*Sy)/div; LR2 := a + b*(bar +lrflag); // +b if TSF // now calc LR1 using the saved values i := bar -N1; // Replace N1 with current bar Sx1 := Sx1 +bar -i; Sy1 := Sy1 +close(bar) -close(i); Sxx1 := Sxx1 +bar*bar -i*i; Sxy1 := Sxy1 +bar*close(bar) -i*close(i); div := N1*Sxx1 - Sx1*Sx1; a := (Sxx1*Sy1 -Sx1*Sxy1)/div; b := (N1*Sxy1 - Sx1*Sy1)/div; LR1 := a + b*(bar +lrflag); // +b if TSF if LR1 > LR2 and pLR1 < pLR2 then // only an example println symbol,",",date(bar),",",lrstr,",",LR1:7:4,",",pLR1:7:4,",", LR2:7:4,",",pLR2:7:4; endif; //endif; endif; endif; endif; pLR1:= LR1; pLR2:= LR2; next bar; ---------- |