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

aggmethods = ["lastvalue" "sum"];
WeeklyTT1 = convert2weekly(DataTable,Aggregation=aggmethods)

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

DailyTT = convert2daily(DataTable,Aggregation=aggmethods);
tail(DailyTT)
WeeklyTT2 = convert2weekly(DailyTT,Aggregation=aggmethods)

% DailyTT is a timetable with daily periodicity. Price is a series of the final stock prices for each day, and Log_Return is the sum of the log returns for each day.
% WeeklyTT1 and WeeklyTT2 are equal.
% convert2weekly reports results on Fridays by default. For weeks during which Friday is not an NYSE trading day, the function reports results on the previous business day. You can use the name-value argument EndOfWeekDay to specify a different day of the week that ends business weeks.
% Copyright 2021 The MathWorks, Inc.
%