%% Specify Aggregation Method for Each Variable
% This example shows how to specify the appropriate aggregation method for the units of a variable. Also, the example shows how to use convert2semiannual to aggregate both intra-day data and aggregated quarterly data, which result in equivalent semiannual aggregates.
% Load the simulated stock price data and corresponding logarithmic returns SimulatedStockSeries.mat.

load SimulatedStockSeries

% The price series Price contains absolute measurements, whereas the log returns series Log_Return is the rate 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.
% To illustrate how to maintain consistency among aggregation methods, use two approaches to aggregate DataTable so that the result has a semiannual periodicity.
% Pass DataTable directly to convert2semiannual.
% Aggregate DataTable so that the result has a quarterly periodicity by using convert2quarterly, and then pass the result to convert2semiannual.
% In both cases, specify reporting the last price and the sum of the log returns for each period.
% Directly aggregate the data so that the result has a semiannual periodicity. For each series, specify the aggregation method that is  appropriate for the unit.

aggmethods = ["lastvalue" "sum"];
SemiannualTT1 = convert2semiannual(DataTable,Aggregation=aggmethods);
tail(SemiannualTT1)

% SemiannualTT1 is a timetable containing the semiannual data. Price is a series of the final stock prices for each January-to-June period and July-to-December period, and Log_Return is the sum of the log returns for each semiannual period.
% Aggregate the data in two steps: aggregate the data so that the result has a quarterly periodicity, then aggregate the quarterly data to semiannual data. For each series, specify the aggregation method that is  appropriate for the unit.

QuarterlyTT = convert2quarterly(DataTable,Aggregation=aggmethods);
tail(QuarterlyTT)
SemiannualTT2 = convert2semiannual(QuarterlyTT,Aggregation=aggmethods)

% QuarterlyTT is a timetable with quarterly periodicity. Price is a series of the final stock prices for each quarter, and Log_Return is the sum of the log returns for each quarter.
% SemiannualTT1 and SemiannualTT2 are equal.
% Copyright 2021 The MathWorks, Inc.
%