Editor

Measure the Trend

Advanced · Write the code · from Time Series: Detect Trends and Anomalies in Business Data

From the lesson: Step 3: Detect Trends

Is the business growing or shrinking? We can answer this by comparing the moving average at the start of our data to the end. We can also use a simple linear regression approach - calculate the slope of sales over time.

Read this part of the lesson

Analyze the trend in the sales data:

1. Calculate the mean sales for the first 7 days and the last 7 days.

2. Calculate the percentage change: (last_week - first_week) / first_week * 100.

3. Use numpy's polyfit to fit a line to the sales: slope, intercept = np.polyfit(range(len(df)), df['sales'], 1).

4. Print "First week avg: $X.XX", "Last week avg: $X.XX", "Change: X.X%", and "Daily growth rate: $X.XX/day" (the slope).

5. Print "Trend: UPWARD" if slope > 0, else "Trend: DOWNWARD".

import pandas as pd
import numpy as np
np.random.seed(42)
dates = pd.date_range('2024-01-01', periods=90, freq='D')
base = 1000 + np.arange(90) * 5
weekend_boost = np.where(dates.dayofweek >= 5, 200, 0)
noise = np.random.normal(0, 80, 90)
sales = np.maximum(base + weekend_boost + noise, 0)
df = pd.DataFrame({'sales': np.round(sales, 2)}, index=dates)
# Analyze the trend

More Time Series exercises

All Python exercises · 50 practice problems · Practical Projects quiz