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()
Out[18]:
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]}")
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'])
In [23]:
# Breakdown by sector
if 'gics_sector' in results.columns:
print("Affected companies by sector:")
print(results['gics_sector'].value_counts())
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")
What Just Happened?¶
The everyrow.io screen:
- Researched each company using web search to understand their business model and cost structure
- Analyzed energy/transportation exposure by examining operations, supply chains, and input costs
- Evaluated historical sensitivity by researching earnings reports and analyst commentary during oil price spikes
- Assessed margin impact mechanisms - whether companies can pass through costs or face margin compression
- 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.