%% Week 1 Homework — Solution
% Goal:
% 1) Load Nominal GDP (current US$) and Real GDP (2015 US$) from CSV.
% 2) Compute GDP Deflator and inflation.
% 3) Compute growth rates for Nominal GDP, Real GDP, and Deflator (inflation).
% 4) Plot and save figures (PNG + .fig).

clear; close all; clc;

%% -------------------- Load data from CSV --------------------
csvName = 'wb_gdp_rgdp.csv';
% Load via CSV to demonstrate readtable pipeline
Tin = readtable(csvName);
years = Tin.Year;
ngdp  = Tin.NominalGDP_USD;
rgdp  = Tin.RealGDP_USD2015eq100;


%% -------------------- Compute GDP Deflator and Inflation --------------------
% Deflator is an index with 2015=100, so Deflator = Nominal / (RGDP/100)
defl = ngdp ./ (rgdp).*100;

% Inflation (GDP deflator-based), percent YoY:
% pi_t = 100 * (Deflator_t / Deflator_{t-1} - 1)
infl = 100 * (defl(2:end) ./ defl(1:end-1) - 1);

%% -------------------- Compute growth rate of RGDP (percent) --------------------

% Real GDP growth
g_rgdp = 100 * (rgdp(2:end) ./ rgdp(1:end-1) - 1);

% Align series for plotting growth (length N-1)
years_g = years(2:end);

%% -------------------- Plots: Levels --------------------
% Plot Nominal vs Real GDP (levels). Use billions for readability.
fig_levels = figure('Color','w');
plot(years, ngdp/1e9, '-o', 'LineWidth', 1.25); hold on;
plot(years, rgdp/1e9, '-s', 'LineWidth', 1.25);
grid on; box on;
xlabel('Year');
ylabel('Billions of US dollars');
ttl = 'Nominal vs Real GDP (2015 US$)';
title(ttl);
legend('Nominal GDP (current US$)','Real GDP (2015 US$)','Location','best');

% Save
saveas(fig_levels, 'gdp_levels.png');
savefig(fig_levels, 'gdp_levels.fig');

%% -------------------- Plots: Growth and Inflation --------------------
% Plot growth of Nominal & Real GDP
fig_growth = figure('Color','w');
plot(years_g, g_rgdp, '-s', 'LineWidth', 1.25);
grid on; box on;
xlabel('Year');
ylabel('Growth rate (%)');
ttl2 = 'Real GDP Growth';
title(ttl2);
legend('Real GDP growth','Location','best');

% Save
saveas(fig_growth, 'rgdp_growth.png');
savefig(fig_growth, 'rgdp_growth.fig');

% Plot inflation (GDP deflator YoY %)
fig_infl = figure('Color','w');
plot(years_g, infl, '-d', 'LineWidth', 1.25);
grid on; box on;
xlabel('Year');
ylabel('Inflation (%, GDP Deflator)');
ttl3 = 'Inflation (GDP Deflator, YoY %)';
title(ttl3);

% Save
saveas(fig_infl, 'inflation_deflator.png');
savefig(fig_infl, 'inflation_deflator.fig');

%% -------------------- Save workspace --------------------
save('week1_homework_workspace.mat', 'ngdp', 'defl', 'rgdp', 'infl', 'g_rgdp', 'years');

%% -------------------- Console summaries (optional) --------------------
fprintf('Years: %d–%d, N=%d\n', years(1), years(end), numel(years));
fprintf('Mean Nominal GDP (US$ bn): %.2f\n', mean(ngdp/1e9, 'omitnan'));
fprintf('Mean Real GDP (2015 US$ bn): %.2f\n', mean(rgdp/1e9, 'omitnan'));
fprintf('Mean inflation (deflator, %%): %.2f\n', mean(infl, 'omitnan'));