Python 读取 CSV 数据并筛选股票记录
在处理金融或业务数据时,CSV 是最常见的交换格式之一。下面展示如何用 Python 标准库下载 Yahoo Finance 的股票数据,并按日期和成交量进行筛选。
核心逻辑
脚本主要完成三个步骤:
- 下载文件:使用
urllib获取远程 CSV。 - 解析数据:利用
csv模块逐行读取。 - 过滤输出:保留 2016 年之后且成交量大于 5000 万的记录。
注意:原代码基于 Python 2 编写,现代开发建议直接使用 Python 3,以下是适配后的版本。
import urllib.request
import csv
# 定义目标 URL 和本地文件名
target_url = 'http://table.finance.yahoo.com/table.csv?s=000001.sz'
local_file = 'pingan.csv'
output_file = 'pingan_filtered.csv'
# 1. 下载数据
try:
urllib.request.urlretrieve(target_url, local_file)
except Exception as e:
print(f"下载失败:{e}")
exit(1)
# 2. 读取并筛选
with open(local_file, 'r', encoding='utf-8') as rf:
reader = csv.reader(rf)
# 先读取表头
headers = next(reader)
with open(output_file, 'w', encoding='utf-8', newline='') as wf:
writer = csv.writer(wf)
writer.writerow(headers)
for row in reader:
# 确保数据列数足够,避免索引越界
if len(row) > 5:
row[] >= :
:
volume = (row[].replace(, ))
volume >= :
writer.writerow(row)
ValueError:
()

