Skip to content

Commit

Permalink
Blackened formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
vthorsteinsson committed May 3, 2024
1 parent 62fecea commit eb518c6
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 46 deletions.
15 changes: 15 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Run vis.py",
"type": "debugpy",
"request": "launch",
"program": "vis.py",
"console": "integratedTerminal"
}
]
}
Empty file added .vscode/settings.json
Empty file.
80 changes: 34 additions & 46 deletions vis.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,58 +3,43 @@
import typing as t
import datetime

URL_VNV = "http://px.hagstofa.is/pxis/api/v1/is/Efnahagur/visitolur/1_vnv/1_vnv/VIS01000.px"
URL_VNV = (
"http://px.hagstofa.is/pxis/api/v1/is/Efnahagur/visitolur/1_vnv/1_vnv/VIS01000.px"
)
URL_VH = "https://talnaefni.fasteignaskra.is/talnaefni/v1/ibudavisitala"
BODY_VNV = {
"query": [
{
"code": "Vísitala",
"selection": {
"filter": "item",
"values": [
"CPI"
]
}
},
{
"code": "Liður",
"selection": {
"filter": "item",
"values": [
"index"
]
}
}
{"code": "Vísitala", "selection": {"filter": "item", "values": ["CPI"]}},
{"code": "Liður", "selection": {"filter": "item", "values": ["index"]}},
],
"response": {
"format": "json"
}
"response": {"format": "json"},
}


def visitala_neysluverds() -> t.Dict[str, float]:
""" Gets latest consumer price index for Statistics of Iceland """
"""Gets latest consumer price index for Statistics of Iceland"""

r = requests.post(URL_VNV, json=BODY_VNV)
json_response = json.loads(r.content)

vnv: t.Dict[str, float] = dict()
for row in json_response['data']:
month = row['key'][0].replace("M", "-")
vnv[month] = float(row['values'][0])
for row in json_response["data"]:
month = row["key"][0].replace("M", "-")
vnv[month] = float(row["values"][0])

return vnv


def visitala_ibudaverds() -> t.Dict[str, float]:
""" Gets latest property price index for all properties in the capital region. """
"""Gets latest property price index for all properties in the capital region."""

r = requests.get(URL_VH)
json_response = json.loads(r.content)

vh: t.Dict[str, float] = dict()
for row in json_response:
month = f"{row['Ar']}-{str(row['Manudur']).rjust(2, '0')}"
vh[month] = float(row['Vst_heild'])
month = f"{row['Ar']}-{str(row['Manudur']).rjust(2, '0')}"
vh[month] = float(row["Vst_heild"])

return vh

Expand All @@ -64,13 +49,12 @@ def months_between(d1: datetime.date, d2: datetime.date) -> int:


def check_data(data: t.Dict[str, float], origin: datetime.date) -> None:
""" Checks if the data is within expected length raises Exception if errors are found. """
"""Checks if the data is within expected length raises Exception if errors are found."""

latest_date = datetime.datetime.strptime(
f"{list(data.keys())[-1]}-01", "%Y-%m-%d"
).date()

latest_date = (
datetime.datetime
.strptime(f"{list(data.keys())[-1]}-01", '%Y-%m-%d')
.date())

if datetime.date.today() - datetime.timedelta(days=90) > latest_date:
raise ValueError("Latest date is not within boundaries")

Expand All @@ -79,21 +63,25 @@ def check_data(data: t.Dict[str, float], origin: datetime.date) -> None:


def main() -> int:
""" Constructs vis.js accoring to the original format of the file """
"""Constructs vis.js accoring to the original format of the file"""

vnv = visitala_neysluverds()
vh = visitala_ibudaverds()

# Simple data checks to make sure not to break
# Simple data checks to make sure not to break
# the website if data is missing.
check_data(vnv, datetime.date(1988, 5, 1))
check_data(vh, datetime.date(1994, 1, 1))

with open("vis.js", 'w', encoding='utf-8') as f:
with open("vis.js", "w", encoding="utf-8") as f:

f.writelines("// Vísitölur húsnæðisverðs og neysluverðs\n")
f.writelines("// Sjá https://fasteignaskra.is/gogn/fasteignagattin/fasteignavidskipti/visitolur-ibuda-og-leiguverds/\n")
f.writelines("// og https://hagstofa.is/talnaefni/efnahagur/verdlag/visitala-neysluverds/\n\n")
f.writelines(
"// Sjá https://fasteignaskra.is/gogn/fasteignagattin/fasteignavidskipti/visitolur-ibuda-og-leiguverds/\n"
)
f.writelines(
"// og https://hagstofa.is/talnaefni/efnahagur/verdlag/visitala-neysluverds/\n\n"
)

f.writelines("var vis = {\n")
for key, vnv_value in vnv.items():
Expand All @@ -104,16 +92,16 @@ def main() -> int:
# Before 1994, there are only records available for vnv
if int(key[:4]) >= 1994 and not vh_value:
continue
f.writelines(f"\"{key}\" : {{ vnv: {vnv_value}")

f.writelines(f'"{key}" : {{ vnv: {vnv_value}')
if vh_value:
f.writelines(f", vh: {vh_value}")
f.writelines(" },\n")

f.writelines("};")

return 0


if __name__ == '__main__':
exit(main())

if __name__ == "__main__":
exit(main())

0 comments on commit eb518c6

Please sign in to comment.