Chapter 2 of 9

The Ministry's open data

Goal. Understand what data we get from the Ministry and why we take the median.

The Italian Ministry of Enterprises and Made in Italy publishes the prices that filling stations report every day, and shows them in the Osservaprezzi Carburanti app. The app uses a web service queried with a POST request that names a point on the map (latitude and longitude) and a fuel type. The answer is a list of nearby stations, each with a name, a position, the date of its last update and its prices: for each fuel a price in euros per litre and an isSelf field saying whether it is a "self" or "served" price.

Our program keeps only the self-service petrol of stations around Arezzo: the service returns about forty, within roughly ten kilometres of the chosen point. One thing to remember: the service is not officially documented as an API, so its format may change (we come back to this in the FAQ).

Why the median

With forty prices we need one number. The mean is pulled by a mistake: if an operator types 2.399 instead of 1.899 by accident, the mean goes up. The median is the middle value when prices are lined up, and a single mistake does not move it.

Analogy. Line up five people from shortest to tallest: the median is the height of the one in the middle. If a giant joins at the end, the person in the middle is still the same.
const prices = [1.979, 1.989, 1.989, 1.999, 2.399];
const sorted = [...prices].sort((a, b) => a - b);
const median = sorted[Math.floor(sorted.length / 2)]; // 1.989

With an even number of prices you average the two middle values: the full program handles that.

The POL price in euros, needed in chapter 6, is read from a public quotation service (in the project, CoinGecko), once a day.

Try it

Change the numbers in the list: put in a huge typo (for example 9.999) and check that the median does not move while the mean does. You can do it in the browser console (F12 key, Console tab).

What you learned