Tuesday, February 16, 2010

get_hisVolatility.m


function vol = get_hisVolatility(closes, N)
%
%   This script is to calculate the historical
%   volatility for close prices using N days sliding window
%   If N is not specified, a default of 20 days will be
%   used.
%
%   Copyright 2010 EdgeMe
%   EdgeMe, 12-Feb-2010
%
%
if nargin==0
    N=20;
end

    dataN=numel(closes);
    vol=[];
    if dataN<N
      warning ('Not enough data')
      return;
    end

    log_change(1)=0;
    for i=2:dataN
    log_change(i) = log(closes(i)/closes(i-1));
    end

    for i=N+1:dataN
    stdev = std(log_change(i-N+1:i));

    % Normalize to annual volatility
    vol(i)= stdev*sqrt(252);
    end

    %fillin the first N days using N+1 vol
    for i=1:N
        vol(i)=vol(N+1);
    end

end

No comments:

Post a Comment