Skip to main content

A Python client for Norwegian traffic data

Project description

PyTrafikk

A Python client and web application for accessing Norwegian traffic data from the Norwegian Public Roads Administration (Statens vegvesen).

Features

  • Query traffic registration points across Norway
  • Filter by road categories (European, National, County, Municipal, Private)
  • Interactive map view showing all measurement points
  • Time series analysis with:
    • Hourly and daily traffic volume data
    • Interactive plots
    • Date range selection
    • Station search

Installation

From PyPI (recommended)

pip install pytrafikk

From Source

# Clone the repository
git clone https://github.com/yourusername/pytrafikk.git
cd pytrafikk

# Create and activate a virtual environment
python -m venv .venv
source .venv/bin/activate  # On Windows: .venv\Scripts\activate

# Install the package and dependencies
pip install -e .

Usage

Web Application

Start the Flask development server:

flask --app pytrafikk.web.app run

Then open http://localhost:5000 in your browser to access:

  • Interactive map view at /map
  • Time series analysis at /timeseries

Python API

from pytrafikk.client import (
    query_traffic_registration_points,
    query_traffic_volume,
    query_traffic_volume_by_day
)

# API base URL
BASE_URL = "https://trafikkdata-api.atlas.vegvesen.no/"

# Get measurement points for different road categories
e_roads = query_traffic_registration_points(BASE_URL, "E")  # European highways
national = query_traffic_registration_points(BASE_URL, "R")  # National roads
county = query_traffic_registration_points(BASE_URL, "F")   # County roads

# Print some point details
for point in e_roads[:3]:
    print(f"Name: {point.name}")
    print(f"ID: {point.id}")
    print(f"Location: {point.location.coordinates.latLon.lat}, {point.location.coordinates.latLon.lon}\n")

# Query hourly traffic volume for yesterday
from datetime import datetime, timedelta
from zoneinfo import ZoneInfo

oslo_tz = ZoneInfo("Europe/Oslo")
yesterday = datetime.now(oslo_tz) - timedelta(days=1)
start_time = yesterday.replace(hour=0, minute=0, second=0, microsecond=0)
end_time = start_time + timedelta(days=1)

volumes = query_traffic_volume(
    BASE_URL,
    point_id="97411V72313",  # Example: E6 Mortenhals
    from_time=start_time.isoformat(),
    to_time=end_time.isoformat()
)

# Print hourly volumes
for volume in volumes.volumes:
    print(f"Time: {volume.from_time.strftime('%H:%M')} - {volume.to_time.strftime('%H:%M')}")
    print(f"Vehicles: {volume.total}")
    print(f"Coverage: {volume.coverage_percentage}%\n")

# Get daily traffic for the last week
week_start = start_time - timedelta(days=7)
daily = query_traffic_volume_by_day(
    BASE_URL,
    point_id="97411V72313",
    from_time=week_start.isoformat(),
    to_time=end_time.isoformat()
)

# Calculate average daily traffic
avg_traffic = sum(v.total for v in daily.volumes) / len(daily.volumes)
print(f"Average daily traffic: {avg_traffic:.0f} vehicles")

# Create a DataFrame with multiple points
from datetime import datetime, timedelta
from zoneinfo import ZoneInfo
import pandas as pd

# Get traffic for multiple points over the last 24 hours
points = ["97411V72313", "44592V2786964"]  # E6 Mortenhals and another point
oslo_tz = ZoneInfo("Europe/Oslo")
end = datetime.now(oslo_tz)
start = end - timedelta(days=1)

df = create_timeseries_df(
    BASE_URL,
    points,
    start.isoformat(),
    end.isoformat()
)

# The DataFrame uses nullable Int64 type for all columns
print("\nColumn types:")
print(df.dtypes)
# Output:
# 97411V72313      Int64
# 44592V2786964    Int64
# dtype: object

# Now you can use pandas operations on the DataFrame
print("\nHourly volumes for multiple points:")
print(df.head())

# Calculate daily totals (handles missing values automatically)
daily_totals = df.resample('D').sum()
print("\nDaily totals:")
print(daily_totals)

# Basic statistics (null values are properly handled)
print("\nSummary statistics:")
print(df.describe())

Development

Running Tests

Tests are written using pytest and can be run with:

pytest

Project Structure

pytrafikk/
├── __init__.py
├── client.py          # Core API client
├── explore.py         # Road category analysis tools
├── tests/
│   └── test_client.py # API client tests
└── web/              # Flask web application
    ├── app.py
    └── templates/
        ├── index.html
        ├── map.html
        └── timeseries.html

License

MIT License

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pytrafikk-0.1.1.tar.gz (12.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

pytrafikk-0.1.1-py3-none-any.whl (12.4 kB view details)

Uploaded Python 3

File details

Details for the file pytrafikk-0.1.1.tar.gz.

File metadata

  • Download URL: pytrafikk-0.1.1.tar.gz
  • Upload date:
  • Size: 12.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.0.1 CPython/3.12.4

File hashes

Hashes for pytrafikk-0.1.1.tar.gz
Algorithm Hash digest
SHA256 9e9537ba93e1809fc6e43dedf131f3a7edcba967677bdb15f39252260978e2dc
MD5 a439ed1bd790d45c028df28a0d9d42fb
BLAKE2b-256 9b490cbf6553d5d0538248bd52ff589b0c35e8b69ddcda59d042d7bb7a612cf1

See more details on using hashes here.

File details

Details for the file pytrafikk-0.1.1-py3-none-any.whl.

File metadata

  • Download URL: pytrafikk-0.1.1-py3-none-any.whl
  • Upload date:
  • Size: 12.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.0.1 CPython/3.12.4

File hashes

Hashes for pytrafikk-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 13046bfb74844891421b91908cadf145fb0a17e9f360c4e4c319d3caf16a1282
MD5 84f284883f55b10bcc8bc612605ee3d0
BLAKE2b-256 09a150e4fd481bf27320520e25323d4d78394e894c6e096d591e38ba79e89b35

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page