from zipline.pipeline import Pipeline
from zipline.pipeline.data import EquityPricing, master, sharadar
from zipline.pipeline.factors import AverageDollarVolume, Latest
from zipline.pipeline.filters import AllPresent, All
def TradableStocksUS(market_cap_filter=False):
"""
Returns a Pipeline filter of tradable stocks, defined as:
- Common stocks only (no preferred stocks, ADRs, LPs, or ETFs)
- Primary shares only
- 200-day average dollar volume >= $2.5M
- price >= $5
- 200 continuous days of price and volume.
If market_cap_filter=True, also requires market cap > $500M.
"""
common_stock = master.SecuritiesMaster.usstock_SecurityType2.latest.eq('Common Stock')
is_primary_share = master.SecuritiesMaster.usstock_PrimaryShareSid.latest.isnull()
tradable_stocks = common_stock & is_primary_share
tradable_stocks = AverageDollarVolume(window_length=200, mask=tradable_stocks) >= 2.5e6
tradable_stocks = Latest([EquityPricing.close], mask=tradable_stocks) > 5
tradable_stocks = AllPresent(inputs=[EquityPricing.close], window_length=200, mask=tradable_stocks)
tradable_stocks = All([EquityPricing.volume.latest > 0], window_length=200, mask=tradable_stocks)
if market_cap_filter:
tradable_stocks = Latest([sharadar.Fundamentals.slice(dimension='ARQ', period_offset=0).MARKETCAP], mask=tradable_stocks) >= 500e6
return tradable_stocks