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

如何使用Python requests模块提取股票指定数据并获取收盘价列

解决方案

方法1:Python原生实现(无需安装第三方依赖)

你可以直接拆分接口返回的CSV格式文本,按需提取对应列的数值,代码示例如下:

import requests
# 优化原url,适配format动态替换股票代码
stock_url = "https://query1.finance.yahoo.com/v7/finance/download/{}"
stock = 'BYND'
params = {
    'range':'6d',
    'interval': '1d',
    'events': 'history'
}
data = requests.get(stock_url.format(stock), params)

# 处理返回的CSV文本
lines = data.text.strip().split('\n')
# 获取表头,定位Close列的索引位置
headers = lines[0].split(',')
close_index = headers.index('Close')
# 提取所有收盘价,转换为浮点型方便后续计算
close_prices = [float(line.split(',')[close_index]) for line in lines[1:]]
# 取最近5天的收盘价(因为拉了6天数据,排除最早的一天即可)
last_5_days_close = close_prices[-5:]

print("所有收盘价:", close_prices)
print("最近5天收盘价:", last_5_days_close)
# 取指定单元格,例如第3行(索引为2)的收盘价
print("第3行收盘价:", close_prices[2])

方法2:使用pandas实现(更灵活,支持复杂单元格操作)

如果需要频繁处理表格类数据,推荐用pandas库,能快速实现按列、按行、按条件筛选数据的需求:

  1. 先安装依赖:
    pip install pandas
  2. 完整代码示例:
import requests
import pandas as pd
from io import StringIO

stock_url = "https://query1.finance.yahoo.com/v7/finance/download/{}"
stock = 'BYND'
params = {
    'range':'6d',
    'interval': '1d',
    'events': 'history'
}
data = requests.get(stock_url.format(stock), params)

# 将CSV文本转为DataFrame表格对象
df = pd.read_csv(StringIO(data.text))
# 直接提取Close列
close_col = df['Close']
print("Close列数据:\n", close_col)
# 提取最近5天收盘价转为列表
last_5_close = df['Close'].tail(5).tolist()
print("最近5天收盘价:", last_5_close)
# 按位置取指定单元格:第4行(索引3)的收盘价
print("第4行收盘价:", df.loc[3, 'Close'])
# 按条件取指定单元格:2021-06-02对应的收盘价
print("2021-06-02收盘价:", df.loc[df['Date'] == '2021-06-02', 'Close'].iloc[0])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 22:54:02