-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgir.js
More file actions
143 lines (125 loc) · 5.57 KB
/
gir.js
File metadata and controls
143 lines (125 loc) · 5.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
const axios = require('axios');
const cheerio = require('cheerio');
const fs = require('fs');
const path = require('path');
const Papa = require('papaparse');
const fetch = require('node-fetch');
const MAPBOX_API_KEY = 'pk.eyJ1IjoibmVwYXYiLCJhIjoiY2xtamU3ZzdsMDN1bzJxbm92OTY2NnpubSJ9.6ewU3v2rWTX7wa8DWMjn-g'; // Replace with your Mapbox API key
// Function to extract latest Global Inflation Rates and store them into CSV file
async function extractInterestRates() {
const url = 'https://www.global-rates.com/en/interest-rates/central-banks/central-banks.aspx';
try {
const response = await axios.get(url);
const $ = cheerio.load(response.data);
const selector = "#ctl00 > table.maintable > tbody > tr > td > table > tbody > tr:nth-child(2) > td:nth-child(2) > table:nth-child(6)";
const rows = $(selector).find('tr');
let csvData = 'Name of interest rate\tCountry/Region\tCurrent Rate\tDirection\tPrevious Rate\tChange\n';
rows.each((index, row) => {
if (index !== 0) { // Skip header row
const columns = $(row).find('td');
const rowData = columns.map((_, col) => {
let text = $(col).text().trim();
// Ensure only numerical values for current and previous rate columns
if (_ === 2 || _ === 4) {
text = text.replace(/[^0-9.]/g, ''); // Remove all non-numeric characters except for the decimal point
}
// Extract direction based on the icon
if (_ === 3) {
const hasUpIcon = $(col).find('img[src*="up.gif"]').length > 0;
const hasDownIcon = $(col).find('img[src*="down.gif"]').length > 0;
text = hasUpIcon ? 'Up' : hasDownIcon ? 'Down' : 'Neutral';
}
// Reformat date in the "Change" column
if (_ === 5) {
const dateParts = text.split('-');
if (dateParts.length === 3) {
text = `${dateParts[2]}-${dateParts[0].padStart(2, '0')}-${dateParts[1].padStart(2, '0')}`;
}
}
return text;
}).get();
csvData += rowData.join('\t') + '\n';
}
});
// Generate filename based on current date and time
const date = new Date();
const filename = `Global_Inflation_Rates_${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}_${date.getHours()}-${date.getMinutes()}-${date.getSeconds()}.csv`;
// Write data to CSV file
fs.writeFileSync(filename, csvData);
console.log(csvData);
console.log(`Data written to ${filename}`);
} catch (error) {
console.error('Error fetching or processing data:', error);
}
}
// Function to get the latest CSV file
function getLatestCSV() {
const files = fs.readdirSync('./'); // Assuming CSV files are in the root directory
const csvFiles = files.filter(file => file.startsWith('Global_Inflation_Rates_') && file.endsWith('.csv'));
csvFiles.sort((a, b) => fs.statSync(b).mtime.getTime() - fs.statSync(a).mtime.getTime());
return csvFiles[0] ? path.join('./', csvFiles[0]) : null;
}
// Function to parse the CSV data
function parseCSVData(file) {
const csvData = fs.readFileSync(file, 'utf8');
return Papa.parse(csvData, { header: true }).data;
}
// Given the country name retrieve conutrys longitude and latitude to be used on map (Mapbox)
async function geocodeCountry(countryName) {
try {
const response = await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${countryName}.json?access_token=${MAPBOX_API_KEY}`);
if (response.ok) {
const data = await response.json();
const feature = data.features[0];
if (feature) {
const { coordinates } = feature.geometry;
return {
latitude: coordinates[1],
longitude: coordinates[0]
};
}
}
} catch (error) {
console.error('Error geocoding country:', error);
}
return null;
}
// Convert DATA into GeoJSON format for displaying on the map (Mapbox)
async function convertToGeoJSON(data) {
const geoJsonData = {
type: 'FeatureCollection',
features: []
};
for (const row of data) {
const countryName = row['Country/Region'];
// Generate random two-digit numbers for currentRate and previousRate
const currentRate = Math.floor(Math.random() * 90 + 10) / 10; // Random float between 1.0 and 9.9
const previousRate = Math.floor(Math.random() * 90 + 10) / 10; // Random float between 1.0 and 9.9
// Use Mapbox Geocoding API to get latitude and longitude for the country
const geoData = await geocodeCountry(countryName);
if (geoData) {
const { latitude, longitude } = geoData;
const feature = {
type: 'Feature',
properties: {
country: countryName,
currentRate,
previousRate
},
geometry: {
type: 'Point',
coordinates: [longitude, latitude]
}
};
geoJsonData.features.push(feature);
}
}
console.log(JSON.stringify(geoJsonData));
return geoJsonData;
}
module.exports = {
extractInterestRates,
getLatestCSV,
convertToGeoJSON,
parseCSVData
};