%% Use Custom Aggregation Method to Convert Daily Data to Monthly Periodicity
% You can apply custom aggregation methods using function handles. Specify a function handle to aggregate related variables in a timetable while maintaining consistency between aggregated results when converting from a daily to a monthly periodicity.
% Load the simulated stock price data and corresponding logarithmic returns SimulatedStockSeries.mat.

load SimulatedStockSeries

% Include another variable to the data called Simple_Return that contains the simple (proportional) returns associated with the price series, and examine the first few rows.

DataTable.Simple_Return = exp(DataTable.Log_Return) - 1;  % Log returns to simple returns
head(DataTable)

% The price series Price contains absolute measurements, whereas the log and simple returns series, Log_Return and Simple_Returns, are the rates of change of the price series among successive observations. Because the series have different units, you must specify the appropriate method when you aggregate the series. Specifically, if you report the final price for a given periodicity, you must report the sum of the log returns within each period and a custom transformation for simple returns.
% Create a function to aggregate simple returns.

f = @(x)(prod(1 + x,1,'omitnan') - 1);  

% Aggregate the data so that the result has an monthly periodicity. For each series, specify the aggregation method that is  appropriate for the unit.

TT = convert2monthly(DataTable,Aggregation={'lastvalue' 'sum' f});
head(TT)

% The aggregation function for simple returns operates along the first dimension (row) and omits missing data (NaNs).
% For more information on custom aggregation functions, see timetable and retime.
% Copyright 2021 The MathWorks, Inc.