How to Build a Reusable CGM Interpretation Template
By the end of this guide you will have a single Python script that takes a raw CGM export and emits three artifacts: a metrics table (time in range, glycemic variability, glucose management indicator), an ambulatory glucose profile plot, and a meal-anchored response table. You will also have a fill-in-the-blanks interpretation document that keeps your reading of the data consistent from month to month. You need a CGM export in CSV form (Dexcom Clarity, Abbott LibreView, or the raw stream from an open-source uploader), Python 3.11 with pandas, numpy, and matplotlib, and ideally a timestamped log of meals and workouts. Everything here is measurement and description. Deciding what a pattern means for your health, and what to do about it, is a conversation with a clinician.
1. Export the raw data and learn its schema
Start by getting the highest-resolution file the vendor will give you. The PDF summary is not enough. Dexcom Clarity exports a CSV whose columns include Timestamp (YYYY-MM-DDThh:mm:ss) and Event Type. It also includes Event Subtype and Glucose Value (mg/dL). Rows are mixed: estimated glucose values (EGV) sit alongside calibration, insulin, and note events, so you must filter on Event Type == "EGV" before doing anything numeric.
Abbott’s LibreView export is different. It has a Record Type integer column where 0 is an automatic scan-free reading and 1 is a manual scan, plus separate columns for historic and scan glucose. Use record type 0 for the continuous series and treat scans as a separate, sparser stream.
Two schema traps matter. Values above the sensor ceiling appear as the strings High or Low rather than numbers, and timestamps are local wall-clock with no timezone offset, so a daylight-saving transition silently duplicates or deletes an hour. Decide your convention now: we clamp High to 400 mg/dL and Low to 40 mg/dL, and localize timestamps with tz_localize('America/New_York', ambiguous='NaT', nonexistent='NaT') so ambiguous rows drop instead of scrambling the time-of-day analysis.
2. Normalize to a canonical time grid
Every metric downstream assumes evenly spaced samples. Dexcom G6 and G7 report every 5 minutes. Libre 3 reports every minute but exports at coarser intervals depending on the product. Resample to a fixed grid so that time in range is a true time fraction rather than a count of unevenly spaced readings.
import pandas as pd, numpy as np
def load_dexcom(path, tz="America/New_York"):
df = pd.read_csv(path)
df = df[df["Event Type"] == "EGV"].copy()
g = df["Glucose Value (mg/dL)"].astype(str)
df["glucose"] = pd.to_numeric(g.replace({"High": "400", "Low": "40"}), errors="coerce")
ts = pd.to_datetime(df["Timestamp (YYYY-MM-DDThh:mm:ss)"])
df["ts"] = ts.dt.tz_localize(tz, ambiguous="NaT", nonexistent="NaT")
df = df.dropna(subset=["ts", "glucose"]).set_index("ts").sort_index()
grid = df["glucose"].resample("5min").mean()
# bridge gaps up to 15 minutes; leave real dropouts as NaN
return grid.interpolate(limit=3, limit_area="inside").to_frame("glucose")
The limit=3 choice is deliberate. Short gaps from a lost Bluetooth connection are safe to bridge, and leaving them as NaN would understate your denominator. Gaps longer than 15 minutes usually mean the sensor was off the body or in warm-up, and interpolating across them invents data.
3. Check data sufficiency before computing a single metric
This is the step most people skip, and it is the one that decides whether the report is worth reading. The standard reporting window is 14 days, which is long enough for the metrics to approximate longer-term glycemia while staying short enough to reflect current behavior 1. Below roughly 70 percent sensor capture within that window, the percentages start to reflect when you wore the sensor rather than how you metabolize glucose.
def sufficiency(df, days=14):
end = df.index.max()
win = df.loc[end - pd.Timedelta(days=days):end]
expected = days * 24 * 12 # 5-minute samples
capture = win["glucose"].notna().sum() / expected
by_hour = win.groupby(win.index.hour)["glucose"].apply(lambda s: s.notna().mean())
return {"capture": round(capture, 3),
"worst_hour": int(by_hour.idxmin()),
"worst_hour_capture": round(by_hour.min(), 3)}
The per-hour breakdown catches a specific failure. If your worst coverage is between 02:00 and 05:00, you are probably losing overnight data to compression on the sensor, and every overnight statistic in the report is biased. Print the sufficiency dictionary at the top of the report and refuse to generate the rest if capture falls below 0.70.
4. Compute the core metrics
These are the numbers that appear on every standardized CGM report, and computing them yourself means you know exactly what the denominator was 2. Time in range is the fraction of time between 70 and 180 mg/dL. The consensus target bands add time below 70 and time below 54, plus time above 180 and time above 250. Coefficient of variation (CV) is defined as standard deviation divided by mean. Prefer it over raw standard deviation as a variability measure, because it scales with mean glucose and stays comparable across people.
def core_metrics(s):
s = s.dropna()
n = len(s)
mean = s.mean()
m = {
"n_readings": n,
"mean_mgdl": round(mean, 1),
"gmi_pct": round(3.31 + 0.02392 * mean, 2),
"sd": round(s.std(ddof=1), 1),
"cv_pct": round(100 * s.std(ddof=1) / mean, 1),
"tir_70_180": round(100 * s.between(70, 180).mean(), 1),
"tbr_lt70": round(100 * (s < 70).mean(), 1),
"tbr_lt54": round(100 * (s < 54).mean(), 1),
"tar_gt180": round(100 * (s > 180).mean(), 1),
"tar_gt250": round(100 * (s > 250).mean(), 1),
}
for q in (5, 25, 50, 75, 95):
m[f"p{q}"] = round(np.percentile(s, q), 1)
return m
The glucose management indicator (GMI) is a linear transform of mean glucose, nothing more: GMI% = 3.31 + 0.02392 × mean mg/dL. A GMI of 6.2 percent corresponds to a mean glucose of about 121 mg/dL over the recording window. GMI is not HbA1c and routinely differs from a lab A1c by several tenths of a percent in either direction, because A1c also depends on red blood cell lifespan and hemoglobin variants. Report both when you have both, and treat a persistent gap between them as a fact about your physiology rather than an error.
If you do not have diabetes, the consensus target bands are the wrong yardstick. The bands were written for people managing insulin, where the binding constraint is hypoglycemia. A metabolically healthy adult typically spends the large majority of the day between 70 and 140 mg/dL with a CV well under 36 percent. Normative CGM distributions have been published for specific populations, including pregnancy without gestational diabetes, and those are more informative comparators than diabetes targets 3. Where your numbers sit relative to any clinical threshold is a question for a clinician who can order confirmatory venous testing.
5. Build the ambulatory glucose profile
The ambulatory glucose profile (AGP) collapses every day in the window onto a single 24-hour axis and plots percentile bands by time of day. It is the visualization the standardized reports are built around, and it is good at exactly one thing: showing you which hours of the day are reliably different from the others 1.
import matplotlib.pyplot as plt
def agp(df, days=14):
end = df.index.max()
w = df.loc[end - pd.Timedelta(days=days):end].copy()
w["tod"] = w.index.hour * 60 + w.index.minute
g = w.groupby("tod")["glucose"]
q = g.quantile([0.05, 0.25, 0.50, 0.75, 0.95]).unstack()
x = q.index / 60
fig, ax = plt.subplots(figsize=(11, 4))
ax.fill_between(x, q[0.05], q[0.95], alpha=0.15, color="C0")
ax.fill_between(x, q[0.25], q[0.75], alpha=0.35, color="C0")
ax.plot(x, q[0.50], color="C0", lw=2)
ax.axhspan(70, 180, color="green", alpha=0.06)
ax.set_xlim(0, 24); ax.set_ylim(40, 300)
ax.set_xlabel("hour of day"); ax.set_ylabel("mg/dL")
return fig, q
Read the AGP in a fixed order. First look at the width of the interquartile band, because a wide band means the same hour behaves differently on different days and points at behavior rather than baseline physiology. Then look at the overnight median between 02:00 and 06:00, which is the closest thing you have to a fasting baseline sampled hundreds of times. Then look at where the median crosses upward, since that timing usually maps onto a specific meal.
6. Segment the day and anchor responses to events
Aggregate metrics tell you the size of the problem. Event-anchored analysis tells you what produced it. Split the record into an overnight window, a fasting window, and post-meal windows. Then compute a response curve for each logged meal.
def meal_response(df, meal_ts, pre_min=15, post_min=180):
t0 = pd.Timestamp(meal_ts)
seg = df.loc[t0 - pd.Timedelta(minutes=pre_min): t0 + pd.Timedelta(minutes=post_min), "glucose"]
if seg.isna().mean() > 0.2 or len(seg) < 20:
return None
baseline = seg.loc[:t0].mean()
peak = seg.max()
t_peak = (seg.idxmax() - t0).total_seconds() / 60
above = (seg - baseline).clip(lower=0)
iauc = np.trapz(above.values, dx=5) # mg/dL * min
after = seg.loc[t0:]
back = after[after <= baseline + 10]
t_return = (back.index[0] - t0).total_seconds() / 60 if len(back) else np.nan
return {"baseline": round(baseline, 1), "peak": round(peak, 1),
"delta": round(peak - baseline, 1), "t_peak_min": round(t_peak),
"iauc_mgdl_min": round(iauc), "t_return_min": t_return}
Four numbers describe a meal response: the rise above baseline, the time to peak, the incremental area under the curve, and the time to return to baseline. They are not interchangeable. A tall spike that rises and falls fast can share an iAUC with a low and long plateau. The two still reflect different underlying kinetics of absorption and disposal 4. We report all four and treat time to return as the most sensitive of them.
Tag every meal row with context you control. Record composition and time of day, whether it followed exercise, and how much you slept the night before. The same meal eaten at 08:00 and 20:00 often produces different curves in the same person, and you will only see that if the tag is in the table.
If you train, add exercise windows as their own event type. Glucose behavior during and after exercise depends on intensity and duration in ways that make a naive time-in-range number misleading for athletes, and high-intensity work can push glucose up rather than down 5. Score exercise sessions separately from meals rather than letting them contaminate the postprandial windows.
7. Write the interpretation template
The template is the durable artifact. Keeping the same slots each cycle is what makes two reports comparable. Fill it in this order, from data quality outward, and write the numbers next to every claim.
WINDOW: {start} to {end} ({days} days, {capture}% capture, worst hour {worst_hour})
SENSOR: {device}, {n_sensors} sensors, sessions: {session_dates}
1. SUFFICIENCY. Capture {capture}%. Gaps concentrated at {worst_hour}:00.
Metrics {are / are not} interpretable for that window.
2. CENTRAL TENDENCY. Mean {mean} mg/dL, GMI {gmi}%, median {p50}.
Lab A1c {a1c}% drawn {date}. Gap: {gmi - a1c} points.
3. VARIABILITY. SD {sd}, CV {cv}%. Widest interquartile band at {hours}.
4. DISTRIBUTION. TIR 70-180: {tir}%. >180: {tar}%. <70: {tbr}%. <54: {tbr54}%.
Each excursion below 70 reviewed for compression artifact: {yes/no}.
5. OVERNIGHT BASELINE. Median 02:00-06:00 = {x} mg/dL, range {lo}-{hi}.
Trend vs prior window: {delta}.
6. MEAL RESPONSES. {n} meals logged. Median delta {d} mg/dL,
median time to peak {tp} min, median time to return {tr} min.
Largest three responses: {list with composition tags}.
7. EXERCISE. {n} sessions. Median change during session {x} mg/dL.
Post-session pattern: {description}.
8. CHANGES SINCE LAST WINDOW. {two or three sentences, with numbers}.
9. QUESTIONS FOR CLINICIAN. {list}.
10. NEXT EXPERIMENT. One variable, defined start and end, defined metric.
Section 9 is not decoration. Any sustained pattern outside expected ranges, any hypoglycemia that is not artifact, and any large gap between GMI and lab A1c belongs in front of someone who can order the confirmatory test. Section 10 keeps you from changing five things at once, which is the most common way a self-tracked CGM record becomes uninterpretable.
8. Hand the artifacts to an AI agent
An agent is useful here for pattern description over a structured summary, and much less useful when handed 4,000 raw rows. Give it the metrics dictionary, the AGP percentile table as CSV, and the meal response table. Then ask for described patterns with the supporting numbers cited. Retrieval-augmented systems grounded in specific source documents produce better CGM counseling than ungrounded generation, so attach the guideline text you want it to reason against rather than trusting recall 6.
Set the constraint explicitly in the prompt: describe patterns, quantify them, and flag what needs a clinician. Ask for the three strongest signals and the three weakest, so you learn which conclusions rest on twelve meals and which rest on two. The failure mode to watch is confident interpretation of a pattern that a single wide-band hour drove.
Common problems
Compression lows are the most frequent artifact in a personal record. Lying on the sensor restricts interstitial flow and produces a rapid drop to a false low, typically overnight, followed by a fast recovery once you move. Check the shape before believing a nocturnal reading below 70. A sharp V lasting 20 to 60 minutes with no symptoms and no meal explanation is usually pressure. It is usually not glucose.
First-day drift is next. Sensors are least accurate in the first 12 to 24 hours after insertion, and Dexcom’s warm-up period does not fully cover it. We exclude the first 12 hours of every sensor session from metric computation and note the exclusion in the report header.
Interstitial lag is a real and permanent offset. CGM measures interstitial fluid, which trails plasma glucose by roughly 5 to 15 minutes, and the lag is largest when glucose is changing fastest. Never compare a fingerstick to a CGM reading during a steep rise and conclude the sensor is broken. Compare at a flat stretch instead.
Sensor-to-sensor offsets break longitudinal comparison. Two sensors worn simultaneously can differ by 10 mg/dL or more in mean, which is enough to move GMI by a quarter point. If a metric shifts exactly when a sensor changed, suspect the device before your physiology. Overlapping the last day of one sensor with the first day of the next gives you a direct estimate of the offset.
Finally, be careful with the leap from a pattern to an action. Studies of how people translate CGM readings into decisions show wide variability in interpretation of the same trace, even among experienced users 7. The template exists to slow that step down: measure it, write it, then ask someone qualified what it means.
Footnotes
-
Irl B. Hirsch, Carol A. Verderese. Professional Flash Continuous Glucose Monitoring with Ambulatory Glucose Profile Reporting to Supplement A1c: Rationale and Practical Implementation. Endocrine Practice, 2017. https://doi.org/10.4158/ep171962.ra ↩ ↩2
-
Thomas W. Martens, Gregg D. Simonson, Richard M. Bergenstal. Using continuous glucose monitoring data in daily clinical practice. Cleveland Clinic Journal of Medicine, 2024. https://doi.org/10.3949/ccjm.91a.23090 ↩
-
Celeste Durnwald, Roy W. Beck, Zoey Li, et al. Continuous Glucose Monitoring Profiles in Pregnancies With and Without Gestational Diabetes Mellitus. Diabetes Care, 2024. https://doi.org/10.2337/dc23-2149 ↩
-
Jitendra D. Belani. Interpreting Continuous Glucose Monitoring Through Metabolic Physiology: A Framework for Precision Nutrition in Type 2 Diabetes. Nutrients, 2026. https://doi.org/10.3390/nu18152578 ↩
-
Mikael Flockhart, Filip J. Larsen. Continuous Glucose Monitoring in Endurance Athletes: Interpretation and Relevance of Measurements for Improving Performance and Health. Sports Medicine, 2023. https://doi.org/10.1007/s40279-023-01910-4 ↩
-
Zhijun Guo, Alvina Lai, Emmanouil Korakas, et al. Retrieval-Augmented Large Language Model Counseling for Continuous Glucose Monitoring in Diabetes: Source-Masked Multirater Comparative Evaluation. Journal of Medical Internet Research, 2026. https://doi.org/10.2196/98519 ↩
-
Jeremy Pettus, David A. Price, Steven V. Edelman. How Patients With Type 1 Diabetes Translate Continuous Glucose Monitoring Data into Diabetes Management Decisions. Endocrine Practice, 2015. https://doi.org/10.4158/ep14520.or ↩
Pothos builds longitudinal molecular profiles of individuals: whole-genome sequencing, single-cell RNA sequencing, and plasma proteomics, delivered as a detailed report, every data file, and stored cells. Build your profile.