MATLAB Answers

Volatility calculation (by analogy of moving average)

43 views (last 30 days)
Caxap Puc
Caxap Puc on 21 Oct 2016
Answered: Adolfo on 24 May 2019
Hi, guys. How can I calculate Volatility for the data set ( I'm pretty newbie in Matlab and programming, that's why loops are hard for my understanding.
%ticker - is array of data
Z = 252; %Number of trading Days in a year
n = 20; %window of volatility
Volat=zeros(length(ticker)- n, 1);
for i = 1:n
log_change = log(ticker(2:n+1)./ticker(1:n));
stdev = std(log_change);
Vol(i) = (stdev*sqrt(252))';
It calculates the only one number, however I'm trying to do 2 things: 1) Create "volatility" array (dataset), which, of course, will contain "ticker minus n" numbers; 2) Create "volatility" as window - from number of start element to number of end element from original dataset.
Will be glad for any assistance.

Answers (1)

Adolfo on 24 May 2019
You have to calculate a time-window volatily of N ticks.
A simple function for only one series of data, that not considers any possible errors on the data structure, could be implemented as follows:
function r = histvar(serie, N)
r = nan(size(serie));
dailyret = (serie(2:end)-serie(1:end-1))./serie(1:end-1);
for i = N+1:size(serie, 1)-1
window = dailyret(i-N:i, :);
r(i+1) = sqrt(cov(window));

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!