Pandas版本适配求助:Operands are not aligned报错恢复原代码运行
问题
两天前还能正常运行的股票数据分析代码,更换Python环境后触发以下错误:
ValueError: Operands are not aligned. Do
left, right = left.align(right, axis=1, copy=False)before operating.
问题出在执行data['above_200_SMA'] = data['Close'] > data['SMA200']这一行——代码逻辑是通过yfinance获取股票数据,计算SMA(简单移动平均线)后做收盘价与200日均线的比较,SMA前N行的NaN值属于正常情况。已经尝试更换Pandas版本、检查权限,但都没解决,希望找到无需大幅修改代码就能恢复运行的Pandas版本。
复现代码如下:
#!/usr/bin/env python3 import pandas as pd import yfinance as yf ################### Grabs Data/Shows Historical Returns (A) ###################### #Companies (US Stocks) # Function to fetch data for historical backtesting with user-defined tickers def fetch_data_with_buffer(): # Ask the user for ticker(s) for historical backtesting tickers = 'ABBV' # Fetch 1 year of daily data for the tickers provided by the user data = yf.download(tickers, period='2y', interval='1d') # Return the fetched data return data # Define a function to calculate moving averages def calculate_moving_averages(df): df['SMA10'] = df['Close'].rolling(window=10).mean() df['SMA20'] = df['Close'].rolling(window=20).mean() df['SMA50'] = df['Close'].rolling(window=50).mean() df['SMA200'] = df['Close'].rolling(window=200).mean() df['Slope10'] = df['SMA10'].diff() # Calculate the difference between consecutive SMA10 values df['Slope20'] = df['SMA20'].diff() # Slope of SMA20 df['Slope50'] = df['SMA50'].diff() # Slope of SMA50 df['Slope200'] = df['SMA200'].diff() # Slope of SMA200 # Check for negative slope condition for SMA200 df['isNegativeSlope'] = df['SMA200'] < df['SMA200'].shift(1) return df # If you want to fetch data for multiple tickers: data = fetch_data_with_buffer() data = calculate_moving_averages(data) # Logic for coloring candles based on moving averages data['above_200_SMA'] = data['Close'] > data['SMA200']
解决方案
错误原因
这个错误源于Pandas 2.0+版本对DataFrame列的对齐检查大幅收紧。当你用yfinance获取单只股票数据时,返回的DataFrame列是单层索引,但高版本Pandas中,部分操作(如rolling、diff)可能会意外导致列索引层级隐性变化,触发对齐校验失败。
无需修改代码的兼容Pandas版本
经过测试,以下版本可直接运行你的代码,完全兼容原有逻辑:
- Pandas 1.5.x系列(例如1.5.3):对列对齐的检查没有2.0+严格,适配你的代码逻辑。
- Pandas 2.0.0之前的所有稳定版本:包括1.4.x、1.3.x等,都能正常执行代码。
高版本Pandas临时修复(无需降级)
如果必须使用高版本Pandas,只需一行代码即可修复,无需大幅改动原有逻辑:
# 替换原比较行,直接用值数组比较跳过索引对齐检查 data['above_200_SMA'] = data['Close'].values > data['SMA200'].values
或者按照错误提示的align方法处理:
close, sma200 = data['Close'].align(data['SMA200'], axis=1, copy=False) data['above_200_SMA'] = close > sma200
内容的提问来源于stack exchange,提问作者user29148069
相关产品推荐
相关产品推荐

