%% Using Timetables in Finance
%
% This example shows how to use timetables to visualize and calculate weekly statistics from simulated daily stock data.
%
% Step 1. Load the data.
% The data for this example is in the MAT-file SimulatedStock.mat, which loads the following:
% Dates corresponding to the closing stock prices, TMW_DATES
% Opening stock prices, TMW_OPEN
% Daily high of stock prices, TMW_HIGH
% Daily low of  stock prices, TMW_LOW
% Closing stock prices, TMW_CLOSE, TMW_CLOSE_MISSING
% Daily volume of traded, TMW_VOLUME
% Data in a table, TMW_TB

load SimulatedStock.mat TMW_*

%
% Step 2. Create timetables.
% In timetables, you can work with financial time series rather than with vectors. When using a timetable, you can easily track the dates. You can manipulate the data series based on the dates, because a timetable object tracks the administration of a time series.
% Use the MATLAB® timetable function to create a timetable object. Alternatively, you can use the MATLAB conversion function table2timetable to convert a table to a timetable. In this example, the timetable TMW_TT is constructed from a table and is only for illustration purposes. After you create a timetable object, you can use the Description field of the timetable object to store meta-information about the timetable.

% Create a timetable from vector input
TMW = timetable(TMW_OPEN,TMW_HIGH,TMW_LOW,TMW_CLOSE_MISSING,TMW_VOLUME, ... 
    'VariableNames',{'Open','High','Low','Close','Volume'},'RowTimes',TMW_DATES);

% Convert from a table to a timetable
TMW_TT = table2timetable(TMW_TB,'RowTimes',TMW_DATES);

TMW.Properties.Description = 'Simulated stock data.';

TMW.Properties

%
% Step 3. Calculate basic data statistics, and fill the missing data.
% Use the MATLAB summary function to view basic statistics of the timetable data. By reviewing the summary for each variable, you can identify missing values. You can then use the MATLAB fillmissing function to fill in missing data in a timetable by specifying a fill method.

summaryTMW = summary(TMW);
summaryTMW.Close
TMW = fillmissing(TMW,'linear');
summaryTMW = summary(TMW);
summaryTMW.Close
summaryTMW.Time

%
% Step 4. Visualize the data.
% To visualize the timetable data, use financial charting functions such as highlow or movavg. For this example, the moving average information is plotted on the same chart for highlow to provide a complete visualization. To obtain the stock performance in 2014, use the MATLAB timerange function to select rows of the timetable. To visualize a technical indicator such as the Moving Average Convergence Divergence (MACD), pass the timetable object into the macd function for analysis.

index = timerange(datetime('01-Jan-2014','Locale','en_US'),datetime('31-Dec-2014','Locale','en_US'),'closed');

highlow(TMW(index,:));
hold on

ema15 = movavg(TMW(:,'Close'),'exponential',15);
ema25 = movavg(TMW(:,'Close'),'exponential',25);

ema15 = ema15(index,:);
ema25 = ema25(index,:);
plot(ema15.Time,ema15.Close,'r');
plot(ema25.Time,ema25.Close,'g');
hold off

legend('Price','15-Day EMA','25-Day EMA')
title('Highlow Plot for TMW')

%

[macdLine, signalLine] = macd(TMW(:,'Close'));

plot(macdLine.Time,macdLine.Close);
hold on
plot(signalLine.Time,signalLine.Close);
hold off

title('MACD for TMW')
legend('MACD Line', 'Signal Line')

%
% Step 5. Create a weekly return and volatility series.
% To calculate weekly return from the daily stock prices, you must resample the data frequency from daily to weekly. When working with timetables, use the MATLAB functions retime or synchronize with various aggregation methods to calculate weekly statistics. To adjust the timetable data to a time-vector basis, use retime and use synchronize with multiple timetables.

weeklyOpen = retime(TMW(:,'Open'),'weekly','firstvalue');
weeklyHigh = retime(TMW(:,'High'),'weekly','max');
weeklyLow = retime(TMW(:,'Low'),'weekly','min');
weeklyClose = retime(TMW(:,'Close'),'weekly','lastvalue');
weeklyTMW = [weeklyOpen,weeklyHigh,weeklyLow,weeklyClose];

weeklyTMW = synchronize(weeklyTMW,TMW(:,'Volume'),'weekly','sum');
head(weeklyTMW)

%  To perform calculations on entries in a timetable, use the MATLAB rowfun function to apply a function to each row of a weekly frequency timetable.

returnFunc = @(open,high,low,close,volume) log(close) - log(open);
weeklyReturn = rowfun(returnFunc,weeklyTMW,'OutputVariableNames',{'Return'});

weeklyStd = retime(TMW(:,'Close'),'weekly',@std);
weeklyStd.Properties.VariableNames{'Close'} = 'Volatility';

weeklyTMW = [weeklyReturn,weeklyStd,weeklyTMW]  

% Copyright 2012 The MathWorks, Inc.