Last active
July 18, 2024 18:54
-
-
Save tcarreira/1fa10eef9044eb99481287c74600345d to your computer and use it in GitHub Desktop.
Get the euribor 6m rate for a given month (average of all days on a given month) - Go or Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
"io" | |
"net/http" | |
"time" | |
) | |
var ( | |
year = 2024 | |
month = 5 | |
) | |
const ( | |
dtFormat = "2006-01-02 (Mon)" | |
urlTemplate = "https://www.euribor-rates.eu/umbraco/api/euriborpageapi/highchartsdata?minticks=%d&maxticks=%d&series[0]=3" | |
) | |
type DailyRate struct { | |
timestamp int | |
rate float64 | |
} | |
func getMonthRange(year, month int) (fromTimestamp, toTimestamp int) { | |
firstDay := time.Date(year, time.Month(month), 1, 0, 0, 0, 0, time.UTC) | |
lastDay := firstDay.AddDate(0, 1, -1) | |
return int(firstDay.Unix() * 1000), int(lastDay.Unix() * 1000) | |
} | |
func fetchData(from, to int) (dr []DailyRate) { | |
url := fmt.Sprintf(urlTemplate, from, to) | |
client := &http.Client{} | |
req, err := http.NewRequest("GET", url, nil) | |
if err != nil { | |
fmt.Println("Error creating HTTP request:", err) | |
return | |
} | |
req.Header.Add("referer", "https://www.euribor-rates.eu/en/euribor-charts/") | |
req.Header.Add("sec-fetch-mode", "cors") | |
resp, err := client.Do(req) | |
if err != nil { | |
panic(fmt.Errorf("Failed to query remove API server: %w", err)) | |
} | |
defer resp.Body.Close() | |
if resp.StatusCode >= 400 { | |
panic(fmt.Errorf("Unexpected response from API server: statusCode=%d. %v", resp.StatusCode, resp)) | |
} | |
body, err := io.ReadAll(resp.Body) | |
if err != nil { | |
panic(fmt.Errorf("Could not read response body. %v", resp)) | |
} | |
data := []struct { | |
Data []interface{} | |
}{} | |
err = json.Unmarshal(body, &data) | |
if err != nil { | |
panic(fmt.Errorf("Unable to parse JSON response: %w\nbody= %v\nresponse: %v", err, string(body), resp)) | |
} | |
for _, pair := range data[0].Data { | |
pairSlice := pair.([]interface{}) | |
timestamp := int(pairSlice[0].(float64)) | |
rate := pairSlice[1].(float64) | |
dr = append(dr, DailyRate{timestamp: timestamp, rate: rate}) | |
} | |
return dr | |
} | |
func formatTimestamp(t int) string { | |
ts := time.Unix(int64(t/1000), 0) | |
ts = ts.UTC() | |
return ts.Format(dtFormat) | |
} | |
func main() { | |
from, to := getMonthRange(year, month) | |
data := fetchData(from, to) | |
rateSum := 0.0 | |
for _, dailyRate := range data { | |
fmt.Printf("%s: %.4f %%\n", formatTimestamp(dailyRate.timestamp), dailyRate.rate) | |
rateSum += dailyRate.rate | |
} | |
avg := rateSum / float64(len(data)) | |
fmt.Println() | |
fmt.Printf("average rate : %.5f %%\n", avg) | |
fmt.Printf("average rate (.3): %.3f %%\n", avg) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import calendar | |
from datetime import datetime, timezone | |
from typing import Tuple | |
from statistics import mean | |
import requests | |
year, month = 2024, 5 | |
def get_range(year: int, month: int) -> Tuple[int, int]: | |
"Return a (from,to) timestamps (ms) for a given year,month" | |
utc = timezone.utc | |
mr = calendar.monthrange(year, month) | |
first_day = datetime(year, month, 1, 0, 0, 0, 0, utc) | |
last_day = datetime(year, month, mr[1], 23, 59, 59, 0, utc) | |
first_t = datetime.timestamp(first_day) | |
last_t = datetime.timestamp(last_day) | |
return int(first_t) * 1000, int(last_t) * 1000 | |
from_t, to_t = get_range(year, month) | |
url = f"https://www.euribor-rates.eu/umbraco/api/euriborpageapi/highchartsdata?minticks={from_t}&maxticks={to_t}&series[0]=3" | |
r = requests.get(url, headers={ | |
"referer": "https://www.euribor-rates.eu/en/euribor-charts/", | |
"sec-fetch-mode": "cors", | |
}) | |
j = r.json() | |
rates = [] | |
for day_value in j[0]["Data"]: | |
day = datetime.fromtimestamp(day_value[0] / 1000, tz=timezone.utc).date() | |
dow = calendar.day_name[day.weekday()] | |
rate = day_value[1] | |
print(f"{day} ({dow[:3]}): {rate:.3f} %") | |
rates.append(rate) | |
print() | |
print(f"average rate : {mean(rates):.5f} %") | |
print(f"average rate (.3): {mean(rates):.3f} %") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment