gleamwall 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- gleamwall/__init__.py +50 -0
- gleamwall/client.py +249 -0
- gleamwall-0.1.0.dist-info/METADATA +183 -0
- gleamwall-0.1.0.dist-info/RECORD +6 -0
- gleamwall-0.1.0.dist-info/WHEEL +4 -0
- gleamwall-0.1.0.dist-info/licenses/LICENSE +24 -0
gleamwall/__init__.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""gleamwall —— 昭楹数据接口的 Python 客户端。
|
|
3
|
+
|
|
4
|
+
import gleamwall as gw
|
|
5
|
+
gw.set_key("你的key") # 或设置环境变量 GLEAMWALL_KEY
|
|
6
|
+
df = gw.fund_holdings("巴菲特") # 最新一季全部持仓,pandas DataFrame
|
|
7
|
+
|
|
8
|
+
文档:https://gleamwall.com/api-docs
|
|
9
|
+
"""
|
|
10
|
+
__version__ = "0.1.0"
|
|
11
|
+
|
|
12
|
+
from .client import Client, GleamWallError, DEFAULT_BASE_URL # noqa: E402
|
|
13
|
+
|
|
14
|
+
_default = None
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def set_key(key, base_url=None):
|
|
18
|
+
"""设置默认 key,之后 gw.xxx() 都用它。"""
|
|
19
|
+
global _default
|
|
20
|
+
_default = Client(key, base_url=base_url)
|
|
21
|
+
return _default
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def client():
|
|
25
|
+
"""返回默认客户端(没设置过就读环境变量 GLEAMWALL_KEY)。"""
|
|
26
|
+
global _default
|
|
27
|
+
if _default is None:
|
|
28
|
+
_default = Client()
|
|
29
|
+
return _default
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _wrap(name):
|
|
33
|
+
meth = getattr(Client, name)
|
|
34
|
+
|
|
35
|
+
def f(*args, **kwargs):
|
|
36
|
+
return getattr(client(), name)(*args, **kwargs)
|
|
37
|
+
|
|
38
|
+
f.__name__ = name
|
|
39
|
+
f.__doc__ = meth.__doc__
|
|
40
|
+
return f
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
_API = ["periods", "search", "superinvestors", "resolve_cik", "fund_holdings", "fund_history",
|
|
44
|
+
"stock_holders", "stock_history", "rankings", "insider", "insider_buys", "insider_clusters",
|
|
45
|
+
"financials", "financials_bulk", "factors", "valuation_quarterly"]
|
|
46
|
+
|
|
47
|
+
for _n in _API:
|
|
48
|
+
globals()[_n] = _wrap(_n)
|
|
49
|
+
|
|
50
|
+
__all__ = ["Client", "GleamWallError", "set_key", "client", "__version__"] + _API
|
gleamwall/client.py
ADDED
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""昭楹数据接口的 Python 客户端。
|
|
3
|
+
|
|
4
|
+
每个函数调一次网站的数据接口,把返回里的主表转成 pandas DataFrame,
|
|
5
|
+
日期列转成 datetime,接口返回里的其余信息放在 ``df.attrs`` 里。
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import os
|
|
10
|
+
import re
|
|
11
|
+
from typing import Any, Dict, Iterable, Optional, Union
|
|
12
|
+
|
|
13
|
+
import pandas as pd
|
|
14
|
+
import requests
|
|
15
|
+
|
|
16
|
+
__version__ = "0.1.0" # 与 __init__ 保持一致
|
|
17
|
+
|
|
18
|
+
DEFAULT_BASE_URL = "https://gleamwall.com/api/v1"
|
|
19
|
+
ENV_KEY = "GLEAMWALL_KEY"
|
|
20
|
+
ENV_BASE = "GLEAMWALL_BASE_URL"
|
|
21
|
+
|
|
22
|
+
# 这些列转成 pandas 日期
|
|
23
|
+
_DATE_COLS = {
|
|
24
|
+
"period", "period_end", "period_start", "filed", "first_filed", "filing_date", "tx_date",
|
|
25
|
+
"latest_period", "last_period", "available_date", "start_date", "end_date", "last_filing",
|
|
26
|
+
"fin_period_end", "fin_available_date",
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class GleamWallError(Exception):
|
|
31
|
+
"""接口返回了错误(没带 key、key 无效、次数用完、参数不对、找不到等)。
|
|
32
|
+
|
|
33
|
+
属性 ``status`` 是 HTTP 状态码,``message`` 是网站给的错误说明。
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
def __init__(self, status: int, message: str, url: str = ""):
|
|
37
|
+
self.status = status
|
|
38
|
+
self.message = message
|
|
39
|
+
self.url = url
|
|
40
|
+
hint = {
|
|
41
|
+
401: "没有带 key 或 key 无效。在 gleamwall.com 我的账户 → 数据接口 生成 key,"
|
|
42
|
+
"然后 gw.set_key(\"你的key\") 或设置环境变量 GLEAMWALL_KEY。",
|
|
43
|
+
429: "今天的调用次数用完了,北京时间 0 点重置。",
|
|
44
|
+
}.get(status, "")
|
|
45
|
+
super().__init__("%s: %s%s" % (status, message, ("\n" + hint) if hint else ""))
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _to_frame(rows: Any, attrs: Dict[str, Any]) -> pd.DataFrame:
|
|
49
|
+
df = pd.DataFrame(rows if rows else [])
|
|
50
|
+
for c in df.columns:
|
|
51
|
+
if c in _DATE_COLS and not pd.api.types.is_datetime64_any_dtype(df[c]):
|
|
52
|
+
df[c] = pd.to_datetime(df[c], errors="coerce")
|
|
53
|
+
df.attrs.update(attrs)
|
|
54
|
+
return df
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _is_cik(x: Any) -> bool:
|
|
58
|
+
return isinstance(x, int) or (isinstance(x, str) and x.strip().isdigit())
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _date(x: Any) -> Optional[str]:
|
|
62
|
+
if x is None:
|
|
63
|
+
return None
|
|
64
|
+
if hasattr(x, "strftime"):
|
|
65
|
+
return x.strftime("%Y-%m-%d")
|
|
66
|
+
s = str(x).strip()
|
|
67
|
+
if re.fullmatch(r"\d{8}", s): # 20260630
|
|
68
|
+
s = "%s-%s-%s" % (s[:4], s[4:6], s[6:])
|
|
69
|
+
return s
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _ticker(t: str) -> str:
|
|
73
|
+
return str(t).strip().upper()
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _join(x: Union[str, Iterable[str], None]) -> Optional[str]:
|
|
77
|
+
if x is None:
|
|
78
|
+
return None
|
|
79
|
+
if isinstance(x, str):
|
|
80
|
+
return x
|
|
81
|
+
return ",".join(str(i).strip() for i in x)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class Client:
|
|
85
|
+
"""数据接口客户端。
|
|
86
|
+
|
|
87
|
+
>>> import gleamwall as gw
|
|
88
|
+
>>> api = gw.Client("你的key")
|
|
89
|
+
>>> api.fund_holdings("巴菲特").head()
|
|
90
|
+
|
|
91
|
+
key 不传时读环境变量 ``GLEAMWALL_KEY``。
|
|
92
|
+
"""
|
|
93
|
+
|
|
94
|
+
def __init__(self, key: Optional[str] = None, base_url: Optional[str] = None,
|
|
95
|
+
timeout: float = 60, session: Optional[requests.Session] = None):
|
|
96
|
+
self.key = key or os.environ.get(ENV_KEY) or None
|
|
97
|
+
self.base_url = (base_url or os.environ.get(ENV_BASE) or DEFAULT_BASE_URL).rstrip("/")
|
|
98
|
+
self.timeout = timeout
|
|
99
|
+
self.session = session or requests.Session()
|
|
100
|
+
self.session.headers["User-Agent"] = ("gleamwall-python/%s" % __version__)
|
|
101
|
+
self.rate_limit_remaining: Optional[int] = None
|
|
102
|
+
self._superinvestors: Optional[pd.DataFrame] = None
|
|
103
|
+
|
|
104
|
+
# ------------------------------------------------------------------ 底层
|
|
105
|
+
def get(self, path: str, **params: Any) -> Dict[str, Any]:
|
|
106
|
+
"""调一个接口,返回原始 JSON(dict)。path 例如 ``"/funds/1067983/holdings"``。"""
|
|
107
|
+
if not self.key:
|
|
108
|
+
raise GleamWallError(401, "缺少 key")
|
|
109
|
+
params = {k: v for k, v in params.items() if v is not None}
|
|
110
|
+
url = self.base_url + ("" if path.startswith("/") else "/") + path
|
|
111
|
+
r = self.session.get(url, params=params, headers={"X-API-Key": self.key}, timeout=self.timeout)
|
|
112
|
+
rem = r.headers.get("X-RateLimit-Remaining")
|
|
113
|
+
if rem is not None:
|
|
114
|
+
try:
|
|
115
|
+
self.rate_limit_remaining = int(rem)
|
|
116
|
+
except ValueError:
|
|
117
|
+
pass
|
|
118
|
+
if r.status_code != 200:
|
|
119
|
+
try:
|
|
120
|
+
js = r.json()
|
|
121
|
+
msg = js.get("error") or js.get("detail") or r.text
|
|
122
|
+
except ValueError:
|
|
123
|
+
msg = r.text[:300]
|
|
124
|
+
raise GleamWallError(r.status_code, str(msg), r.url)
|
|
125
|
+
return r.json()
|
|
126
|
+
|
|
127
|
+
def _table(self, path: str, rows: str, **params: Any) -> pd.DataFrame:
|
|
128
|
+
js = self.get(path, **params)
|
|
129
|
+
attrs = {k: v for k, v in js.items() if k != rows}
|
|
130
|
+
return _to_frame(js.get(rows), attrs)
|
|
131
|
+
|
|
132
|
+
# ------------------------------------------------------------------ 13F 机构持仓
|
|
133
|
+
def periods(self) -> list:
|
|
134
|
+
"""能查询的 13F 季度(季末日期字符串),从新到旧。"""
|
|
135
|
+
return list(self.get("/periods").get("periods") or [])
|
|
136
|
+
|
|
137
|
+
def search(self, q: str) -> pd.DataFrame:
|
|
138
|
+
"""按名称或代码搜机构。返回机构表;匹配的证券表在 ``df.attrs["securities"]``(DataFrame)。"""
|
|
139
|
+
js = self.get("/search", q=q)
|
|
140
|
+
df = _to_frame(js.get("managers"), {})
|
|
141
|
+
if df.empty and re.search(r"[\u4e00-\u9fff]", q):
|
|
142
|
+
# 搜索接口只认英文名;中文先在知名投资人的中文简称里找
|
|
143
|
+
si = self._superinvestors if self._superinvestors is not None else self.superinvestors()
|
|
144
|
+
if len(si) and "label_zh" in si:
|
|
145
|
+
hit = si[si["label_zh"].fillna("").str.contains(q.strip(), regex=False)]
|
|
146
|
+
cols = [c for c in ("cik", "manager_name", "label_zh", "latest_aum") if c in hit]
|
|
147
|
+
df = hit[cols].reset_index(drop=True)
|
|
148
|
+
df.attrs["securities"] = _to_frame(js.get("securities"), {})
|
|
149
|
+
return df
|
|
150
|
+
|
|
151
|
+
def superinvestors(self) -> pd.DataFrame:
|
|
152
|
+
"""网站精选的知名投资人(巴菲特、阿克曼、伯里等)最新一季概况,一行一家。"""
|
|
153
|
+
df = self._table("/superinvestors", "rows")
|
|
154
|
+
self._superinvestors = df
|
|
155
|
+
return df
|
|
156
|
+
|
|
157
|
+
def resolve_cik(self, fund: Union[int, str]) -> int:
|
|
158
|
+
"""把机构写法统一成 CIK:数字原样返回;中文简称(巴菲特、段永平)或英文名先在知名投资人里找,
|
|
159
|
+
找不到再用搜索接口取第一条。名字解析会多用 1–2 次调用。"""
|
|
160
|
+
if _is_cik(fund):
|
|
161
|
+
return int(fund)
|
|
162
|
+
name = str(fund).strip().lower()
|
|
163
|
+
si = self._superinvestors if self._superinvestors is not None else self.superinvestors()
|
|
164
|
+
if len(si):
|
|
165
|
+
for col in ("label_zh", "manager_name"):
|
|
166
|
+
if col in si:
|
|
167
|
+
hit = si[si[col].fillna("").str.lower().str.contains(name, regex=False)]
|
|
168
|
+
if len(hit):
|
|
169
|
+
return int(hit.iloc[0]["cik"])
|
|
170
|
+
found = self.search(str(fund))
|
|
171
|
+
if len(found):
|
|
172
|
+
return int(found.iloc[0]["cik"])
|
|
173
|
+
raise GleamWallError(404, "找不到机构:%s" % fund)
|
|
174
|
+
|
|
175
|
+
def fund_holdings(self, fund: Union[int, str], period: Any = None) -> pd.DataFrame:
|
|
176
|
+
"""某家机构某季的全部 13F 持仓(含加减仓、估算买卖金额)。
|
|
177
|
+
|
|
178
|
+
fund: CIK(1067983)、中文简称("巴菲特")或英文名("berkshire")。
|
|
179
|
+
period: 季末日期,如 "2026-06-30";不填为最新一季。
|
|
180
|
+
"""
|
|
181
|
+
return self._table("/funds/%d/holdings" % self.resolve_cik(fund), "holdings", period=_date(period))
|
|
182
|
+
|
|
183
|
+
def fund_history(self, fund: Union[int, str]) -> pd.DataFrame:
|
|
184
|
+
"""某家机构每季的申报总市值、持仓数、新建仓数和清仓数。"""
|
|
185
|
+
return self._table("/funds/%d/history" % self.resolve_cik(fund), "history")
|
|
186
|
+
|
|
187
|
+
def stock_holders(self, ticker: str, period: Any = None) -> pd.DataFrame:
|
|
188
|
+
"""某只股票某季的全部 13F 持有机构,每行一家,带加减仓。"""
|
|
189
|
+
return self._table("/stocks/%s/holders" % _ticker(ticker), "holders", period=_date(period))
|
|
190
|
+
|
|
191
|
+
def stock_history(self, ticker: str) -> pd.DataFrame:
|
|
192
|
+
"""某只股票每季的持有机构数、机构合计持股、加减仓家数和净买入金额。"""
|
|
193
|
+
return self._table("/stocks/%s/history" % _ticker(ticker), "history")
|
|
194
|
+
|
|
195
|
+
def rankings(self, kind: str = "buys", period: Any = None, limit: int = 100) -> pd.DataFrame:
|
|
196
|
+
"""本季机构买卖排行。kind:buys 净买入、sells 净卖出、popular 持有机构最多、listings 新上市/分拆。"""
|
|
197
|
+
if kind not in ("buys", "sells", "popular", "listings"):
|
|
198
|
+
raise ValueError("kind 只能是 buys / sells / popular / listings")
|
|
199
|
+
return self._table("/rankings/%s" % kind, "rows", period=_date(period), limit=limit)
|
|
200
|
+
|
|
201
|
+
# ------------------------------------------------------------------ 内部人交易
|
|
202
|
+
def insider(self, ticker: Optional[str] = None, code: str = "PS", since: Any = None,
|
|
203
|
+
limit: int = 100) -> pd.DataFrame:
|
|
204
|
+
"""内部人(董事、高管、10% 以上股东)交易明细,按申报日从新到旧。
|
|
205
|
+
|
|
206
|
+
code:PS 公开市场买入+卖出(默认)、P 只要买入、S 只要卖出、ALL 全部,或 "M,F" 这样的交易代码。
|
|
207
|
+
limit 最多 1000。
|
|
208
|
+
"""
|
|
209
|
+
return self._table("/insider", "transactions", ticker=_ticker(ticker) if ticker else None,
|
|
210
|
+
code=code, since=_date(since), limit=limit)
|
|
211
|
+
|
|
212
|
+
def insider_buys(self, days: int = 30, limit: int = 100) -> pd.DataFrame:
|
|
213
|
+
"""最近 7 / 30 / 90 天金额最大的内部人公开市场买入,一份申报一行。"""
|
|
214
|
+
return self._table("/insider/buys", "rows", days=days, limit=limit)
|
|
215
|
+
|
|
216
|
+
def insider_clusters(self) -> pd.DataFrame:
|
|
217
|
+
"""近 90 天里 14 天之内有 3 位以上内部人买入的股票。"""
|
|
218
|
+
return self._table("/insider/clusters", "rows")
|
|
219
|
+
|
|
220
|
+
# ------------------------------------------------------------------ 财报
|
|
221
|
+
def financials(self, ticker: str, freq: str = "annual", as_of: Any = None) -> pd.DataFrame:
|
|
222
|
+
"""一家公司的三张报表(47 个科目),一期一行。
|
|
223
|
+
|
|
224
|
+
freq:annual 年报、quarterly 单季。as_of:点时日期,只返回那天之前已公布的首次数字(回测用),
|
|
225
|
+
这时返回长表。公司信息在 ``df.attrs["company"]``。
|
|
226
|
+
"""
|
|
227
|
+
if freq not in ("annual", "quarterly"):
|
|
228
|
+
raise ValueError("freq 只能是 annual 或 quarterly")
|
|
229
|
+
rows = "point_in_time" if as_of else "periods"
|
|
230
|
+
return self._table("/stocks/%s/financials" % _ticker(ticker), rows, freq=freq, as_of=_date(as_of))
|
|
231
|
+
|
|
232
|
+
def financials_bulk(self, tickers: Union[str, Iterable[str]], metrics: Union[str, Iterable[str], None] = None,
|
|
233
|
+
freq: str = "annual", as_of: Any = None) -> pd.DataFrame:
|
|
234
|
+
"""一次取最多 50 家公司的指定科目,拼成一张长表(ticker × 期)。"""
|
|
235
|
+
if freq not in ("annual", "quarterly"):
|
|
236
|
+
raise ValueError("freq 只能是 annual 或 quarterly")
|
|
237
|
+
t = _join(tickers)
|
|
238
|
+
if t and len([x for x in t.split(",") if x.strip()]) > 50:
|
|
239
|
+
raise ValueError("一次最多 50 个代码")
|
|
240
|
+
return self._table("/financials/bulk", "rows", tickers=t.upper() if t else t,
|
|
241
|
+
metrics=_join(metrics), freq=freq, as_of=_date(as_of))
|
|
242
|
+
|
|
243
|
+
def factors(self, ticker: str) -> pd.DataFrame:
|
|
244
|
+
"""逐季 22 个财务因子(成长、利润率、ROE/ROA/ROIC、杠杆、派息等)和 TTM 营收、净利、现金流。"""
|
|
245
|
+
return self._table("/stocks/%s/factors" % _ticker(ticker), "factors")
|
|
246
|
+
|
|
247
|
+
def valuation_quarterly(self, ticker: str) -> pd.DataFrame:
|
|
248
|
+
"""每个季末的价格、市值和 PE / PS / PB / EV-EBITDA(价格由机构持仓申报推算)。"""
|
|
249
|
+
return self._table("/stocks/%s/valuation_quarterly" % _ticker(ticker), "valuation_quarterly")
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: gleamwall
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: 昭楹 GleamWall 数据接口 Python 客户端:13F 机构持仓、内部人交易、财报和因子,取来就是 DataFrame
|
|
5
|
+
Project-URL: Homepage, https://gleamwall.com
|
|
6
|
+
Project-URL: Documentation, https://gleamwall.com/api-docs
|
|
7
|
+
Author: GleamWall
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: 13F,Form 4,factors,financial statements,insider trading,institutional holdings,pandas,quant,机构持仓,量化
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Intended Audience :: Financial and Insurance Industry
|
|
13
|
+
Classifier: Natural Language :: Chinese (Simplified)
|
|
14
|
+
Classifier: Natural Language :: English
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Topic :: Office/Business :: Financial :: Investment
|
|
18
|
+
Requires-Python: >=3.8
|
|
19
|
+
Requires-Dist: pandas>=1.0
|
|
20
|
+
Requires-Dist: requests>=2.20
|
|
21
|
+
Provides-Extra: test
|
|
22
|
+
Requires-Dist: pytest>=7; extra == 'test'
|
|
23
|
+
Requires-Dist: responses>=0.23; extra == 'test'
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
|
|
26
|
+
# gleamwall
|
|
27
|
+
|
|
28
|
+
昭楹 GleamWall 数据接口的官方 Python 客户端。一行代码取到加工好的机构持仓、内部人交易、财报和财务因子,返回就是 pandas DataFrame。
|
|
29
|
+
|
|
30
|
+
[接口文档](https://gleamwall.com/api-docs) · [English](#english)
|
|
31
|
+
|
|
32
|
+
```python
|
|
33
|
+
import gleamwall as gw
|
|
34
|
+
|
|
35
|
+
gw.set_key("你的key")
|
|
36
|
+
gw.fund_holdings("巴菲特").head()
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
```
|
|
40
|
+
ticker issuer value weight action ...
|
|
41
|
+
0 AAPL APPLE INC 7.590119e+10 0.249514 HOLD ...
|
|
42
|
+
1 AXP AMERICAN EXPRESS CO ...
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
## 为什么用它
|
|
46
|
+
|
|
47
|
+
- **取来就能用**:证券代码已经对好,换代码、拆股、迟报和明显填错的申报已经处理,每季的加仓、减仓、新建仓、清仓和估算买卖金额已经算好。
|
|
48
|
+
- **中文友好**:机构可以直接写中文简称(巴菲特、段永平、阿克曼),文档和报错都是中文。
|
|
49
|
+
- **DataFrame 直出**:日期列已经转成 `datetime`,接口返回的其余信息在 `df.attrs` 里。
|
|
50
|
+
- **点时财报**:`financials(..., as_of=...)` 只给那天之前已经公布的首次数字,回测不偷看未来。
|
|
51
|
+
|
|
52
|
+
## 安装
|
|
53
|
+
|
|
54
|
+
```bash
|
|
55
|
+
pip install gleamwall
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
需要 Python 3.8 及以上,依赖只有 `requests` 和 `pandas`。
|
|
59
|
+
|
|
60
|
+
## 拿 key
|
|
61
|
+
|
|
62
|
+
登录 [gleamwall.com](https://gleamwall.com),进「我的账户 → 数据接口」生成 key。两种用法任选:
|
|
63
|
+
|
|
64
|
+
```python
|
|
65
|
+
import gleamwall as gw
|
|
66
|
+
gw.set_key("你的key")
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
或者设置环境变量,代码里就不用写 key:
|
|
70
|
+
|
|
71
|
+
```bash
|
|
72
|
+
# macOS / Linux
|
|
73
|
+
export GLEAMWALL_KEY=你的key
|
|
74
|
+
# Windows PowerShell
|
|
75
|
+
setx GLEAMWALL_KEY 你的key
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
## 能取什么
|
|
79
|
+
|
|
80
|
+
| 函数 | 内容 |
|
|
81
|
+
|---|---|
|
|
82
|
+
| `periods()` | 能查询的季度 |
|
|
83
|
+
| `search(q)` | 按名称或代码搜机构(匹配的证券在 `df.attrs["securities"]`) |
|
|
84
|
+
| `superinvestors()` | 知名投资人最新一季概况:规模、集中度、前五大、本季买卖、换手率 |
|
|
85
|
+
| `fund_holdings(fund, period=None)` | 某家机构某季全部持仓,带加减仓和估算买卖金额 |
|
|
86
|
+
| `fund_history(fund)` | 某家机构每季的总市值、持仓数、新建仓和清仓数 |
|
|
87
|
+
| `stock_holders(ticker, period=None)` | 某只股票某季的全部持有机构 |
|
|
88
|
+
| `stock_history(ticker)` | 某只股票每季的持有机构数、合计持股、净买入 |
|
|
89
|
+
| `rankings(kind, period=None, limit=100)` | 本季机构买卖排行:`buys` `sells` `popular` `listings` |
|
|
90
|
+
| `insider(ticker=None, code="PS", since=None, limit=100)` | 内部人交易明细 |
|
|
91
|
+
| `insider_buys(days=30, limit=100)` | 最近 7 / 30 / 90 天金额最大的内部人买入 |
|
|
92
|
+
| `insider_clusters()` | 14 天内 3 位以上内部人一起买入的股票 |
|
|
93
|
+
| `financials(ticker, freq="annual", as_of=None)` | 三张报表 47 个科目,可取点时数据 |
|
|
94
|
+
| `financials_bulk(tickers, metrics=None, freq="annual", as_of=None)` | 一次取最多 50 家公司的指定科目 |
|
|
95
|
+
| `factors(ticker)` | 逐季 22 个财务因子和 TTM 营收、净利、现金流 |
|
|
96
|
+
| `valuation_quarterly(ticker)` | 季末价格、市值、PE / PS / PB / EV-EBITDA |
|
|
97
|
+
|
|
98
|
+
`fund` 可以写 CIK(`1067983`)、中文简称(`"巴菲特"`)或英文名(`"berkshire"`)。写名字时会先查一次知名投资人和搜索接口,多用一两次调用。每个字段的含义见 [接口文档](https://gleamwall.com/api-docs)。
|
|
99
|
+
|
|
100
|
+
## 例子
|
|
101
|
+
|
|
102
|
+
**巴菲特这季做了什么**
|
|
103
|
+
|
|
104
|
+
```python
|
|
105
|
+
df = gw.fund_holdings("巴菲特")
|
|
106
|
+
moves = df[df.action.isin(["NEW", "ADD", "REDUCE", "SOLD_OUT"])]
|
|
107
|
+
print(moves.sort_values("flow_value")[["ticker", "action", "change_pct", "flow_value"]])
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
**这季机构抢着买什么**
|
|
111
|
+
|
|
112
|
+
```python
|
|
113
|
+
buys = gw.rankings("buys", limit=20)
|
|
114
|
+
pop = gw.rankings("popular", limit=100)
|
|
115
|
+
print(buys.merge(pop[["ticker", "n_holders"]], on="ticker", how="left"))
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
**内部人集群买入,配上财务因子**
|
|
119
|
+
|
|
120
|
+
```python
|
|
121
|
+
import pandas as pd
|
|
122
|
+
|
|
123
|
+
cl = gw.insider_clusters().head(10)
|
|
124
|
+
rows = []
|
|
125
|
+
for t in cl.ticker:
|
|
126
|
+
f = gw.factors(t)
|
|
127
|
+
if len(f):
|
|
128
|
+
rows.append(f.sort_values("period_end").iloc[-1].rename(t)) # 最近一季
|
|
129
|
+
f = pd.DataFrame(rows).rename_axis("ticker").reset_index()
|
|
130
|
+
print(cl.merge(f, on="ticker")[["ticker", "n_insiders", "value", "roe", "gross_margin"]])
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
**一篮子公司的营收对比**
|
|
134
|
+
|
|
135
|
+
```python
|
|
136
|
+
df = gw.financials_bulk(["AAPL", "MSFT", "NVDA", "GOOGL"], metrics=["revenue", "net_income"])
|
|
137
|
+
print(df.pivot_table(index="fiscal_year", columns="ticker", values="revenue"))
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
**回测用的点时财报**
|
|
141
|
+
|
|
142
|
+
```python
|
|
143
|
+
pit = gw.financials("AAPL", as_of="2024-06-30") # 只含 2024-06-30 以前公布的首次数字
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
## 多个 key 或自定义设置
|
|
147
|
+
|
|
148
|
+
```python
|
|
149
|
+
api = gw.Client("另一个key", timeout=30)
|
|
150
|
+
api.stock_holders("NVDA")
|
|
151
|
+
print(api.rate_limit_remaining) # 今天剩余调用次数(接口返回时更新)
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
`api.get(path, **params)` 可以直接调任何接口,拿到原始 JSON。
|
|
155
|
+
|
|
156
|
+
## 报错
|
|
157
|
+
|
|
158
|
+
接口出错时抛 `gw.GleamWallError`,带 `status`(HTTP 状态码)和 `message`:
|
|
159
|
+
|
|
160
|
+
| 状态码 | 意思 |
|
|
161
|
+
|---|---|
|
|
162
|
+
| 401 | 没带 key 或 key 无效 |
|
|
163
|
+
| 404 | 找不到这家机构或这个代码 |
|
|
164
|
+
| 429 | 今天的次数用完,北京时间 0 点重置 |
|
|
165
|
+
|
|
166
|
+
## 许可
|
|
167
|
+
|
|
168
|
+
客户端代码用 MIT 许可。接口返回的数据受 [gleamwall.com 用户协议](https://gleamwall.com/terms) 约束,仅限个人研究使用,不得转售或公开再分发。数据仅供参考,不构成投资建议。
|
|
169
|
+
|
|
170
|
+
## English
|
|
171
|
+
|
|
172
|
+
`gleamwall` is the official Python client for the GleamWall data API: processed 13F institutional holdings, insider trades, financial statements and factors, returned as pandas DataFrames.
|
|
173
|
+
|
|
174
|
+
```python
|
|
175
|
+
import gleamwall as gw
|
|
176
|
+
gw.set_key("your-key") # or set GLEAMWALL_KEY
|
|
177
|
+
gw.fund_holdings("berkshire") # latest 13F portfolio with quarter-on-quarter changes
|
|
178
|
+
gw.stock_holders("NVDA") # every institutional holder of a stock
|
|
179
|
+
gw.insider_buys(days=30) # largest open-market insider purchases
|
|
180
|
+
gw.financials("AAPL", as_of="2024-06-30") # point-in-time statements for backtests
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
Get a key at gleamwall.com under My account → Data API. Field definitions are in the [API docs](https://gleamwall.com/api-docs). The client code is MIT-licensed; data is subject to the [terms of use](https://gleamwall.com/terms), for personal research only, and is not investment advice.
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
gleamwall/__init__.py,sha256=qq4sDfBfkm9UM_S5ggwl5v662aSMP5g5tULljp7L2Po,1415
|
|
2
|
+
gleamwall/client.py,sha256=2SdX9N8SjXi3aHm1dy_2oURKi7XsWjnqDoDxr8TU4fA,11988
|
|
3
|
+
gleamwall-0.1.0.dist-info/METADATA,sha256=LGzShayWEJaVTrvDxwAwMVE2TjgIxbc-2EuNHFC3hrs,7325
|
|
4
|
+
gleamwall-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
5
|
+
gleamwall-0.1.0.dist-info/licenses/LICENSE,sha256=xGyqqwzk6woD-Fj_EedyDK7LCw_gX6kDpZ7b2YOKqRM,1254
|
|
6
|
+
gleamwall-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Shanghai Zhaoying Information Technology Co., Ltd.
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
22
|
+
|
|
23
|
+
Note: this license covers the client code only. Data returned by the GleamWall
|
|
24
|
+
API is subject to the terms of use at https://gleamwall.com/terms.
|