clear; close; clc;

A = [1 2 3];          % 1x3 double array
x = 5;                % scalar double
M = rand(3);          % 3x3 double matrix

s1 = "GDP";       % string
s2 = 'Inflation'; % char

C = {'Italy', 2024, 2.5};

d = datetime(2024,1,1);   % Jan 1, 2024

S.Country = 'Italy';
S.Year    = 2024;
S.GDP     = 2.5;


clear; close; clc;


T = readtable('gdp_quarterly.csv');
head(T)

% Excel
X = readmatrix('gdp_quarterly.xlsx');

% Check variable types
summary(T)

% Suppose we computed GDP growth rates
T.growth = [NaN; diff(log(T.GDP))*100];
% Write to new CSV
writetable(T,'gdp_cleaned.csv');


% Example: write results to log
fid = fopen('results.log','w');
fprintf(fid,'Mean GDP growth: %.2f%%\n', mean(T.growth,'omitnan'));
fprintf(fid,'Sample size: %d\n', height(T));
fclose(fid);

% Convert to timetable indexed by Time
TT = table2timetable(T, 'RowTimes', 'Time');


% Optional: drop duplicate time column if present, then sort
if any(strcmp('Time', TT.Properties.VariableNames))
    TT.Time = [];
end
TT = sortrows(TT);   % ensure chronological order
head(TT)

% Levels to logs
TT.GDP_log = log(TT.GDP);

% QoQ growth (approx, in %): 100 * diff(log(GDP))
TT.GDP_qoq = [NaN; 100 * diff(TT.GDP_log)];

% Quick diagnostics
summary(TT)

% Remove rows with any missing entries
TT_nomiss = rmmissing(TT);

% Or fill missing values (choose a method)
TT_fill = fillmissing(TT,'linear');   % 'previous','next','constant',...

% Exact YoY growth (%, needs 4-quarter lag)
TT.GDP_yoy = NaN(height(TT),1);
TT.GDP_yoy(5:end) = 100 * ( ...
    TT.GDP(5:end) ./ TT.GDP(1:end-4) - 1 );

% Inspect alignment
head(TT(:, {'GDP','GDP_qoq','GDP_yoy'}))

% Checkpoint for reproducibility
save('gdp_quarterly_clean.mat','TT');

% Later: reload and continue
clear TT
load('gdp_quarterly_clean.mat','TT');
whos TT

%----
%% Example: Build quarterly datetime from Year + Quarter
clear; clc;

% ---- Sample data: quarterly GDP ----
Year    = [2022; 2022; 2022; 2023; 2023; 2023];
Quarter = [1;    2;    3;    1;    2;    3];
GDP     = [1000; 1025; 1035; 1050; 1070; 1085];

% Put in a table
T = table(Year, Quarter, GDP);
disp('Original table:');
disp(T);

% ---- Construct datetime ----
month = (T.Quarter - 1) * 3 + 1;        % convert Q1,Q2,Q3,Q4 -> Jan, Apr, Jul, Oct
T.Time = datetime(T.Year, month, 1);    % pick 1st day of quarter

% ---- Convert to timetable ----
TT = table2timetable(T, 'RowTimes','Time');

disp('Converted timetable:');
disp(TT);


% If your table has numeric Year and Quarter columns:
month = (T.Quarter - 1) * 3 + 1;   % 1,4,7,10
T.Time = datetime(T.Year, month, 1);    % first day of quarter
TT = table2timetable(T, 'RowTimes','Time');

%----
%% Plotting
%----
clear; close; clc;
load('gdp_quarterly_clean.mat','TT');
whos TT

figure('Color','w');
plot(TT.Time, TT.GDP, '-o', 'LineWidth', 1.25);
grid on; box on;

xlabel('Time');
ylabel('GDP (billions)');
title('GDP Level — Quarterly');
legend({'GDP'}, 'Location','best');

figure('Color','w');
plot(TT.Time, TT.GDP, '--s', 'MarkerSize', 5, 'LineWidth', 1.25); 
grid on; box on;

xlabel('Time'); ylabel('GDP (billions)');
title('GDP Level — Style Demo');

% Axis limits and ticks (optional)
xlim([TT.Time(1) TT.Time(end)]);
%ylim([min(TT.GDP)*0.95, max(TT.GDP)*1.05]);

% Add a horizontal reference line (e.g. long-run mean)
hold on; yline(mean(TT.GDP,'omitnan'), ':', 'Mean GDP'); 
hold off;

% Option A: two panels (clear separation)
figure('Color','w');

subplot(2,1,1);
plot(TT.Time, TT.GDP, '-o', 'LineWidth', 1.2); grid on; box on;
ylabel('GDP (billions)'); title('GDP Level');

subplot(2,1,2);
plot(TT.Time, TT.GDP_yoy, '-s', 'LineWidth', 1.2); grid on; box on;
ylabel('YoY growth (%)'); xlabel('Time'); 
yline(0,':'); legend({'YoY'},'Location','best');

% Option B: dual y-axes (compact, but use carefully)
figure('Color','w');
yyaxis left
plot(TT.Time, TT.GDP, '-o', 'LineWidth', 1.2); ylabel('GDP (billions)');
yyaxis right
plot(TT.Time, TT.GDP_yoy, '-s', 'LineWidth', 1.2); ylabel('YoY growth (%)');
grid on; box on; xlabel('Time'); title('GDP: Level (LHS) and YoY (RHS)');
legend({'GDP','YoY'},'Location','best');


% Recession band placeholder (example dates)
t0 = datetime(2008,1,1); t1 = datetime(2009,6,1);

figure('Color','w');
plot(TT.Time, TT.GDP, 'LineWidth', 1.25); grid on; box on; hold on;

% Shade a time window with patch (behind the line)
yl = ylim;
patch([t0 t1 t1 t0], [yl(1) yl(1) yl(2) yl(2)], ...
        [0.9 0.9 0.9], 'EdgeColor','none', 'FaceAlpha',0.5);
uistack(findobj(gca,'Type','line'),'top'); % keep line on top

xlabel('Time'); ylabel('GDP (billions)');
title('GDP with Recession Band (Illustrative)');
hold off;

% Save outputs
saveas(gcf, 'week3_gdp_level.png');
savefig(gcf, 'week3_gdp_level.fig');