如何通过pandas datareader获取股票一年历史RSI数据?
获取过去一年每日RSI数据的解决方案
雅虎财经的官方接口(包括pdr.get_data_yahoo())并不直接提供历史RSI数据,因为RSI属于技术分析衍生指标,不同使用者可能会用不同的计算参数(比如默认的14周期),所以主流财经数据API一般只提供原始价格数据,让用户自行计算衍生指标。
你可以按以下步骤实现需求:
方法1:用ta库快速计算RSI
ta是专门的技术分析Python库,封装了RSI等常用指标的计算逻辑,步骤如下:
- 先安装
ta库(如果未安装):
pip install ta
- 编写代码获取收盘价并计算RSI:
import pandas_datareader as pdr from datetime import datetime, timedelta import ta # 设置时间范围:过去一年 end_date = datetime.now() start_date = end_date - timedelta(days=365) # 替换成你需要的标的代码 ticker = "AAPL" # 获取每日收盘价数据 close_prices = pdr.get_data_yahoo(ticker, start=start_date, end=end_date)['Close'] # 计算RSI(默认周期14,可通过window参数修改) rsi_indicator = ta.momentum.RSIIndicator(close=close_prices, window=14) daily_rsi = rsi_indicator.rsi() # 查看最近5天的RSI数据 print(daily_rsi.tail())
方法2:手动实现RSI计算
如果不想依赖第三方库,可以自己编写RSI的计算逻辑(基于标准的平滑移动平均算法):
import pandas_datareader as pdr from datetime import datetime, timedelta import pandas as pd def calculate_rsi(close_prices, window=14): # 计算每日价格变动 price_delta = close_prices.diff() # 分离上涨和下跌幅度 gains = price_delta.where(price_delta > 0, 0) losses = -price_delta.where(price_delta < 0, 0) # 计算窗口内的平均上涨/下跌幅度 avg_gain = gains.rolling(window=window).mean() avg_loss = losses.rolling(window=window).mean() # 计算相对强度(RS)和RSI rs = avg_gain / avg_loss rsi = 100 - (100 / (1 + rs)) return rsi # 设置时间范围 end_date = datetime.now() start_date = end_date - timedelta(days=365) # 获取收盘价 ticker = "AAPL" close_prices = pdr.get_data_yahoo(ticker, start=start_date, end=end_date)['Close'] # 计算每日RSI daily_rsi = calculate_rsi(close_prices) print(daily_rsi.tail())
两种方法得到的结果一致,你可以根据需求选择。注意:雅虎财经的免费接口可能存在访问限制,如果遇到请求失败,可以尝试调整请求频率或使用其他备用数据源。
内容的提问来源于stack exchange,提问作者Frank Nowicki
相关产品推荐
相关产品推荐

