Loop with Time series
4 views (last 30 days)
Show older comments
Dear all, I'm currently trying to build a Global minimum Variance Portfolio that changes over time. I have a timetable of several daily returns of 8 assets, and I want lo calculate the global minimum variance portfolio for that given month. I tried with imposing 21 as the number of days in a month, however this is not optimal, since months also have 22 and 23 days. Is it possible to create a loop where I link the groups to the belonging month?
Brief example: I have 5208 daily returns, assuming that every month has 21 days the output should be a 248x8 matrix
Thank you all
0 Comments
Answers (1)
Voss
on 26 Sep 2023
You can use the month and year functions, along with findgroups, to group the timetable by year and month. Then splitapply to perform some function (e.g., your method to "calculate the global minimum variance portfolio") on each month's data.
% construct a timetable like yours, containing (random)
% daily returns of 8 assets over 5208 days:
n_days = 5208;
n_assets = 8;
temp = num2cell(randn(n_days,n_assets),1);
t = timetable(datetime(now()-(n_days-1:-1:0).', ...
'ConvertFrom','datenum','Format','dd-MMM-yyyy'),temp{:})
% group returns by year and month
mm = month(t.Time);
yy = year(t.Time);
g = findgroups(yy,mm);
% apply a function on each group (i.e., each month+year)
% the function get_max_return() here calculates the maximum
% value amongst all the returns of that group
tC = splitapply(@(varargin)get_max_return(varargin{:}),t,g)
function out = get_max_return(varargin)
out = max([varargin{:}],[],'all');
end
0 Comments
See Also
Categories
Find more on Data Transformation in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!