Everyrow
Getting Started
  • Installation
  • Skills vs MCP
Guides
  • How to Add A Column to a DataFrame with Web Research
  • How to Classify and Label Data with an LLM in Python
  • Remove Duplicates from ML Training Data in Python
  • Filter a Pandas DataFrame with LLMs
  • How to Fuzzy Join DataFrames in Python
  • How to sort a dataset using web data in Python
  • How to resolve duplicate rows in Python with LLMs
API Reference
  • dedupe
  • merge
  • rank
  • agent_map
  • screen
Case Studies
  • Build an AI lead qualification pipeline in Python
  • Fuzzy join two Pandas DataFrames using LLMs
  • Fuzzy match and merge contact lists in Python
  • How to filter job postings with LLM Agents
  • How to merge datasets without common ID in Python
  • How to score and prioritize leads with AI in Python
  • How to Screen Stocks in Python with AI Agents
  • How to use LLMs to deduplicate CRM Data
  • LLM-powered Merging at Scale
  • LLM-powered Screening at Scale
  • Python Notebook to screen stocks using AI Agents
  • Running LLM Web Research Agents at Scale
  • Score and rank leads without a CRM in Python
  • Use LLM Agents to research government data at scale

How to Screen Stocks in Python with AI Agents¶

Screen the S&P 500 for large cap companies whose margins fall when oil prices go up.

This identifies companies that are negatively impacted by rising oil prices through:

  • Higher input costs (transportation, energy-intensive manufacturing)
  • Reduced consumer spending on discretionary items
  • Increased operational expenses
  • Supply chain disruptions

This is a filter that no traditional stock screener can perform.

In [ ]:
# Setup
import asyncio
from pathlib import Path

import pandas as pd
from pydantic import BaseModel, Field
from dotenv import load_dotenv

# Load API key from .env
load_dotenv()

from everyrow.ops import screen
In [18]:
# Load S&P 500 companies
stocks = pd.read_csv("../data/S&P 500 Companies.csv")
print(f"Loaded {len(stocks)} companies")
stocks.head()
Loaded 502 companies
Out[18]:
cik company ticker market_cap_usd_billion gics_sector gics_sub_industry headquarters founded
0 1045810 Nvidia NVDA 4425.366110 Information Technology Semiconductors Santa Clara, California 1993
1 320193 Apple Inc. AAPL 4247.171105 Information Technology Technology Hardware, Storage & Peripherals Cupertino, California 1977
2 1652044 Alphabet Inc.(Class A) GOOGL 3825.129226 Communication Services Interactive Media & Services Mountain View, California 1998
3 1652044 Alphabet Inc.(Class C) GOOG 3814.940738 Communication Services Interactive Media & Services Mountain View, California 1998
4 789019 Microsoft MSFT 3642.251543 Information Technology Systems Software Redmond, Washington 1975
In [19]:
# Define the screening criteria
SCREENING_TASK = """
Find large cap companies whose profit margins fall when oil prices go up.

**Criteria for negative oil price impact on margins:**

1. **High energy costs**: Companies with energy-intensive operations (manufacturing, 
   transportation, logistics, airlines, shipping) where oil/energy is a significant 
   input cost that cannot be easily passed through to customers.

2. **Transportation-dependent**: Companies with heavy reliance on transportation 
   (retailers with extensive supply chains, delivery services, freight/logistics) 
   where fuel costs directly impact margins.

3. **Consumer discretionary sensitivity**: Companies whose customers reduce spending 
   when oil prices rise (automotive, travel, restaurants, retail) leading to margin 
   compression from lower volumes or pricing pressure.

4. **Energy-intensive manufacturing**: Companies that use significant amounts of 
   energy in production (chemicals, metals, paper, packaging) where higher energy 
   costs compress margins.

5. **Historical correlation**: Companies that have shown margin compression during 
   periods of high oil prices in the past (check earnings reports, 10-Ks, analyst 
   commentary during oil price spikes).

**Exclude:**
- Energy companies (they benefit from higher oil prices)
- Companies with strong pricing power that can pass through costs
- Companies with minimal energy/transportation exposure
- Companies that have hedged energy costs effectively
"""

# Output schema - just pass/fail for efficiency
class ScreenResult(BaseModel):
    passes: bool = Field(
        description="True if company's margins fall when oil prices go up"
    )
In [ ]:
# Run the screen
async def run_screen():
    print("Screening... (this will take a few minutes)\n")
    
    result = await screen(
        task=SCREENING_TASK,
        input=stocks,
        response_model=ScreenResult,
    )
    
    return result.data

# Run it
results = await run_screen()
In [21]:
# Summary
print(f"Companies with margins that fall when oil prices rise: {len(results)}")
print(f"Pass rate: {len(results)/len(stocks)*100:.1f}% of S&P 500\n")

print("Affected companies:")
for _, row in results.iterrows():
    print(f"  {row['ticker']:6} | {row['company'][:40]}")
Companies with margins that fall when oil prices rise: 150
Pass rate: 29.9% of S&P 500

Affected companies:
  AMZN   | Amazon
  BRK.B  | Berkshire Hathaway
  WMT    | Walmart
  COST   | Costco
  KO     | Coca-Cola Company (The)
  MCD    | McDonald's
  DIS    | Walt Disney Company (The)
  UBER   | Uber
  VZ     | Verizon
  TJX    | TJX Companies
  BKNG   | Booking Holdings
  BA     | Boeing
  COF    | Capital One
  UNP    | Union Pacific Corporation
  LOW    | Lowe's
  MDT    | Medtronic
  DE     | Deere & Company
  MCK    | McKesson Corporation
  NEM    | Newmont
  CVS    | CVS Health
  SBUX   | Starbucks
  NKE    | Nike, Inc.
  DASH   | DoorDash
  DELL   | Dell Technologies
  MMM    | 3M
  GD     | General Dynamics
  WM     | Waste Management
  ORLY   | O’Reilly Automotive
  SHW    | Sherwin-Williams
  MAR    | Marriott International
  HWM    | Howmet Aerospace
  ECL    | Ecolab
  JCI    | Johnson Controls
  MNST   | Monster Beverage
  ABNB   | Airbnb
  ITW    | Illinois Tool Works
  RCL    | Royal Caribbean Group
  GLW    | Corning Inc.
  GM     | General Motors
  CMI    | Cummins
  SPG    | Simon Property Group
  COR    | Cencora
  PWR    | Quanta Services
  HLT    | Hilton Worldwide
  NSC    | Norfolk Southern
  CSX    | CSX Corporation
  FDX    | FedEx
  AZO    | AutoZone
  CL     | Colgate-Palmolive
  ROST   | Ross Stores
  APD    | Air Products
  WDC    | Western Digital
  BDX    | Becton Dickinson
  F      | Ford Motor Company
  URI    | United Rentals
  CAH    | Cardinal Health
  LVS    | Las Vegas Sands
  FAST   | Fastenal
  GWW    | W. W. Grainger
  CARR   | Carrier Global
  CMG    | Chipotle Mexican Grill
  KR     | Kroger
  DAL    | Delta Air Lines
  TGT    | Target Corporation
  YUM    | Yum! Brands
  VMC    | Vulcan Materials Company
  NUE    | Nucor
  MLM    | Martin Marietta Materials
  SYY    | Sysco
  KMB    | Kimberly-Clark
  CCL    | Carnival
  OTIS   | Otis Worldwide
  UAL    | United Airlines Holdings
  EXPE   | Expedia Group
  LEN    | Lennar
  IR     | Ingersoll Rand
  LYV    | Live Nation Entertainment
  ODFL   | Old Dominion
  KHC    | Kraft Heinz
  ROL    | Rollins, Inc.
  K      | Kellanova
  TSCO   | Tractor Supply
  EME    | Emcor
  PHM    | PulteGroup
  STLD   | Steel Dynamics
  GIS    | General Mills
  DG     | Dollar General
  STZ    | Constellation Brands
  JBL    | Jabil
  DLTR   | Dollar Tree
  HUBB   | Hubbell Incorporated
  PPG    | PPG Industries
  LH     | Labcorp
  LULU   | Lululemon Athletica
  RL     | Ralph Lauren Corporation
  WSM    | Williams-Sonoma, Inc.
  NVR    | NVR, Inc.
  DRI    | Darden Restaurants
  CHD    | Church & Dwight
  TSN    | Tyson Foods
  IP     | International Paper
  EXPD   | Expeditors International
  WST    | West Pharmaceutical Services
  AMCR   | Amcor
  LUV    | Southwest Airlines
  SW     | Smurfit Westrock
  JBHT   | J.B. Hunt
  IFF    | International Flavors & Fragrances
  PKG    | Packaging Corporation of America
  PNR    | Pentair
  LII    | Lennox International
  APTV   | Aptiv
  DD     | DuPont
  TKO    | TKO Group Holdings
  BBY    | Best Buy
  TXT    | Textron
  DPZ    | Domino's
  MAS    | Masco
  AVY    | Avery Dennison
  BALL   | Ball Corporation
  CLX    | Clorox
  ZBRA   | Zebra Technologies
  HRL    | Hormel Foods
  BLDR   | Builders FirstSource
  VTRS   | Viatris
  HST    | Host Hotels & Resorts
  HAS    | Hasbro
  SWK    | Stanley Black & Decker
  SJM    | J.M. Smucker Company (The)
  AES    | AES Corporation
  BAX    | Baxter International
  AOS    | A. O. Smith
  TAP    | Molson Coors Beverage Company
  POOL   | Pool Corporation
  CPB    | Campbell's Company (The)
  HSIC   | Henry Schein
  NCLH   | Norwegian Cruise Line Holdings
  CAG    | Conagra Brands
  LW     | Lamb Weston
  MOS    | Mosaic Company (The)
  LKQ    | LKQ Corporation
  MHK    | Mohawk Industries
  PEP    | PepsiCo
  KDP    | Keurig Dr Pepper
  EL     | Estée Lauder Companies (The)
  DOV    | Dover Corporation
  ULTA   | Ulta Beauty
  ON     | ON Semiconductor
  MKC    | McCormick & Company
  IEX    | IDEX Corporation
In [22]:
# View the research for a specific company
if 'research' in results.columns and len(results) > 0:
    sample = results.iloc[0]
    print(f"Research for {sample['company']} ({sample['ticker']}):\n")
    print(sample['research'])
Research for Amazon (AMZN):

{'screening_result': "Amazon's retail business is highly transportation-dependent, with billions in shipping and fulfillment costs. Analysts have specifically noted that Amazon's profits can be 'hammered' by higher gas and diesel prices, as the costs to power its vast logistics network rise significantly [1018724_1, 1018724_2].", 'passes': "Amazon's retail business is highly transportation-dependent, with billions in shipping and fulfillment costs. Analysts have specifically noted that Amazon's profits can be 'hammered' by higher gas and diesel prices, as the costs to power its vast logistics network rise significantly [1018724_1, 1018724_2]."}
In [23]:
# Breakdown by sector
if 'gics_sector' in results.columns:
    print("Affected companies by sector:")
    print(results['gics_sector'].value_counts())
Affected companies by sector:
gics_sector
Consumer Discretionary    39
Industrials               39
Consumer Staples          28
Materials                 18
Health Care               11
Information Technology     6
Communication Services     4
Financials                 2
Real Estate                2
Utilities                  1
Name: count, dtype: int64
In [24]:
# Save results
results.to_csv("oil_price_margin_screen_results.csv", index=False)
print(f"Results saved to oil_price_margin_screen_results.csv")
Results saved to oil_price_margin_screen_results.csv

What Just Happened?¶

The everyrow.io screen:

  1. Researched each company using web search to understand their business model and cost structure
  2. Analyzed energy/transportation exposure by examining operations, supply chains, and input costs
  3. Evaluated historical sensitivity by researching earnings reports and analyst commentary during oil price spikes
  4. Assessed margin impact mechanisms - whether companies can pass through costs or face margin compression
  5. Made a judgment on whether the company's margins fall when oil prices rise

This would take an analyst weeks to do manually for 500 companies.

Understanding the Results¶

Companies identified here are vulnerable to margin compression when oil prices rise. This could be due to:

  • Direct energy costs in manufacturing or operations
  • Transportation/logistics costs that can't be passed through
  • Reduced consumer demand for discretionary goods/services
  • Supply chain disruptions that increase costs

These companies may benefit from hedging strategies or could be short candidates during oil price spikes.