You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何按N天分段计算并可视化线性回归曲线?

Segmented Linear Regression for Time Series (Every N Days)

Got it, let's walk through exactly how to implement this segmented linear regression and visualize the results. You already have a solid slope/intercept calculator, so we'll build on that with a loop to handle the N-day chunks, then plot everything together.

Step 1: Define Your Segmentation Logic

First, pick your segment size N (e.g., 7 for weekly segments). We'll split your time series into consecutive chunks of N days, and automatically handle the final partial chunk if your total data length isn't a perfect multiple of N.

Step 2: Full Implementation Code

Here's how to wrap your existing function in a loop to compute each segment's regression line, then store all results for plotting:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# Your existing slope/intercept function (unchanged)
def slope_intercept(x_val, y_val):
    x = np.array(x_val)
    y = np.array(y_val)
    m = ( ( (np.mean(x)*np.mean(y) ) - np.mean(x*y)) / ( ( np.mean(x)*np.mean(x)) - np.mean(x*x)))
    m = round(m,2)
    b=(np.mean(y)-np.mean(x)*m)
    b=round(b,2)
    return m,b

# Example setup (replace with your actual DataFrame)
# Assume `future` is your time series DataFrame with 'close' column and sequential index
# future = pd.read_csv('your_data.csv', index_col='date', parse_dates=True)

# Set your desired segment size
N = 5  # Adjust this to your preferred number of days per segment

# Initialize a list to store each segment's regression data
regression_segments = []

# Iterate over each N-day chunk
total_days = len(future)
for i in range(0, total_days, N):
    # Get bounds for the current segment (handle final partial chunk)
    end_idx = min(i + N, total_days)
    segment = future.iloc[i:end_idx]
    
    # Extract x (index values) and y (close prices) for the segment
    x_vals = segment.index.tolist()
    y_vals = segment['close'].tolist()
    
    # Calculate slope and intercept using your function
    m, b = slope_intercept(x_vals, y_vals)
    
    # Generate regression line points for this segment
    segment['reg_line'] = [m * x + b for x in x_vals]
    
    # Add the segment to our list
    regression_segments.append(segment)

# Combine segments into a single DataFrame (optional but handy for analysis)
combined_reg_data = pd.concat(regression_segments)

Step 3: Visualize the Results

Now let's plot the original close prices alongside all segmented regression lines. We'll loop through each segment to plot its line—you can even color-code segments if you want to distinguish them clearly:

plt.figure(figsize=(12,6))

# Plot original close price data
plt.plot(future.index, future['close'], label='Original Close Price', color='blue', alpha=0.5)

# Plot each segmented regression line
for seg_num, segment in enumerate(regression_segments):
    plt.plot(segment.index, segment['reg_line'], label=f'Segment {seg_num+1} Regression', linestyle='--')

plt.title(f'Segmented Linear Regression (Every {N} Days)')
plt.xlabel('Date/Index')
plt.ylabel('Close Price')
plt.legend()
plt.grid(True)
plt.show()

Notes for Datetime Indices

If your future DataFrame uses datetime indices instead of integers, convert dates to numeric ordinals for the regression calculation (since linear regression requires numeric x-values):

# Replace x_vals with this for datetime indices
x_vals = segment.index.map(pd.Timestamp.toordinal).tolist()
# The plot will still use the original datetime index for readability

Edge Case Handling

  • Partial final segment: Our code uses min(i + N, total_days) to ensure we don't go out of bounds, so even the last chunk with fewer than N days gets a regression line.
  • Skip partial segments: If you don't want to include partial chunks, add a check inside the loop: if end_idx - i < N: break

内容的提问来源于stack exchange,提问作者hkml

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:47:07