Chapter 2 of 9
The Ministry's open data
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.
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
prices: five sample prices in euros per litre. The last one, 2.399, is a typo.sorted: the same list in ascending order (the copy[...prices]leaves the original untouched).sorted.length / 2: with five values this is 2.5 andMath.floorturns it into 2, the third place (counting starts at zero).- The result is 1.989. The mean of the same values would be about 2.07, dragged up by the typo.
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
- The Ministry publishes station prices with a date and a self/served distinction.
- We use self-service petrol from stations around Arezzo, about forty.
- The median resists a single mistake better than the mean.