Python对时间序列进行数据分析与可视化的实战指南

作者:

文章目录
  • 3σ原则检测异常值 # 计算滚动均值和标准差 rolling_mean = close_prices.rolling(window=20).mean() rolling_std = close_prices.rolling(window=20).std() # 定义异常阈值 upper_bound = rolling_mean + 3 * rolling_std lower_bound = rolling_mean – 3 * rolling_std # 检测异常值 anomalies = close_prices[(close_prices > upper_bound) | (close_prices < lower_bound)] # 可视化 plt.figure(figsize=(14, 6)) plt.plot(close_prices.index, close_prices, label=’收盘价’, alpha=0.7) plt.plot(upper_bound.index, upper_bound, ‘r–‘, label=’上界’) plt.plot(lower_bound.index, lower_bound, ‘r–‘, label=’下界’) plt.scatter(anomalies.index, anomalies, color=’red’, label=’异常值’, zorder=5) plt.title(‘股价异常值检测(3σ原则)’, fontsize=16) plt.legend() plt.show() 典型应用:2024年3月的异常下跌被成功标记,可能对应重大政策变动或市场恐慌事件。
  • Q1:如何处理非交易日数据缺失? A:使用resample方法填充非交易日: # 生成完整日期范围 full_dates = pd.date_range(start=’2020-11-17′, end=’2025-11-17′, freq=’B’) # B表示工作日 close_prices = close_prices.reindex(full_dates) close_prices = close_prices.interpolate(method=’linear’) # 线性插值填充 Q2:如何选择合适的可视化周期? A:根据分析目标选择: 长期趋势:使用月/季度数据 短期波动:使用日/周数据 高频交易:使用分钟级数据 Q3:如何保存可视化图表? A:Matplotlib保存方法: plt.savefig(‘stock_analysis.png’, dpi=300, bbox_inches=’tight’) Plotly保存方法: fig.write_html(‘interactive_chart.html’) # 保存为HTML fig.write_image(“interactive_chart.png”, scale=2) # 需要安装kaleido库 Q4:如何处理多只股票对比分析? A:使用子图或合并数据: # 获取多只股票数据 stocks = yf.download([‘600519.SS’, ‘000858.SZ’, ‘601318.SH’], start=’2020-11-17′, end=’2025-11-17′)[‘Close’] # 绘制子图 fig, axes = plt.subplots(3, 1, figsize=(14, 12)) for i, code in enumerate(stocks.columns): axes[i].plot(stocks.index, stocks, label=code) axes[i].set_title(f’股价走势’) axes[i].legend() plt.tight_layout() plt.show()
  • 时间序列模型: ARIMA模型:statsmodels.tsa.arima.model.ARIMA Prophet模型:from prophet import Prophet 高级可视化: Seaborn热力图:展示相关性矩阵 Plotly 3D图表:展示多变量关系 实战项目: 股票预测系统:结合LSTM神经网络 异常检测系统:实时监控股价异常波动 通过本文的实战案例,读者已掌握从数据获取到高级分析的完整流程。建议从简单案例开始实践,逐步尝试更复杂的模型和可视化技术。时间序列分析的核心在于理解数据背后的时间规律,而Python提供了从基础到高级的完整工具链,帮助我们高效完成这项工作。 到此这篇关于Python对时间序列进行数据分析与可视化的实战指南的文章就介绍到这了,更多相关Python时间序列内容请搜索风君子博客以前的文章或继续浏览下面的相关文章希望大家以后多多支持风君子博客! 您可能感兴趣的文章: 利用Python实现时间序列动量策略 Python实现时间序列变化点检测功能 使用python进行时间序列预测的流程 Python数据可视化中的时间序列图表功能(实例展示其强大功能) python机器学习darts时间序列预测和分析 使用Python进行时间序列分析的8种绘图类型 Python时间序列的实现
  • 目录
    • 一、环境搭建与数据准备
      • 1. 安装必要库
      • 2. 获取股票数据
    • 二、数据清洗与预处理
      • 1. 处理缺失值
      • 2. 时间索引设置
    • 三、基础可视化分析
      • 1. 基础折线图
      • 2. 移动平均线分析
    • 四、高级分析技术
      • 1. 季节性分解
      • 2. 自相关分析
    • 五、交互式可视化(Plotly版)
      • 1. 安装库
      • 2. 创建交互式图表
    • 六、实战案例:异常检测
      • 七、常见问题Q&A
        • 八、进阶学习资源

          ​在金融投资领域,股票价格波动、用户行为模式等数据都蕴含着时间维度上的规律。掌握时间序列分析技术,能帮助我们从数据中挖掘出隐藏的趋势、周期和异常。本文将以股票价格数据为例,通过Python实现从数据加载到可视化分析的全流程,用通俗易懂的方式拆解核心步骤。

          pip install pandas matplotlib seaborn statsmodels yfinance
          
          • pandas:数据清洗与处理的核心工具
          • matplotlib/seaborn:静态数据可视化
          • statsmodels:时间序列模型构建
          • yfinance:获取雅虎财经股票数据

          以贵州茅台为例,获取其近5年日线数据:

          import yfinance as yf
          
          # 下载数据(参数:股票代码,时间范围)
          data = yf.download('600519.SS', start='2020-11-17', end='2025-11-17')
          # 提取收盘价作为分析对象
          close_prices = data['Close']
          print(close_prices.head())
          

          输出示例:

          12020-11-17    1750.00
          22020-11-18    1735.50
          32020-11-19    1748.80
          4…

          # 检查缺失值数量
          print(f"缺失值数量:{close_prices.isnull().sum()}")
          
          # 线性插值填充缺失值
          close_prices = close_prices.interpolate(method='linear')
          

          # 确保索引为datetime类型
          close_prices.index = pd.to_datetime(close_prices.index)
          
          # 重采样为周数据(可选)
          weekly_data = close_prices.resample('W').last()
          

          import matplotlib.pyplot as plt
          plt.figure(figsize=(14, 6))
          plt.plot(close_prices.index, close_prices.values, 
                   label='贵州茅台收盘价', color='#1f77b4')
          plt.title('2020-2025年贵州茅台股价走势', fontsize=16)
          plt.xlabel('日期', fontsize=12)
          plt.ylabel('价格(元)', fontsize=12)
          plt.grid(True, linestyle='--', alpha=0.7)
          plt.legend()
          plt.tight_layout()
          plt.show()
          

          效果说明:通过折线图可直观看到股价的长期趋势和短期波动。2021年初的峰值和2024年的震荡区间清晰可见。

          # 计算20日和60日移动平均
          ma_20 = close_prices.rolling(window=20).mean()
          ma_60 = close_prices.rolling(window=60).mean()
          
          plt.figure(figsize=(14, 6))
          plt.plot(close_prices.index, close_prices, label='收盘价', alpha=0.5)
          plt.plot(close_prices.index, ma_20, label='20日均线', linewidth=2)
          plt.plot(close_prices.index, ma_60, label='60日均线', linewidth=2)
          plt.title('股价与移动平均线对比', fontsize=16)
          plt.legend()
          plt.show()
          

          关键发现:当短期均线(20日)上穿长期均线(60日)时,常被视为买入信号;反之则为卖出信号。

          from statsmodels.tsa.seasonal import seasonal_decompose
          
          # 按年周期分解(假设数据有年度季节性)
          result = seasonal_decompose(close_prices, model='additive', period=252)  # 252个交易日≈1年
          
          result.plot()
          plt.suptitle('股价季节性分解', y=1.02)
          plt.tight_layout()
          plt.show()
          

          分解结果

          • 趋势(Trend) :长期价格走向
          • 季节性(Seasonal) :年度内的周期性波动
          • 残差(Residual) :去除趋势和季节性后的随机波动

          from statsmodels.graphics.tsaplots import plot_acf
          
          plt.figure(figsize=(12, 6))
          plot_acf(close_prices.dropna(), lags=60, alpha=0.05)  # 显示60阶自相关
          plt.title('股价自相关图', fontsize=16)
          plt.xlabel('滞后阶数(交易日)', fontsize=12)
          plt.ylabel('自相关系数', fontsize=12)
          plt.show()
          

          解读技巧

          • 若前20阶自相关系数显著不为零,说明股价存在短期记忆性
          • 若在252阶(约1年)出现峰值,可能存在年度周期性

          pip install plotly
          

          import plotly.graph_objects as go
          
          fig = go.Figure()
          fig.add_trace(go.Scatter(
              x=close_prices.index,
              y=close_prices,
              name='收盘价',
              line=dict(color='#1f77b4', width=2)
          ))
          
          # 添加移动平均线
          fig.add_trace(go.Scatter(
              x=ma_20.index,
              y=ma_20,
              name='20日均线',
              line=dict(color='#ff7f0e', width=1.5, dash='dash')
          ))
          
          fig.update_layout(
              title='贵州茅台股价交互式图表',
              xaxis_title='日期',
              yaxis_title='价格(元)',
              hovermode='x unified',
              template='plotly_white'
          )
          
          fig.show()
          

          交互功能

          • 鼠标悬停显示具体数值
          • 缩放查看特定时间段
          • 拖动图表调整显示范围

          原则检测异常值

          # 计算滚动均值和标准差
          rolling_mean = close_prices.rolling(window=20).mean()
          rolling_std = close_prices.rolling(window=20).std()
          
          # 定义异常阈值
          upper_bound = rolling_mean + 3 * rolling_std
          lower_bound = rolling_mean - 3 * rolling_std
          
          # 检测异常值
          anomalies = close_prices[(close_prices > upper_bound) | (close_prices < lower_bound)]
          
          # 可视化
          plt.figure(figsize=(14, 6))
          plt.plot(close_prices.index, close_prices, label='收盘价', alpha=0.7)
          plt.plot(upper_bound.index, upper_bound, 'r--', label='上界')
          plt.plot(lower_bound.index, lower_bound, 'r--', label='下界')
          plt.scatter(anomalies.index, anomalies, color='red', label='异常值', zorder=5)
          plt.title('股价异常值检测(3σ原则)', fontsize=16)
          plt.legend()
          plt.show()
          

          典型应用:2024年3月的异常下跌被成功标记,可能对应重大政策变动或市场恐慌事件。

          Q1:如何处理非交易日数据缺失?

          A:使用resample方法填充非交易日:

          # 生成完整日期范围
          full_dates = pd.date_range(start='2020-11-17', end='2025-11-17', freq='B')  # B表示工作日
          close_prices = close_prices.reindex(full_dates)
          close_prices = close_prices.interpolate(method='linear')  # 线性插值填充
          

          Q2:如何选择合适的可视化周期?

          A:根据分析目标选择:

          • 长期趋势:使用月/季度数据
          • 短期波动:使用日/周数据
          • 高频交易:使用分钟级数据

          Q3:如何保存可视化图表?

          A:Matplotlib保存方法:

          plt.savefig('stock_analysis.png', dpi=300, bbox_inches='tight')
          

          Plotly保存方法:

          fig.write_html('interactive_chart.html')  # 保存为HTML
          fig.write_image("interactive_chart.png", scale=2)  # 需要安装kaleido库
          

          Q4:如何处理多只股票对比分析?

          A:使用子图或合并数据:

          # 获取多只股票数据
          stocks = yf.download(['600519.SS', '000858.SZ', '601318.SH'], 
                              start='2020-11-17', end='2025-11-17')['Close']
          
          # 绘制子图
          fig, axes = plt.subplots(3, 1, figsize=(14, 12))
          for i, code in enumerate(stocks.columns):
              axes[i].plot(stocks.index, stocks
          , label=code) axes[i].set_title(f'
          股价走势') axes[i].legend() plt.tight_layout() plt.show()

          时间序列模型

          • ARIMA模型:statsmodels.tsa.arima.model.ARIMA
          • Prophet模型:from prophet import Prophet

          高级可视化

          • Seaborn热力图:展示相关性矩阵
          • Plotly 3D图表:展示多变量关系

          实战项目

          • 股票预测系统:结合LSTM神经网络
          • 异常检测系统:实时监控股价异常波动

          通过本文的实战案例,读者已掌握从数据获取到高级分析的完整流程。建议从简单案例开始实践,逐步尝试更复杂的模型和可视化技术。时间序列分析的核心在于理解数据背后的时间规律,而Python提供了从基础到高级的完整工具链,帮助我们高效完成这项工作。

          到此这篇关于Python对时间序列进行数据分析与可视化的实战指南的文章就介绍到这了,更多相关Python时间序列内容请搜索风君子博客以前的文章或继续浏览下面的相关文章希望大家以后多多支持风君子博客!

          您可能感兴趣的文章:

          • 利用Python实现时间序列动量策略
          • Python实现时间序列变化点检测功能
          • 使用python进行时间序列预测的流程
          • Python数据可视化中的时间序列图表功能(实例展示其强大功能)
          • python机器学习darts时间序列预测和分析
          • 使用Python进行时间序列分析的8种绘图类型
          • Python时间序列的实现

          站内搜索