%% 
clear all; close all; clc;

%% WORLD BANK: Annual Nominal GDP (current US$)
% Country: set ISO3 code (e.g., 'ITA', 'USA', 'FRA', 'DEU', 'GBR', 'ESP',
% 'PRT') for all countries 'all'
country = 'USA';

% Build API URL (per_page large to get full history, JSON format)
url = ['https://api.worldbank.org/v2/country/' country ...
       '/indicator/NY.GDP.MKTP.CD?format=json&per_page=20000'];

% Read JSON
raw = webread(url);           % raw is a 1x2 cell array: {metadata, data}
data = raw{2};                % second cell contains an array of structs

%  Preallocate memory for the data
countries = cell(length(data), 1);
values = cell(length(data), 1);
periods = cell(length(data), 1);
countries_code = cell(length(data), 1);


% Extract GDP values and years from the data
for i = 1:length(data)
    if isempty(data(i).value)              % GDP value
        values{i} = NaN;                   % Missing data = NaN
    else
    values{i} = data(i).value;        % Extract GDP values 
    end
    periods{i} = data(i).date;     % Extract corresponding years (strings)
    countries{i} = data(i).country.value;  % Country name
    countries_code{i} = data(i).countryiso3code;  % Country name
end

years=str2double(periods); %convert periods to numerical values
gdpValues=cell2mat(values); %convert values to numerical values

%Optional: save data in a table
gdpTable = table(countries', countries_code', years', gdpValues', ...
    'VariableNames', {'country', 'ccode' 'years', 'value'});

% Plot (levels)
figure;
plot(years, gdpValues./1e9, '-o', 'LineWidth', 1.25); grid on;
xlabel('Year'); ylabel('GDP (current US$, billions)');
title(['Nominal GDP (World Bank) — ' country]);

%Sort both series from oldest to newest year
WB_years = flip(years); WB_gdp = flip(gdpValues);  
% Save for challenge week 1
save('wb_nominal_gdp.mat', 'WB_years', 'WB_gdp', 'country');

%% Add Real GDP

%% ----------- Real GDP  (Index, 2015=100) -----------
url_rgdp = ['https://api.worldbank.org/v2/country/' country ...
            '/indicator/NY.GDP.MKTP.KD?format=json&per_page=20000'];

raw_rgdp = webread(url_rgdp);
data_rgdp = raw_rgdp{2};

%  Preallocate memory for the data
countries_rgdp = cell(length(data_rgdp), 1);
values_rgdp = cell(length(data_rgdp), 1);
periods_rgdp = cell(length(data_rgdp), 1);
countries_code_rgdp = cell(length(data_rgdp), 1);

% Extract Real GDP values and years from the data
for i = 1:length(data_rgdp)
    if isempty(data_rgdp(i).value)              % GDP value
        values_rgdp{i} = NaN;                   % Missing data = NaN
    else        
    values_rgdp{i} = data_rgdp(i).value;        % Extract GDP values 
    end
    periods_rgdp{i} = data_rgdp(i).date;     % Extract corresponding years (strings)
    countries_rgdp{i} = data_rgdp(i).country.value;  % Country name
    countries_code_rgdp{i} = data_rgdp(i).countryiso3code;  % Country name
end


WB_years_rgdp=flip(str2double(periods_rgdp)); %convert periods to numerical values and sort them from oldest to newest
WB_rgdp=flip(cell2mat(values_rgdp)); %convert values to numerical values and sort them from oldest to newest


figure;
plot(WB_years_rgdp, WB_rgdp./1e9, '-o', 'LineWidth', 1.25); grid on;
xlabel('Year'); ylabel('GDP  (2015 US$, billions)');
title(['Real GDP (World Bank) — ' country]);

%save in CVS
csvName = 'wb_gdp_rgdp.csv';
T = table(WB_years, WB_gdp, WB_rgdp, 'VariableNames', {'Year','NominalGDP_USD','RealGDP_USD2015eq100'});
writetable(T, csvName);