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 lessonAnalyze 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".
More Time Series exercises
- Build the Time Series DataFrameAdvanced
- Compute Moving AveragesAdvanced
- Discover Seasonal PatternsAdvanced
- Flag Anomalous DaysAdvanced
- The Complete Trend ReportAdvanced
All Python exercises · 50 practice problems · Practical Projects quiz