Skip to main content

03 - Telematics for Insurance: A UBI Data Pipeline at Scale

Detect braking without inventing it, cut data into trips, fit a score that explains claims and keep location data under control under the GDPR.

What do you think about this article?

At a Glance

Detect braking without inventing it, cut data into trips, fit a score that explains claims and keep location data under control under the GDPR.

Telematics pipeline: from driving data to premium, with privacy built in

Usage-based insurance (UBI) prices the contract on how you actually drive: braking, speed, time of day. For a developer the problem is not "big data" but a chain of four steps, each of which can silently skew the result: reading a noisy signal without inventing events, cutting the stream into trips, turning trips into a score that explains claims, and doing it without accumulating more personal data than you need. Here we walk through them one by one with synthetic data that was actually run, and at the most delicate point (location) we lean on the guidelines of the European Data Protection Board.

You will not find figures on the telematics market or on average discounts: I could not check them against a primary source, so I do not print them. What you get is measured mechanism. The link upstream is policy administration (Cloud-native policy management); downstream, the score feeds into risk assessment (AI underwriting).

Where the data comes from

There are four sources, and they differ in what they measure and who controls them. The choice has consequences for the data model before it has consequences for cost.

SourceWhat it providesMain limit
Dongle on the OBD-II portSpeed and engine parameters from the vehicleDoes not know the speed limit of the road section; resolution of the values to be checked on the device
Smartphone appLocation and accelerometerCannot tell driver from passenger; depends on the operating system
Installed black boxLocation, accelerations and vehicle dataHardware installation and management
Manufacturer APINative vehicle dataDepends on agreements with the manufacturer

The most useful part for your work is the last column: signal quality is not an abstract property of "telematics data" but of the device, and the rest of the pipeline has to be aware of it. In the next section you will see a case where the resolution of a single reading decides whether an event exists.

Detecting a hard braking event without inventing it

The typical threshold for hard braking is a deceleration of about 3 m/s² (0.3 g, where g is 9.81 m/s²). It is derived from speed: change in speed divided by the time between two samples. If speed is a whole-number reading in km/h sampled at 10 Hz, a single 1 km/h step in 0.1 s is worth 2.78 m/s², almost the threshold; two adjacent steps exceed it. Quantization noise therefore produces hard-braking events that never happened.

The listing builds a synthetic 120 s trip with two real braking events (4 m/s² for 2 s), rounds speed to whole km/h (an assumption of this experiment: check the resolution of your own device) and counts events with three different windows. The count_events function groups consecutive samples below the threshold into a single event, because a braking lasts many samples and must be counted once. The last line repeats the calculation on the unrounded data, as a control.

Python: the same trip, 18 events or 2 depending on how you compute it
import numpy as np

HZ = 10                    # samples per second (assumed)
THRESHOLD = -3.0           # m/s^2, about 0.3 g
KMH_PER_MS = 3.6

# Synthetic 120 s trip: cruising at 50 km/h with a gentle oscillation and
# two real braking events (4 m/s^2 for 2 s, from 50 to about 21 km/h), followed by a gentle pickup.
t = np.arange(0, 120, 1 / HZ)
speed = 50 + 1.5 * np.sin(t / 7.0)
for start in (30, 80):
    drop = 4.0 * KMH_PER_MS                         # 14.4 km/h lost per second
    for i, ts in enumerate(t):
        dt = ts - start
        if 0 <= dt < 2:                             # braking
            speed[i] -= drop * dt
        elif 2 <= dt < 7:                           # holding the low speed
            speed[i] -= drop * 2
        elif 7 <= dt < 12:                          # gentle pickup (about 1.6 m/s^2)
            speed[i] -= drop * 2 * (12 - dt) / 5

reading = np.round(speed)                           # the device reads whole km/h

def count_events(kmh, window_s):
    """Events = consecutive groups of samples with deceleration below the threshold."""
    step = max(1, int(round(window_s * HZ)))
    v = kmh / KMH_PER_MS
    acc = (v[step:] - v[:-step]) / (step / HZ)
    below = acc <= THRESHOLD
    starts = np.sum(below[1:] & ~below[:-1]) + (1 if below[0] else 0)
    return int(starts), float(acc.min())

print("real braking events inserted: 2 (4.0 m/s^2 for 2 s)")
for label, kmh, window in [
    ("whole-number readings, adjacent samples (0.1 s)", reading, 0.1),
    ("whole-number readings, 0.5 s window", reading, 0.5),
    ("whole-number readings, 1.0 s window", reading, 1.0),
    ("unrounded, adjacent samples", speed, 0.1),
]:
    n, amin = count_events(kmh, window)
    print(f"{label:50s} events {n:2d}  max deceleration {amin:6.2f} m/s^2")

# Output:
# real braking events inserted: 2 (4.0 m/s^2 for 2 s)
# whole-number readings, adjacent samples (0.1 s)    events 18  max deceleration  -5.56 m/s^2
# whole-number readings, 0.5 s window                events  2  max deceleration  -4.44 m/s^2
# whole-number readings, 1.0 s window                events  2  max deceleration  -4.17 m/s^2
# unrounded, adjacent samples                        events  2  max deceleration  -4.02 m/s^2

With adjacent samples on the whole-number data the detector finds 18 events and a "maximum deceleration" of 5.56 m/s² (two steps in 0.1 s); with a 0.5 s or a 1 s window it finds 2, the real ones, with maximum deceleration of 4.44 and 4.17 m/s² respectively. On the unrounded data two events are found even with adjacent samples. The lesson is practical: compute acceleration over a window longer than the signal resolution, and store the window used together with the event, otherwise two fleets with different devices are not comparable. The trade-off: a long window also dampens real braking (4.17 against the 4.0 we started from) and can hide very brief events.

From points to trips: the session window

A trip has no reliable start event: the car stops at a traffic light, in a queue, at a short stop. The simplest rule is the session window: points belong to the same trip as long as the gap between two readings does not exceed a fixed interval, here 5 minutes. It is the same idea as in Apache Flink, whose documentation defines the session window as a window that closes when it receives no elements for a certain time.

The sessionize function walks the points in time order, opens a new group when the gap exceeds GAP, computes distance by adding up the distances between consecutive points with the haversine formula (haversine_km) and discards groups below MIN_KM. The test stream has four pieces: a trip with a three-minute stop in the middle (it stays a single trip), a 37-minute silence, a second trip and a very short trip.

Python: sessionization by time gap and distance with Haversine
from datetime import datetime, timedelta
from math import asin, cos, radians, sin, sqrt

GAP = timedelta(minutes=5)       # silence gap that closes a trip
MIN_KM = 0.5                     # below this distance the trip is discarded

def haversine_km(lat1, lon1, lat2, lon2):
    r = 6371.0088                # mean Earth radius in km
    p1, p2 = radians(lat1), radians(lat2)
    a = sin((p2 - p1) / 2) ** 2 + cos(p1) * cos(p2) * sin(radians(lon2 - lon1) / 2) ** 2
    return 2 * r * asin(sqrt(a))

def sessionize(points):
    """points: list of (UTC datetime, lat, lon) sorted by time -> list of trips."""
    sessions, current = [], []
    for p in points:
        if current and p[0] - current[-1][0] > GAP:
            sessions.append(current)
            current = []
        current.append(p)
    if current:
        sessions.append(current)
    trips = []
    for s in sessions:
        km = sum(haversine_km(a[1], a[2], b[1], b[2]) for a, b in zip(s, s[1:]))
        if km >= MIN_KM:
            trips.append({"start": s[0][0].isoformat(), "end": s[-1][0].isoformat(),
                          "points": len(s), "km": round(km, 2)})
    return trips

def drive(t0, minutes, lat, lon, dlat_per_min, step_s=30):
    """Points every step_s seconds along a straight line (synthetic data)."""
    pts = []
    for k in range(int(minutes * 60 / step_s) + 1):
        pts.append((t0 + timedelta(seconds=k * step_s), lat + dlat_per_min * k * step_s / 60, lon))
    return pts

t0 = datetime(2026, 3, 2, 8, 0, 0)
stream = (
    drive(t0, 10, 40.35, 18.17, 0.01)                                   # trip 1, part A
    + drive(t0 + timedelta(minutes=13), 10, 40.45, 18.17, 0.01)         # 3 min stop: same trip
    + drive(t0 + timedelta(minutes=60), 8, 40.55, 18.17, 0.008)         # 37 min of silence: trip 2
    + drive(t0 + timedelta(minutes=100), 1, 40.60, 18.17, 0.001)        # very short trip: discarded
)
for trip in sessionize(stream):
    print(trip)
print("input points:", len(stream))

# Output:
# {'start': '2026-03-02T08:00:00', 'end': '2026-03-02T08:23:00', 'points': 42, 'km': 22.24}
# {'start': '2026-03-02T09:00:00', 'end': '2026-03-02T09:08:00', 'points': 17, 'km': 7.12}
# input points: 62

The output has two trips: the first with 42 points and 22.24 km (the three-minute stop does not split it), the second with 17 points and 7.12 km; the 37-minute silence separates them, and the trip of about 110 metres was discarded. The limit of the method: a long stop inside a real trip (a half-hour break) splits the trip in two, and a garage without signal can do the same for no reason. The 5-minute value is a choice to calibrate on your own data. In production the same logic runs in a stream processing engine; the PyFlink form is the following, and it has to be adapted to your project:

PyFlink: session window per policy (schema to adapt)
# Schema to adapt: not executed (PyFlink is not installed in the test environment).
# Form taken from the Apache Flink documentation on session windows.
trips = (
    readings                                   # DataStream with timestamps and watermarks already assigned
    .key_by(lambda r: r["policy_ref"])         # one session per policy (or per device)
    .window(EventTimeSessionWindows.with_gap(Time.minutes(5)))
    .process(TripWindowFunction())             # your ProcessWindowFunction: distance, events, duration
)

This is a schema to adapt, not executed: I do not have PyFlink in the test environment. The form EventTimeSessionWindows.with_gap(Time.minutes(...)) is the one shown in the Flink documentation on windows; the imports, the window function and the configuration of watermarks and parallelism depend on the version. The advantage over the Python listing is that Flink handles late and out-of-order data for you, which do not exist in the listing because the points are already sorted.

From behaviour to premium: a model that explains claims

This is where the most common mistake is made: choosing the weights by hand ("braking 30%, speed 25%, night 15%") and calling the result a score. The score has to be tied to claims, otherwise you are assigning discounts and surcharges without knowing whether they really separate good drivers from bad ones. The standard actuarial method for frequency is a Poisson regression with a log link: the number of claims per policy-year depends on the exponential of a linear combination of the variables, and exp(coefficient) is the relativity, the factor by which frequency is multiplied for each additional standard deviation. Exposure (the fraction of the year during which the policy was observed) enters as a weight.

The listing generates 40,000 synthetic contracts with three behavioural variables and a known true effect, estimates the GLM with scikit-learn's PoissonRegressor (target = claims / exposure, weight = exposure) and compares the coefficients with the truth. Then it turns the predicted frequency into a premium factor with a floor at 0.70 and a cap at 1.50, and rebalances: after clipping the weighted mean is no longer 1, and without the divisor the portfolio would collect less than it should. Finally it compares the GLM score with the hand-weighted one, looking at claims per year in the worst and in the best decile.

Python: Poisson GLM on driving data, with factor clipping and comparison
import numpy as np
from sklearn.linear_model import PoissonRegressor

rng = np.random.default_rng(6440)
N = 40_000
FEATURES = ["braking_100km", "speeding_100km", "night_share"]

# --- SYNTHETIC data: the true world is known, so we can check the model. ---
braking = rng.lognormal(mean=0.6, sigma=0.35, size=N)          # events per 100 km
speeding = rng.lognormal(mean=0.2, sigma=0.5, size=N)
night = rng.beta(1.5, 8, size=N)                               # share of night-time km
exposure = rng.uniform(0.3, 1.0, size=N)                       # policy-years observed
X = np.column_stack([braking, speeding, night])
Z = (X - X.mean(axis=0)) / X.std(axis=0)
TRUE_BETA = np.array([0.25, 0.10, 0.15])                       # true effect (log scale)
base_rate = 0.06                                               # claims per policy-year
lam = base_rate * np.exp(Z @ TRUE_BETA)
claims = rng.poisson(lam * exposure)

# --- Model: frequency = claims / exposure, weighted by exposure. ---
glm = PoissonRegressor(alpha=0.0, max_iter=500)
glm.fit(Z, claims / exposure, sample_weight=exposure)
print(f"contracts {N}, policy-years {exposure.sum():.0f}, claims observed {claims.sum()}")
print(f"{'variable':26s} {'true':>6s} {'estimated':>10s} {'relativity per +1 std':>22s}")
for name, b, e in zip(FEATURES, TRUE_BETA, glm.coef_):
    print(f"{name:26s} {b:6.2f} {e:10.3f} {np.exp(e):22.3f}")

# --- From score to premium: relativity with floor and cap, then rebalancing. ---
pred = glm.predict(Z)
raw = pred / np.average(pred, weights=exposure)
factor = np.clip(raw, 0.70, 1.50)
mean_after_clip = np.average(factor, weights=exposure)
factor = factor / mean_after_clip            # total premium stays what it was
at_limits = np.mean((raw < 0.70) | (raw > 1.50))
print(f"\nraw factor: min {raw.min():.2f}, median {np.median(raw):.2f}, max {raw.max():.2f}")
print(f"share of contracts touched by floor or cap: {at_limits:.1%}")
print(f"weighted mean after clipping: {mean_after_clip:.3f} -> rebalancing divisor")

# --- Comparison with hand-picked weights (style "30% braking, 25% speeding, 15% night"). ---
hand = 0.30 * Z[:, 0] + 0.25 * Z[:, 1] + 0.15 * Z[:, 2]

def decile_ratio(score):
    order = np.argsort(score)
    d = len(score) // 10
    low, high = order[:d], order[-d:]
    f = lambda idx: claims[idx].sum() / exposure[idx].sum()
    return f(high), f(low)

for label, s in [("Poisson GLM", pred), ("hand weights", hand)]:
    hi, lo = decile_ratio(s)
    print(f"{label:12s} claims/year in worst decile {hi:.3f}, best {lo:.3f}, ratio {hi / lo:.2f}")

# Output:
# contracts 40000, policy-years 25978, claims observed 1741
# variable                     true  estimated  relativity per +1 std
# braking_100km                0.25      0.222                  1.249
# speeding_100km               0.10      0.038                  1.039
# night_share                  0.15      0.176                  1.192
#
# raw factor: min 0.48, median 0.93, max 6.31
# share of contracts touched by floor or cap: 19.1%
# weighted mean after clipping: 0.981 -> rebalancing divisor
# Poisson GLM  claims/year in worst decile 0.120, best 0.042, ratio 2.88
# hand weights claims/year in worst decile 0.107, best 0.042, ratio 2.57

The model recovers the order and the order of magnitude of the coefficients but not the exact value: with 1,741 observed claims the estimation error is of the order of 0.02: repeating the experiment with 20 different seeds (a check outside the listing) the estimates have means of 0.253, 0.095 and 0.146 and a standard deviation between 0.020 and 0.024. The value for speeding (0.038 against a true 0.10) is therefore a sampling fluctuation, not a defect of the method, and shows how noisy data with few claims can be. The raw factor ranges from 0.48 to 6.31; 19.1% of contracts are touched by the floor or the cap, and the mean after clipping is 0.981, so the factors are divided by that number.

The final comparison: claims per year of 0.120 in the worst decile and 0.042 in the best for the GLM (ratio 2.88), 0.107 and 0.042 for the hand weights (2.57). Be careful how you read this result: the synthetic data are built with the same form as the model, so the GLM starts with an advantage. It does not prove that a GLM always beats hand-picked weights on real data; it shows that you can (and must) measure it on yours.

Privacy as part of the design

The EDPB Guidelines 01/2020 on connected vehicles say, at point 63, that location data are "particularly revealing" of people's life habits: trips let you infer home and workplace, and possibly sensitive information such as a place of worship. They recommend collecting them only if strictly necessary. At point 78 they describe precisely the insurance case: driving behaviour can be processed in the vehicle or by a provider on behalf of the insurer, and the insurer receives only a periodic numeric score, without the raw data, so that minimisation is guaranteed by design. Concrete choices follow for the pipeline:

  • Compute the score close to the source: send the insurer the aggregate score, not the traces
  • Limit the retention of raw data: define a period and a job that deletes
  • Reduce location precision: if you need the road type, you do not need the address
  • Pseudonymise identifiers: keep the token separate from the key that lets you trace back to the policyholder

These are design choices motivated by Article 5(1), points (c) and (e) (data minimisation and storage limitation), and by Article 25 (data protection by design and by default) of the GDPR. They do not establish a legal basis on their own: whether the processing rests on consent, on the contract or on something else is decided by the controller, and it is not a matter of code. Recital 26 also specifies that pseudonymised data remain personal data, so a token does not make a route anonymous.

The listing shows the three minimal mechanisms with measured numbers. Deletion has a 90-day threshold that is an example choice, not an obligation; the generalisation of coordinates measures how far the point moves when rounded; the token uses HMAC-SHA256 with a key kept elsewhere.

Python: deletion by age, coarser coordinates, HMAC pseudonym
import hmac, hashlib, sqlite3
from datetime import date, timedelta
from math import asin, cos, radians, sin, sqrt

TODAY = date(2026, 11, 12)
RETENTION_DAYS = 90            # DESIGN choice of the example, not a legal obligation

db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE raw_points (policy_ref TEXT, day TEXT, lat REAL, lon REAL)")
rows = [("P1", str(TODAY - timedelta(days=d)), 40.3515 + d * 1e-4, 18.1718) for d in (1, 30, 89, 90, 91, 200)]
db.executemany("INSERT INTO raw_points VALUES (?, ?, ?, ?)", rows)

def purge(db, today, days):
    cutoff = str(today - timedelta(days=days))
    with db:
        cur = db.execute("DELETE FROM raw_points WHERE day < ?", (cutoff,))
    return cur.rowcount, cutoff

removed, cutoff = purge(db, TODAY, RETENTION_DAYS)
left = [r[0] for r in db.execute("SELECT day FROM raw_points ORDER BY day")]
print(f"cutoff {cutoff}: deleted {removed}, remaining {len(left)} ({left[0]} .. {left[-1]})")

def hav_m(lat1, lon1, lat2, lon2):
    p1, p2 = radians(lat1), radians(lat2)
    a = sin((p2 - p1) / 2) ** 2 + cos(p1) * cos(p2) * sin(radians(lon2 - lon1) / 2) ** 2
    return 2 * 6371008.8 * asin(sqrt(a))

lat, lon = 40.35147, 18.17183
for decimals in (3, 2, 1):
    rl, ro = round(lat, decimals), round(lon, decimals)
    print(f"{decimals} decimals -> ({rl}, {ro}), displacement {hav_m(lat, lon, rl, ro):7.0f} m")

def pseudonym(key: bytes, policy_id: str) -> str:
    return hmac.new(key, policy_id.encode(), hashlib.sha256).hexdigest()[:16]

k1, k2 = b"example-key-1", b"example-key-2"
print("same key, same id   :", pseudonym(k1, "POL-0001") == pseudonym(k1, "POL-0001"))
print("other key, same id  :", pseudonym(k1, "POL-0001") == pseudonym(k2, "POL-0001"))
print("token:", pseudonym(k1, "POL-0001"))

# Output:
# cutoff 2026-08-14: deleted 2, remaining 4 (2026-08-14 .. 2026-11-11)
# 3 decimals -> (40.351, 18.172), displacement      54 m
# 2 decimals -> (40.35, 18.17), displacement     225 m
# 1 decimals -> (40.4, 18.2), displacement    5900 m
# same key, same id   : True
# other key, same id  : False
# token: d1f8a562caf34e95

With a 90-day threshold the job deletes the two oldest records (91 and 200 days), and the record of exactly 90 days stays, because the comparison is "strictly less than". Rounding to two decimals moves the example point by 225 m, to one decimal by 5,900 m; the values depend on the point and on the latitude, so they must be re-measured on your own area. The second part is the property of the pseudonym that matters: the same identifier gives the same token only with the same key, so without the key (kept separately) you cannot trace back to the policyholder, but whoever holds it can, and that is exactly why pseudonymisation is not anonymisation.

What you can do now

You know that a braking threshold computed on whole-number readings at 10 Hz invents events, and how to avoid it with a window longer than the resolution; you can split a stream of points into trips with a session window and you know the equivalent form in Flink; you can estimate a claims-based frequency score, with relativity, floor, cap and rebalancing, and you know that the comparison has to be redone on your own data; you know which privacy choices follow from an EDPB text and from three GDPR articles. The next step is how this score enters the acceptance decision, in the article AI underwriting: feature engineering and risk scoring. For the domain you start from, see article 1 of the series.

Frequently asked questions

Why does the braking detector find more events than really happened?

Because speed arrives in whole-number values and a single 1 km/h step in 0.1 seconds equals 2.78 m/s², close to the threshold of 3 m/s². Two adjacent steps exceed it. Computing acceleration over a window of half a second or more removes these false events, at the cost of dampening real braking a little.

How much location data should I keep for usage-based insurance?

As little as possible. The EDPB Guidelines 01/2020 describe, as a design solution, computing the score close to the source, with the insurer receiving only the periodic score. How long to keep raw data depends on your case and has to be decided with the data protection officer: the 90-day period in the listing is only an example.

Does a pseudonymous token make data anonymous?

No. Recital 26 of the GDPR says that personal data which have undergone pseudonymisation, and which could be attributed to a person by the use of additional information, remain information on an identifiable person. The token reduces risk but the processing remains subject to the regulation.

Sources

The listings braking.py, trips.py, score.py and privacy.py were run twice with the same output (Python 3, NumPy 2.3.5, scikit-learn 1.8.0). The PyFlink schema was not executed. All data are synthetic with a fixed seed; no market figure is reported.

Try These Tools

Free developer tools related to this topic.

Commenti

Caricamento commenti...

Sign in to comment

New articles and tools on Telegram too

The Telegram channel flags the site's new articles and tools.

Did you like this article?

Explore other content on the blog or discover my projects