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
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Author: Gertjan van den Burg
"""
import clevercsv
import json
import sys
def format_month(ymm):
year, month = ymm.split("M")
return f"{year}-{month}"
def main(input_filename, output_filename):
with open(input_filename, "r", newline="", encoding="ascii") as fp:
reader = clevercsv.DictReader(
fp, delimiter=",", quotechar='"', escapechar=""
)
rows = list(reader)
by_currency = {}
for row in rows:
cur = row["CURRENCY"]
if not cur in by_currency:
by_currency[cur] = []
by_currency[cur].append(row)
by_month = {}
for cur in by_currency:
for item in by_currency[cur]:
if item["Value"] == ":":
continue
month = item["TIME"]
if not month in by_month:
by_month[month] = {}
by_month[month][cur] = item
to_delete = []
for month in by_month:
if not len(by_month[month]) == 2:
to_delete.append(month)
for month in to_delete:
del by_month[month]
ratio = {}
for month in sorted(by_month.keys()):
usd = by_month[month]["US dollar"]
isk = by_month[month]["Icelandic krona"]
ratio[format_month(month)] = float(usd["Value"]) / float(isk["Value"])
tuples = [(m, ratio[m]) for m in ratio]
name = "usd_isk"
longname = "USD-ISK exhange rate"
data = {
"name": name,
"longname": longname,
"n_obs": len(tuples),
"n_dim": 1,
"time": {
"format": "%Y-%m",
"index": list(range(len(tuples))),
"raw": [t[0] for t in tuples],
},
"series": [
{
"label": "Exchange rate",
"type": "float",
"raw": [t[1] for t in tuples],
}
],
}
with open(output_filename, "w") as fp:
json.dump(data, fp, indent="\t")
if __name__ == "__main__":
main(sys.argv[1], sys.argv[2])
|