/* Adaptive Moving Average AMA(k,fsc,ssc) */ /* Notice: Some codes use a direction rather than absolute value of it */ /* for the numerator of eratio. I follow Kaufman's as in Ehlors' book. */ /* If we consider k+1 periods, calculate both numerator and denominator */ /* for k+1 periods rather than k periods only for denominator. */ new; cls; let data[50,1]= 60 61 60 62 60 63 64 65 69 70 69 66 64 64 62 64 65 55 53 57 60 58 63 63 63 68 69 69 68 69 70 67 66 67 68 69 69 77 80 80 78 76 76 72 71 70 73 71 78 80 ; data=rev(data); /* original data in reverse order */ t=seqa(1,1,rows(data)); library pgraph; graphset; _pltype=6; _plegctl=1; _plegstr="actual\000AMA(5)\000AMA(10)"; title("Adaptive Moving Average"); fsc=2; /* Fast SC Period */ ssc=30; /* Slow SC Period */ xy(t,data~ama(data,5,fsc,ssc)~ama(data,10,fsc,ssc)); proc ama(x,k,fsc,ssc); local diff,absdiff,num,denom,i,eratio,fconst,sconst,c,m,alpha; diff=zeros(1,cols(x))|(x[2:rows(x),.]-x[1:rows(x)-1,.]); absdiff=abs(diff); num=miss(zeros(rows(x),cols(x)),0); denom=miss(zeros(rows(x),cols(x)),0); i=k+1; do while i<=rows(x); num[i,.]=abs(x[i,.]-x[i-k,.]); /* absolute value */ denom[i,.]=sumc(absdiff[i-k:i,.])'; /* for k+1 periods */ i=i+1; endo; eratio=num./denom; fconst=2/(fsc+1); sconst=2/(ssc+1); c=(eratio*(fconst-sconst)+sconst)^2; /* eratio and c for frist k period being blank */ alpha=2/(k+1); m=zeros(rows(x),cols(x)); /* the same as ema(k) for first k period(from 1 through k) */ m[1,.]=x[1,.]; i=2; do while i<=k; m[i,.]=alpha*x[i,.]+(1-alpha)*m[i-1,.]; i=i+1; endo; /* then, ama for the rest of the period */ i=k+1; do while i<=rows(x); m[i,.]=m[i-1,.]+c[i,.].*(x[i,.]-m[i-1,.]); i=i+1; endo; retp(m); endp;