-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCurrencyConversion.py
616 lines (526 loc) · 14 KB
/
CurrencyConversion.py
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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
# pylint: disable=invalid-name
"""
A program that converts user input value from one currency into another into a
`JSON` file. It takes the following arguments:
- --date=YYYY-MM-DD / -d=YYYY-MM-DD
An extra feature: you can use `now` instead of YYYY-MM-DD if you want today's
values. Check the repository-level README.md file for more information.
"""
###############################################################################
# Imports
###############################################################################
import sys
from os import path
from datetime import datetime
from argparse import ArgumentParser
from typing import NoReturn, TypeAlias, TypedDict
import math
import json
import requests
from requests.models import Response
###############################################################################
# Constants
###############################################################################
ISO_4217_CURRENCY_CODES: set = {
"AED",
"AFN",
"ALL",
"AMD",
"ANG",
"AOA",
"ARS",
"AUD",
"AWG",
"AZN",
"BAM",
"BBD",
"BDT",
"BGN",
"BHD",
"BIF",
"BMD",
"BND",
"BOB",
"BOV",
"BRL",
"BSD",
"BTN",
"BWP",
"BYN",
"BZD",
"CAD",
"CDF",
"CHE",
"CHF",
"CHW",
"CLF",
"CLP",
"CNY",
"COP",
"COU",
"CRC",
"CUC",
"CUP",
"CVE",
"CZK",
"DJF",
"DKK",
"DOP",
"DZD",
"EGP",
"ERN",
"ETB",
"EUR",
"FJD",
"FKP",
"FOK",
"GBP",
"GEL",
"GGP",
"GHS",
"GIP",
"GMD",
"GNF",
"GTQ",
"GYD",
"HKD",
"HNL",
"HRK",
"HTG",
"HUF",
"IDR",
"ILS",
"IMP",
"INR",
"IQD",
"IRR",
"ISK",
"JEP",
"JMD",
"JOD",
"JPY",
"KES",
"KGS",
"KHR",
"KID",
"KMF",
"KRW",
"KWD",
"KYD",
"KZT",
"LAK",
"LBP",
"LKR",
"LRD",
"LSL",
"LYD",
"MAD",
"MDL",
"MGA",
"MKD",
"MMK",
"MNT",
"MOP",
"MRU",
"MUR",
"MVR",
"MWK",
"MXN",
"MXV",
"MYR",
"MZN",
"NAD",
"NGN",
"NIO",
"NOK",
"NPR",
"NZD",
"OMR",
"PAB",
"PEN",
"PGK",
"PHP",
"PKR",
"PLN",
"PYG",
"QAR",
"RON",
"RSD",
"RUB",
"RWF",
"SAR",
"SBD",
"SCR",
"SDG",
"SEK",
"SGD",
"SHP",
"SLE",
"SLL",
"SOS",
"SRD",
"SSP",
"STN",
"SVC",
"SYP",
"SZL",
"THB",
"TJS",
"TMT",
"TND",
"TOP",
"TRY",
"TTD",
"TVD",
"TWD",
"TZS",
"UAH",
"UGX",
"USD",
"USN",
"UYI",
"UYU",
"UYW",
"UZS",
"VED",
"VES",
"VND",
"VUV",
"WST",
"XAF",
"XAG",
"XAU",
"XBA",
"XBB",
"XBC",
"XBD",
"XCD",
"XDR",
"XOF",
"XPD",
"XPF",
"XPT",
"XSU",
"XTS",
"XUA",
"XXX",
"YER",
"ZAR",
"ZMW",
"ZWL",
}
PREMATURE_EXIT: str = (
"\n"
+ "Type out 'end' instead of forcing an exit because the program "
+ "won't write it's output otherwise!"
)
SCRIPT_PATH: str = path.dirname(path.abspath(__file__))
###############################################################################
# Types/Classes
###############################################################################
class HistoricalFastForexResponseJSON(TypedDict):
r"""This is an example of a historically fetched response JSON
```json
{
"date":"2024-06-08",
"base":"BGN",
"results": {
"EUR":0.51633
},
"ms":2
}
```
This program makes use of the Self["results"][`output_currency`] value.
where the `output_currency` variable varies based on the user input.
"""
date: str
base: str
results: dict[str, float]
ms: int
class OutputJSONFormat(TypedDict):
r"""The output file format class which is used in a list with the
dictionaries with the following JSON format:
```json
[
{
"date": "2024-06-08",
"amount": 1.0,
"base_currency": "EUR",
"target_currency": "BGN",
"converted_amount": 1.93
},
{
"date": "2024-06-08",
"amount": 3216532.0,
"base_currency": "USD",
"target_currency": "JPY",
"converted_amount": 504205543.74
}
]
"""
date: str
amount: float
base_currency: str
target_currency: str
converted_amount: float
OutputJSON: TypeAlias = list[OutputJSONFormat]
###############################################################################
# Fucntions
###############################################################################
def save_and_exit(output: OutputJSON) -> NoReturn:
r"""Handles writing the stored OutputJSON to the output directory. By default
in 'output/conversions.json' but the file name can be changed.
:param output: The program's output file JSON data.
:rtype: typing.NoReturn
"""
output_file_path = path.join(SCRIPT_PATH, "output/conversions.json")
choice: str = ""
while True:
if path.exists(output_file_path):
print(
f"Filename {output_file_path} already exists.\n",
"Do you want to write to another file in 'output/'? y/n: ",
end="",
sep="",
)
choice = input()
if choice.lower() == "y":
output_file_name: str = input("Enter your custom output file name: output/")
output_file_path: str = path.join(SCRIPT_PATH, "output", output_file_name)
if path.exists(output_file_path):
continue
break
print(
"Do you want to: \n",
"(1). override your existing file\n",
f"(2). exit without saving to {output_file_path}?\n",
"Default = None: ",
end="",
sep="",
)
choice: str = input()
if choice == "1":
break
if choice == "2":
sys.exit(0)
print("Please make a valid choice.")
with open(output_file_path, "w", encoding="utf-8") as output_file:
json.dump(
obj=output,
fp=output_file,
ensure_ascii=False,
indent=2,
)
print("Gracefully exiting...")
sys.exit(0)
def parse_yyyy_mm_dd(date: datetime) -> str:
r"""Handles the parsing of the trailing zeroes in the month and dates.
:param yyyy_mm_dd: The program's date argument in the form of datetime.
YYYY-MM-DD format.
:rtype: str
"""
parsed_month: str = str(date.month)
if date.month < 10:
parsed_month = "0" + parsed_month
parsed_day: str = str(date.day)
if date.day < 10:
parsed_day = "0" + parsed_day
return "-".join((str(date.year), parsed_month, parsed_day))
def parse_time(yyyy_mm_dd: str) -> str:
r"""Handles the parsing of the entire date as well as verifying it's between
2015 and now.
:param yyyy_mm_dd: The program's raw date argument. YYYY-MM-DD format.
:rtype: str
"""
if yyyy_mm_dd.lower() == "now":
return parse_yyyy_mm_dd(datetime.now())
separated_yyyy_mm_dd = yyyy_mm_dd.split("-")
date: datetime
if len(separated_yyyy_mm_dd) != 3:
print("Please make sure to specify a --date / -d flag.")
sys.exit(1)
try:
date: datetime = datetime(
year=int(separated_yyyy_mm_dd[0]),
month=int(separated_yyyy_mm_dd[1]),
day=int(separated_yyyy_mm_dd[2]),
)
if date.year < 2015:
print("There's no data for anything before 2015-01-01.")
sys.exit(1)
elif date > datetime.now():
print(
"This program doesn't have the capabilities to forsee future currency",
"values... yet.",
)
sys.exit(1)
except ValueError:
print("Please make sure your YYYY-MM-DD format only uses integer values.")
sys.exit(1)
return parse_yyyy_mm_dd(date)
def input_currency_value(prompt: str, output: OutputJSON) -> float:
r"""Handles user input with parsing from int to float and enforcing 2 decimal
points.
:param prompt: The looping user prompt.
:param output: The program's output file JSON data.
:rtype: float
"""
value_error = (
"Please enter an integer or a decimal value with up to 2 floating points."
)
while True:
amount: str = input(prompt)
if not amount:
print(value_error)
continue
if amount.lower() == "end":
save_and_exit(output=output)
try:
split = amount.split(".")
if len(split) == 2 and len(split[1]) > 2:
print(value_error)
continue
return float(amount)
except ValueError:
try:
return float(amount + ".0")
except ValueError:
print(value_error)
continue
def input_currency_type(prompt: str, output: OutputJSON) -> str:
r"""Utility function used for prompting the user for their 3 digit currency
input currency type which is ISO 4217 compliant.
:param prompt: The looping user prompt.
:param output: The program's output file JSON data.
:rtype: str
"""
while True:
currency: str = input(prompt)
currency = currency.upper()
if not currency:
print("Please enter the 3 digit code of your target currency.")
continue
if currency.lower() == "end":
save_and_exit(output)
if currency not in ISO_4217_CURRENCY_CODES:
print("Please enter an ISO 4217 compliant currency code.")
print(
"https://en.wikipedia.org/wiki/ISO_4217#List_of_ISO_4217_currency_codes"
)
continue
break
return currency
def program_loop(
fastforex_api_key: str,
date: str,
cached_conversions: dict[tuple[str, str], float],
output: OutputJSON,
) -> None:
r"""Main program loop which sends and caches the required information from API
requests to [fastforex](https://www.fastforex.io/).
:param fast_forex_api_key: The finance API endpoint key.
:param date: The program's date argument. YYYY-MM-DD format.
:param cached_conversions: A dictionary that's used to reduce the amount of
API calls.
:param output: The program's output file JSON data.
:rtype: None
"""
print("Type 'end' at any time to gracefully exit the program.")
amount: float = input_currency_value(prompt="Enter amount: ", output=output)
from_currency: str = input_currency_type(
prompt="Enter input currency: ", output=output
)
to_currency: str = input_currency_type(
prompt="Enter target currency: ", output=output
)
if (from_currency, to_currency) in cached_conversions:
print("Adding from cache...")
converted_amount: float = (
amount * cached_conversions[(from_currency, to_currency)]
)
output.append(
{
"date": date,
"amount": amount,
"base_currency": from_currency,
"target_currency": to_currency,
"converted_amount": converted_amount,
}
)
print(output[-1])
return None
fastforex_request_url: str = (
f"https://api.fastforex.io/historical?date={date}"
+ f"&from={from_currency}&to={to_currency}&api_key={fastforex_api_key}"
)
headers = {"accept": "application/json"}
response: Response = requests.get(
fastforex_request_url, headers=headers, timeout=10
)
if response.status_code != 200:
print("API response failed.")
print(response)
return None
response_json: HistoricalFastForexResponseJSON = response.json()
converted_amount: float = amount * response_json["results"][to_currency]
# Rounding down to the floor because it's finance.
converted_amount = math.floor(converted_amount * 100) / 100
converted_amount = float(str(f"{converted_amount:.2f}"))
print(f"Converted amount: {converted_amount}")
cached_conversions[(from_currency, to_currency)] = converted_amount
print(response_json)
output.append(
{
"date": date,
"amount": amount,
"base_currency": from_currency,
"target_currency": to_currency,
"converted_amount": converted_amount,
}
)
print(output[-1])
return None
###############################################################################
# Main
###############################################################################
def main(date: str) -> None:
r"""Other than the argument parsing, the main function here is also responsible
for storing the cache and the entire OutputJSON file.
:rtype: None
"""
config: dict[str, str]
with open(
path.join(SCRIPT_PATH, "config.json"), "r", encoding="utf-8"
) as config_file:
config = json.load(config_file)
fastforex_api_key: str = config["fast_forex_api_key"]
# print(f"{fastforex_api_key}")
cached_conversions: dict[tuple[str, str], float] = {}
output: OutputJSON = OutputJSON([])
while True:
program_loop(fastforex_api_key, date, cached_conversions, output)
if __name__ == "__main__":
parser = ArgumentParser(
prog="CurrencyConversion.py",
description="Converts user input value from one currency into another into a JSON file.",
)
parser.add_argument(
"--date",
"-d",
type=str,
default="",
required=True,
help=(
"The date format is YYYY-MM-DD. You can also use 'now' as a shorthand for the current"
+ " system day."
),
)
args = parser.parse_args()
try:
main(date=parse_time(args.date))
except KeyboardInterrupt:
print(PREMATURE_EXIT)
sys.exit(1)
except EOFError:
print(PREMATURE_EXIT)
sys.exit(1)