fft filtering problem revisited

View: New views
1 Messages — Rating Filter:   Alert me  

fft filtering problem revisited

by babelproofreader :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

As a follow up to a query I posted earlier, http://www.nabble.com/Problem-with-using-fft-and-ifft-functions-td24588890.html, and after more reading on the subject I now have the code below, which is not quite working

typprice=(high.+low.+close)./3;

% check to see if there are negative prices due to backadjusted continuous prices  
 if(min(min(typprice))<=0)
 backadj=(abs(min(min(typprice)))+tick); % if so, calculate an adjustment factor
 else
 backadj=0; % otherwise set adjustment factor to zero
 endif

adjtypprice=typprice.+backadj;
detrendedprice=adjtypprice;

% First, detrend the data using logs
logchange=log10(adjtypprice./shift(adjtypprice,1));
avelogchange=mean(logchange(2:end));
adjlogchange=logchange.-avelogchange;
adjlogchange(1,1)=0.0;

 for i=2:n
 detrendedprice(i,1)=detrendedprice(i-1,1)*(10^adjlogchange(i,1));
 endfor

% raise length to the next power of two and pad with zeros as preparation for the fft
l=2^(nextpow2(rows(detrendedprice)));
diff=l-rows(detrendedprice);
pad=zeros(diff,1);
padded_detrendedprice=[detrendedprice;pad];

% The actual filtering in the frequency domain
fouriertran=fft(padded_detrendedprice);
[b,a]=butter(2,0.96);
[h,w]=freqz(b,a,l,"whole");
invfouriertran=real(ifft(h.*fouriertran));

% Remove "padding"
unpadded_invfouriertran=invfouriertran(1:n);

% retrend
fft_logchange=log10(unpadded_invfouriertran./shift(unpadded_invfouriertran,1));
adj_fft_logchange=fft_logchange.+avelogchange;
adj_fft_logchange(1,1)=0.0;
retrendedprice=zeros(n,1);
retrendedprice(1,1)=adjtypprice(1,1);

 for i=2:n
 retrendedprice(i,1)=retrendedprice(i-1,1)*(10^adj_fft_logchange(i,1));
 endfor

recon_price=retrendedprice.-backadj;

x=(1:n)';
A=[x,typprice,recon_price];
dlmwrite("fftchart",A)

The problem is that the smoothed price, recon_price, is either above or below typprice when plotted, the difference varying depending on the second value of the function butter(2,???). Of course what I would like is for recon_price to be a smoothed version of typpprice. Can someone point out the error(s) in my code, or indeed, my approach?