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

使用Python获取ETF持仓及配置 调整脚本新增权重(%)列方法咨询

调整后可直接提取权重的完整可运行脚本

import requests
import re
import pandas as pd

keys = ['XLU', 'XLRE']
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:83.0) Gecko/20100101 Firefox/83.0"
}

all_etf_holdings = []

def main(url):
    with requests.Session() as req:
        req.headers.update(headers)
        for etf_ticker in keys:
            r = req.get(url.format(etf_ticker))
            print(f"正在提取: {etf_ticker} 持仓数据")
            # 匹配页面内嵌的完整持仓结构化数据
            raw_data = re.findall(r'etf_holdings\.table_data = (\[.*?\])', r.text)
            if not raw_data:
                print(f"未找到{etf_ticker}的持仓数据")
                continue
            holdings = eval(raw_data[0])
            for hold in holdings:
                ticker_match = re.search(r'etf/([^"]*)', hold[1])
                if ticker_match:
                    # 原始数据下标3的位置就是权重百分比字段
                    all_etf_holdings.append({
                        "ETF代码": etf_ticker,
                        "持仓代码": ticker_match.group(1),
                        "权重(%)": hold[3]
                    })

main("https://www.zacks.com/funds/etf/{}/holding")

# 清洗生成最终DataFrame
holdings_df = pd.DataFrame(all_etf_holdings)
holdings_df = holdings_df[holdings_df['持仓代码'].notna()].reset_index(drop=True)
print(holdings_df)

可选优化:转换权重为数值格式

如果需要对权重做数值计算,可以在生成DataFrame后添加以下代码,去掉百分号转换为浮点型:

holdings_df['权重(%)'] = holdings_df['权重(%)'].str.replace('%', '', regex=False).astype(float)

内容的提问来源于stack exchange,提问作者Andrew Hicks

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 12:54:04