codinggames

How to calculate the annual inflation in Brazil using JavaScript

Written in May 13, 2021 - 🕒 2 min. read

Today I needed to know the accumulated inflation of the last year for Brazil for a project I am working on, information that can be easily accessed on the IBGE website, however, I needed this data in JSON or at least XML format.

Inflation
Inflation

Incredibly, just searching for ”API accumulated inflation 2021 brazil” did not return any useful results. I even tried ”how to calculate the accumulated inflation “javascript”” and nothing, which is why I’m writing this post.

The Central Bank of Brazil provides several end-points with data related to the Brazilian economy, but for a person who does not understand economics like myself, it is difficult to know which is the correct endpoint to get the correct data.

The Central Bank of Brazil has end-points in the format https://api.bcb.gov.br/dados/serie/bcdata.sgs.XXX/dados, in which XXX is the data reference code. First I found this end-point, which seemed to be correct, but the value of April 2021 is 0.05 and on the IBGE website the value is 0.31, which is not what I need.

After trying a few different codes that I found searching on Google, I found this end-point, in which the April 2021 value is 0.31. Yay!

It is possible to filter the results of this end-point using https://api.bcb.gov.br/dados/serie/bcdata.sgs.433/dados/ultimos/12?formato=json, which returns the values of the last 12 months.

Now we can use this data to calculate the accumulated inflation for the last year:

const fetchBacenData = async () => {
    const url = 'https://api.bcb.gov.br/dados/serie/bcdata.sgs.433/dados/ultimos/12?formato=json';
    const result = await fetch(url, {
        method: 'GET',
    }).then(async (response) => await response.text());

    return JSON.parse(result);
};

const data = await fetchBacenData();

To calculate the annual inflation we use the following formula: accumulated inflation = ((1 + previous monthly inflation) * (1 + current monthly inflation)) - 1 (provided by my great mathematician friend Leandro). And how do we accumulate data using JavaScript? By using reduce:

const inflation =
    data.reduce((acc, curr) => ((1 + parseFloat(acc)) * (1 + parseFloat(curr.valor) / 100)) - 1, 0);

This will give us 0.06759188526903293, which by rounding we get to the amount of 6,76%, just like it is on the IBGE website. Noice!

I hope the next person who Googles “API accumulated inflation 2021 brazil” find this post 😊

That’s all for today, cheers!

Tags:


Post a comment

Comments

No comments yet.