Use Chinese natural language via Python fromTonghuashun WenCaiquery A-shares and other market data.
⚠️ Requires Cookie: a valid Cookie for the WenCai website must be provided. See below for how to obtain it.
Environment Requirements
- Python 3.7+
- Node.js v16+(pywencai internally executes JS code)
- pip package manager
Installation
pip install pywencai --upgrade
How to Obtain Cookie
If the environment variable WENCAI_COOKIEexists, it can be used directly; if the call fails, obtain it again as follows:
- Open in your browser https://www.iwencai.com and log in.
- Press F12 to open developer tools → switch to the Network tab.
- Perform any query on the WenCai page.
- Find the request sent to
iwencai.comand copy from the request headers theCookievalue. - Use this string as the
cookieparameter.
Cookie Management
Prefer using environment variables or files to manage the Cookie, avoiding hardcoding:
import os
import pywencai
# 方法1:从环境变量读取Cookie(推荐)
cookie = os.environ.get('WENCAI_COOKIE', '')
# 方法2:从文件读取Cookie
def load_cookie(path='~/.wencai_cookie'):
path = os.path.expanduser(path)
if os.path.exists(path):
with open(path) as f:
return f.read().strip()
return ''
# 方法3:封装查询函数,统一管理Cookie和错误处理
def query(q, **kwargs):
cookie = load_cookie()
try:
return pywencai.get(
query=q, cookie=cookie,
no_detail=True, retry=3, sleep=1,
**kwargs
)
except Exception as e:
print(f"查询失败: {e}")
return None
# 使用
df = query('今日涨停的股票')
Basic Usage
import pywencai
# 查询今日涨幅前10的股票,需要有效cookie
res = pywencai.get(query='今日涨幅前10', cookie='your_cookie_here')
print(res)
API Reference:pywencai.get(**kwargs)
Required Parameters
- query — Chinese natural language query string, e.g.
'今日涨停股票'、'市盈率小于20的股票' - cookie — Cookie string obtained from the WenCai website (required)
Optional Parameters
- sort_key — sort field name, e.g.
'退市@退市日期' - sort_order — sort direction:
'asc'(ascending) or'desc'(descending) - page — page number (default:
1) - perpage — number of results per page (default and maximum:
100) - loop — set to
Trueto get all pages; or set to an integernto get the first n pages - query_type — query category (default:
'stock'), optional values:
| Value | Description |
|---|---|
stock |
A-share stocks |
zhishu |
Indices |
fund |
Funds |
hkstock |
Hong Kong stocks |
usstock |
US stocks |
threeboard |
New Third Board |
conbond |
Convertible bonds |
insurance |
Insurance |
futures |
Futures |
lccp |
Wealth management products |
- retry — number of retries on failure (default:
10) - sleep — delay in seconds between paginated requests (default:
0) - log — set to
Trueprint logs in the console - pro — set to
Trueuse the paid version (requires the corresponding cookie) - no_detail — set to
Truealways returnDataFrameorNone(do not return dict) - find — list of preferred stock codes, e.g.
['600519', '000010'] - request_params — passed to
requestsadditional parameters, e.g.{'proxies': proxies}
Return Values
- List-type queries → return
pandas.DataFrame - Detail-type queries → return
dict(may contain text and DataFrame)
Usage Examples
Query by market type
import pywencai
# A股股票(默认)
res = pywencai.get(query='今日涨停的股票', cookie=cookie)
# 指数数据
res = pywencai.get(query='上证指数近5日涨跌幅', query_type='zhishu', cookie=cookie)
# 基金数据
res = pywencai.get(query='近一年收益率最高的前20只基金', query_type='fund', cookie=cookie)
# 可转债数据
res = pywencai.get(query='可转债溢价率小于10%', query_type='conbond', cookie=cookie)
# 港股数据
res = pywencai.get(query='港股市值最大的前20只股票', query_type='hkstock', cookie=cookie)
Fundamental stock selection
# 估值筛选
res = pywencai.get(query='市盈率小于20的股票', cookie=cookie)
res = pywencai.get(query='市盈率小于10且市净率小于1的股票', cookie=cookie)
# 财务指标
res = pywencai.get(query='ROE大于15%且营收同比增长率大于20%的股票', cookie=cookie)
# 多条件综合筛选
res = pywencai.get(query='市盈率小于20且营收同比增长大于30%且机构持仓比例大于10%的股票', cookie=cookie)
res = pywencai.get(query='今日站上20日均线且市盈率小于30且ROE大于10%的股票', cookie=cookie)
Technical and capital flow
# 技术信号
res = pywencai.get(query='今日MACD金叉的股票', cookie=cookie)
res = pywencai.get(query='KDJ的J值小于0的股票', cookie=cookie)
res = pywencai.get(query='今日成交量是5日均量2倍以上且涨幅大于5%的股票', cookie=cookie)
# 资金流向
res = pywencai.get(query='今日主力资金净流入前20的股票', cookie=cookie)
res = pywencai.get(query='北向资金持股比例最高的前20只股票', cookie=cookie)
Sorting, pagination, and proxy
# 按指定字段排序
res = pywencai.get(
query='退市股票',
sort_key='退市@退市日期',
sort_order='asc',
cookie=cookie
)
# 自动分页获取全部数据(使用代理)
proxies = {'http': 'http://proxy:8080', 'https': 'http://proxy:8080'}
res = pywencai.get(
query='昨日涨幅',
loop=True,
log=True,
cookie=cookie,
request_params={'proxies': proxies}
)
Historical data query
# 指定日期
res = pywencai.get(query='2024年1月2日涨幅前10的股票', cookie=cookie)
# 日期范围
res = pywencai.get(query='2024年上半年涨幅最大的前20只股票', cookie=cookie)
Complete example: multi-strategy automated stock selection and export
import pywencai
import pandas as pd
import time
cookie = os.environ.get('WENCAI_COOKIE', '')
# 定义多个筛选策略
strategies = {
"低估值高分红": "市盈率小于15且股息率大于3%的股票",
"高成长": "营收同比增长大于30%且净利润同比增长大于30%的股票",
"技术突破": "今日放量突破20日均线且涨幅大于3%的股票",
"机构关注": "近一个月机构调研次数大于3次的股票",
"北向资金": "北向资金今日净买入前20的股票",
}
results = {}
for name, query in strategies.items():
try:
res = pywencai.get(query=query, cookie=cookie, no_detail=True)
if res is not None and not res.empty:
results[name] = res
print(f"策略 [{name}] 选出 {len(res)} 只股票")
else:
print(f"策略 [{name}] 无结果")
except Exception as e:
print(f"策略 [{name}] 查询失败: {e}")
time.sleep(2) # 每次查询间隔2秒,避免被封禁
# 保存结果到Excel(每个策略一个工作表)
if results:
with pd.ExcelWriter("选股结果.xlsx") as writer:
for name, df in results.items():
df.to_excel(writer, sheet_name=name, index=False)
print("筛选结果已保存到 选股结果.xlsx")
Usage tips
- Use in moderation — high-frequency calls may be banned by the WenCai server; it is recommended to have an interval of ≥ 2 seconds between each query.
- Always usethe latest version:
pip install pywencai --upgrade - Query string usageChinese natural language — write queries as if searching on the WenCai website.
- When
loop=Trueand setfindwhen,loopis ignored, and only the first 100 results are returned. - When using paid data, set
pro=Trueand provide a validcookie。
Common error handling
| Error | Cause | Solution |
|---|---|---|
Cookie expired |
Cookie expired | Log in to the WenCai website again to obtain a new Cookie |
ReturnNone |
Query returned no results or was rate-limited | Check the query statement and reduce the call frequency |
Node.js not found |
Node.js not installed | Install Node.js v16+ |
JSONDecodeError |
Server returned an exception | Increaseretryparameter and retry later |
| Returns a dict instead of a DataFrame | The query is of detail type | Setno_detail=Trueforce return of a DataFrame |
Rules
- Before using this Skill, confirm that what the user needs isWenCai natural language data query, rather than a pure market data API (such as baostock) or a backtesting framework (such as backtrader/rqalpha).
- In the examples, the
cookieparameter should uniformly use the environment variableWENCAI_COOKIEor the Cookie file management method,do not hard-code Cookie strings。 - Always set
no_detail=Trueto ensure returningDataFrame(unless the user explicitly needs a detail dict). - For batch queries, the
sleepparameter must be set (recommended ≥ 2 seconds) to avoid being banned by the server. - Query strings should use Chinese natural language, consistent with the input method in the WenCai website search box.