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

如何通过Nasdaq API用Python仅抓取指定的AAPL内幕交易数据

问题

我想通过Nasdaq API抓取AAPL内幕交易数据(对应页面:https://www.nasdaq.com/market-activity/stocks/aapl/insider-activity),只需要date、transaction type、shares traded这三类数据,但当前代码会抓取表中所有内容,请问该如何修改代码?

当前代码:

import requests
import pandas as pd
import json

headers = {
    "accept": "application/json, text/plain, */*",
    "origin": "https://www.nasdaq.com",
    "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.5112.79 Safari/537.36",
}

pd.set_option("display.max_columns", None)
pd.set_option("display.max_colwidth", None)

url = "https://api.nasdaq.com/api/company/AAPL/insider-trades?limit=20&type=ALL&sortColumn=lastDate&sortOrder=DESC"
r = requests.get(url, headers=headers)
df = pd.json_normalize(
    r.json()["data"]["transactionTable"]["table"]["rows"]
)


df.to_json("AAPL22_institutional_table_MRKTVAL.json", indent=4) 

当前输出包含了insider、relation等所有字段,不符合需求。

解决方案

你只需要在生成全量DataFrame后,筛选出目标列,并可根据需要重命名列名来匹配你想要的字段名,最后保存即可。

修改后的代码如下:

import requests
import pandas as pd
import json

headers = {
    "accept": "application/json, text/plain, */*",
    "origin": "https://www.nasdaq.com",
    "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.5112.79 Safari/537.36",
}

pd.set_option("display.max_columns", None)
pd.set_option("display.max_colwidth", None)

url = "https://api.nasdaq.com/api/company/AAPL/insider-trades?limit=20&type=ALL&sortColumn=lastDate&sortOrder=DESC"
r = requests.get(url, headers=headers)
df = pd.json_normalize(
    r.json()["data"]["transactionTable"]["table"]["rows"]
)

# 筛选需要的列,并重命名为你想要的字段名
filtered_df = df[['lastDate', 'transactionType', 'sharesTraded']].rename(columns={
    'lastDate': 'date',
    'transactionType': 'transaction type',
    'sharesTraded': 'shares traded'
})

# 保存筛选后的结果
filtered_df.to_json("AAPL_insider_trades_filtered.json", indent=4) 

修改说明:

  1. 添加filtered_df = df[['lastDate', 'transactionType', 'sharesTraded']]:从全量数据中提取API返回的对应字段(lastDate对应date,transactionType对应transaction type,sharesTraded对应shares traded)
  2. 使用.rename()方法将列名改为你需要的命名格式(可选,但能让输出的JSON键名更符合需求)
  3. 最后保存筛选后的DataFrame,而不是原全量DataFrame

这样输出的JSON就只会包含你需要的三类数据,示例输出如下:

{
    "date": {
        "0": "11\/22\/2022",
        "1": "10\/28\/2022",
        "2": "10\/17\/2022"
    },
    "transaction type": {
        "0": "Sell",
        "1": "Automatic Sell",
        "2": "Automatic Sell"
    },
    "shares traded": {
        "0": "20,200",
        "1": "176,299",
        "2": "8,053"
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 05:35:11