%% 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 convert2quarterly to aggregate both intra-day data and aggregated monthly data, which result in equivalent quarterly 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 quarterly periodicity.
% Pass DataTable directly to convert2quarterly.
% Aggregate DataTable so that the result has a monthly periodicity by using convert2monthly, and then pass the result to convert2quarterly.
% 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 quarterly periodicity. For each series, specify the aggregation method that is  appropriate for the unit.

aggmethods = ["lastvalue" "sum"];
QuarterlyTT1 = convert2quarterly(DataTable,Aggregation=aggmethods);
tail(QuarterlyTT1)

% QuarterlyTT1 is a timetable containing the annual data. Price is a series of the final stock prices for each year, and Log_Return is the sum of the log returns for each quarter.
% Aggregate the data in two steps: aggregate the data so that the result has a monthly periodicity, then aggregate the monthly data to quarterly data. For each series, specify the aggregation method that is appropriate for the unit.

MonthlyTT = convert2monthly(DataTable,Aggregation=aggmethods);
tail(MonthlyTT)
QuarterlyTT2 = convert2quarterly(MonthlyTT,Aggregation=aggmethods);
tail(QuarterlyTT2)

% MonthlyTT is a timetable with monthly periodicity. Price is a series of the final stock prices for each month, and Log_Return is the sum of the log returns for each month.
% QuarterlyTT1 and QuarterlyTT2 are equal.
% Copyright 2021 The MathWorks, Inc.