Condition Monitoring Trend and Time-to-Alarm Python Script Generator
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.
Fill in
trend_to_alarm.py
import csv
from datetime import datetime
CSV_PATH = "pump_01_vibration.csv"
TIME_COL = "timestamp"
VALUE_COL = "velocity_mm_s"
ALERT = 4.5
DANGER = 7.1
WINDOW = 30
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
timestamp,velocity_mm_s 2026-09-01T06:00:00,2.10 2026-09-02T06:00:00,2.14 2026-09-03T06:00:00,2.19
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.
Show trend and days-to-alarm in your ERP
Optional: we can review where your readings live and sketch a read-only way to show trend results next to asset records.
Optional. The tool and every export work without this. No spam.
How to use it
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.
- 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
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
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
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.
Frequently Asked Questions
Is a linear trend good enough for predicting failure?
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?
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?
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?
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.
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.
Related Tools
Condition Monitoring Alarm SQL Query Generator
Fill in your table and column names and get SQL that finds sensor readings over limits and flags assets with no open work order.
Maintenance & ReliabilityVibration Fault Signature Diagnosis Reference
A searchable lookup of what each common machine fault looks like in a vibration spectrum, with dominant frequency, direction and the first check to make.
Maintenance & ReliabilityPredictive Maintenance Data Readiness Assessment
Ten questions that show whether your asset data, failure history and sensor coverage can support predictive maintenance, and what to fix first.
Maintenance & ReliabilityCondition Monitoring Program Readiness Checklist
A practical checklist for starting or auditing a condition monitoring program, from asset selection to closing the loop in the work order system.
More Maintenance & Reliability tools
See all- TPM Autonomous Maintenance CIL Standard Template
- ISO 4406 Oil Cleanliness Code Reference
- Infrared Thermography Severity and Emissivity Reference
- Condition Monitoring Finding and Recommendation Report Template
- MTBF and MTTR Worksheet
- TPM Autonomous Maintenance Standard Template
- TPM Pillars and Autonomous Maintenance 7 Steps Reference
- Preventive Maintenance Schedule Template
- Maintenance Work Order Template