Jupyter使用SQLAlchemy合并WRDS两数据集返回空表如何解决
WRDS OptionMetrics表内连接返回空结果修复
都是实际用WRDS踩过的实坑,直接按顺序排查:
- 第一优先级查关联键类型/值不匹配
你连的两个表中,optionm.opprcd2020是OptionMetrics官方原生的日度期权行情表,optionm.option_price_2020不是官方标准表,属于用户上传/二次加工的衍生表,最常见的问题就是两个表的optionid、date字段看着名字一样,实际数据类型或者编码规则完全对不上:- 比如一个表
date是DATE类型只存年月日,另一个是TIMESTAMP带时分秒,直接等值判断永远不相等 - 比如一个表
optionid是整数类型,另一个是浮点型存了带.0的数值,或是旧加工表用的是2019年之前OptionMetrics的老版optionid编码规则,和新的官方表id完全匹配不上
先跑两段单表查询确认字段类型和样本值,再做join:
如果类型不一致,join的时候显式转成相同类型就行,比如写成-- 查官方表的关联键类型和样本 select optionid, date, pg_typeof(optionid), pg_typeof(date) from optionm.opprcd2020 limit 5; -- 查加工表的关联键类型和样本 select optionid, date, pg_typeof(optionid), pg_typeof(date) from optionm.option_price_2020 limit 5;on a.optionid::bigint = b.optionid::bigint and a.date::date = b.date::date - 比如一个表
- 你完全没必要做这个join
官方原生的opprcd2020表本身就自带标的买卖价字段,分别是underlying_bid和underlying_ask,你要补的两个字段直接从单表取就行,绕开join根本不会出现匹配不上的问题,改完的代码如下:company = conn.raw_sql(""" select a.symbol, a.strike_price, a.optionid, a.impl_volatility, a.open_interest, a.volume, a.vega, a.best_bid, a.best_offer, a.date, a.exdate, a.underlying_bid as underlyingbid, a.underlying_ask as underlyingask from optionm.opprcd2020 a where a.volume > 500 and a.volume > 0.5 * a.open_interest and a.cp_flag = 'C' and (a.exdate - a.date) <= 30 and (a.exdate - a.date) > 0 and a.best_bid > 0.3 LIMIT 50 """) - 快速排查逻辑
要是你确实需要用那个加工表,先把所有where过滤条件全删掉,只留join逻辑查匹配条数:
这个语句如果返回0,百分百是关联键的问题,和你写的筛选条件没关系;如果返回大于0的数,再逐步加where条件,看是哪条筛选把结果全滤掉了。select count(1) from optionm.opprcd2020 a inner join optionm.option_price_2020 b on a.optionid = b.optionid and a.date = b.date
补充:WRDS用的PostgreSQL引擎,两个date类型字段直接做减法算间隔天数的写法是对的,不用改日期计算逻辑。
内容的提问来源于stack exchange,提问作者ayoubster
相关产品推荐
相关产品推荐

