# Condition Monitoring Trend and Time-to-Alarm Python Script Generator

> Source: https://netray.co/tools/condition-monitoring-alarm-trend-python-script-generator
> Publisher: Netray (netray.co), AI and integration engineering for ERP and manufacturing systems.
> Section: Free Tools

## Short answer

Get a standard-library Python script that fits a trend to recent sensor readings and estimates how many days remain before an alarm limit is crossed.

## Category

maintenance

## Industry

Discrete Manufacturing

## Audience

- Reliability engineer
- Data analyst
- Maintenance planner

## Tool

**Kind:** template

**Output:** code

**Language:** python

**Fields:**

#### CSV file path

**Key:** csv_path

**Type:** text

**Default:** pump_01_vibration.csv

#### Timestamp column

**Key:** time_col

**Type:** text

**Default:** timestamp

#### Value column

**Key:** value_col

**Type:** text

**Default:** velocity_mm_s

#### Alert limit

**Key:** alert

**Type:** number

**Default:** 4.5

#### Danger limit

**Key:** danger

**Type:** number

**Default:** 7.1

#### Number of recent points to fit

**Key:** window

**Type:** number

**Default:** 30

**Blocks:**

#### trend_to_alarm.py

**Body:** import csv
from datetime import datetime

CSV_PATH = "{{csv_path}}"
TIME_COL = "{{time_col}}"
VALUE_COL = "{{value_col}}"
ALERT = {{alert}}
DANGER = {{danger}}
WINDOW = {{window}}

def load(path):
    rows = []
    with open(path, newline="") as fh:
        for rec in csv.DictReader(fh):
            t = datetime.fromisoformat(rec[TIME_COL])
            rows.append((t, float(rec[VALUE_COL])))
    rows.sort(key=lambda r: r[0])
    return rows

def fit_line(points):
    # least squares fit of value = a + b * days
    t0 = points[0][0]
    xs = [(t - t0).total_seconds() / 86400.0 for t, _ in points]
    ys = [v for _, v in points]
    n = len(xs)
    mx = sum(xs) / n
    my = sum(ys) / n
    sxx = sum((x - mx) ** 2 for x in xs)
    if sxx == 0:
        return my, 0.0, xs[-1]
    b = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / sxx
    a = my - b * mx
    return a, b, xs[-1]

def days_to(limit, a, b, now_x):
    if b <= 0:
        return None
    x_cross = (limit - a) / b
    return max(0.0, x_cross - now_x)

rows = load(CSV_PATH)
if len(rows) < 5:
    raise SystemExit("Need at least 5 readings")
recent = rows[-WINDOW:]
a, b, now_x = fit_line(recent)
last_value = recent[-1][1]

print("Latest reading:", round(last_value, 3))
print("Trend per day:", round(b, 4))
for name, limit in (("alert", ALERT), ("danger", DANGER)):
    if last_value >= limit:
        print(name, "limit already exceeded")
        continue
    d = days_to(limit, a, b, now_x)
    if d is None:
        print(name, "limit: no upward trend")
    else:
        print(name, "limit in about", round(d, 1), "days")

#### Expected CSV layout

**Body:** timestamp,{{value_col}}
2026-09-01T06:00:00,2.10
2026-09-02T06:00:00,2.14
2026-09-03T06:00:00,2.19

**Notes:** Uses only the Python standard library (3.7 or later). A straight line is a rough guide, not a remaining useful life model: wear often accelerates. Use it to prioritise inspections, then confirm with another technique. Timestamps must be ISO format.

## Content

**Intro:** A simple trend line answers a practical question: if this reading keeps rising at the recent rate, how many days until it hits the alert and danger limits. This generator writes a short Python script for that, with your column names and limits filled in.

**Sections:**

#### How to use it

**Body:** Export a CSV of readings for one measurement point, with a timestamp column and a value column. Enter the file path, the column names, the alert and danger limits, and the number of recent points to fit. Copy the script into a file and run it with Python. It fits a least squares line through the most recent points and reports the daily slope and the number of days until each limit is crossed. A shorter window reacts faster to a change in slope, a longer window is more stable.

**Bullets:**

- Fit one point at a time, not a mix of machines
- Use 20 to 60 recent points as a starting window
- Re-run weekly and keep the results
- Treat the output as a prioritisation aid

#### The method

**Body:** Ordinary least squares fits value = a + b x days, where b is the slope in units per day. The crossing time for a limit L is (L - a) / b, and the days remaining is that value minus the current time on the same axis. If the slope is zero or negative, no crossing is predicted. Real degradation is rarely linear, so for bearings in particular the estimate will be optimistic once the defect starts to progress. Exponential or power law fits can be added if your data supports them.

#### Worked example

**Body:** A pump bearing has a velocity of 3.2 mm/s with a recent slope of 0.05 mm/s per day. The alert limit is 4.5 mm/s, so the crossing is (4.5 - 3.2) / 0.05 = 26 days away. The danger limit of 7.1 mm/s is about 78 days away on the same slope. With a 26 day warning, a planner can order the bearing, book a window and avoid an unplanned stop. If the slope doubles next week, the script will show it.

#### Common mistakes

**Body:** Fitting across a maintenance event mixes two different regimes: restart the data after a repair or a rebuild. Ignoring missing data and gaps creates a false slope. Using a slope of a noisy series without smoothing can also give wild predictions, so check the plot of the data before trusting the number.

**Cta:** If you want trend and time-to-alarm results surfaced in your ERP or CMMS dashboard, with the query shown, we can scope that with you. Ask for an expert review.

**Faq:**

#### Is a linear trend good enough for predicting failure?

**Answer:** It is good enough to rank which assets need attention first, not to promise a failure date. Degradation often accelerates near the end of life, so treat the estimate as an upper bound on the time you have.

#### What data frequency should I use?

**Answer:** Daily or per-shift readings work well for slow wear like bearing trends. Faster data is useful for detecting step changes, but you may need to average it to hourly or daily values before fitting.

#### Do I need extra Python packages?

**Answer:** No. The script uses only the csv and datetime modules from the standard library. For plotting or more advanced models you can add libraries such as numpy and matplotlib later.

#### How do I choose alert and danger limits?

**Answer:** Start from the relevant standard or manufacturer guidance for the machine class, then adjust using your own baseline. Limits set at a multiple of the healthy baseline are common for machines where no standard fits.

## Search terms

predict time to alarm python, vibration trend linear regression python, condition monitoring python script, remaining useful life simple trend, sensor csv trend analysis, predictive maintenance python example, days to alarm limit calculation, linear trend extrapolation sensor data

---
Talk to an engineer: https://netray.co/contact?intent=erp_ai | Machine catalog: https://netray.co/agent/catalog.json
