PYTHON
[|]
#Part 17
FREE Analytical Course by PythonInvest Starts in May 2025

Stock Screening Using Fundamental and Technical Indicators (Paid Data)

Unlocking Hidden Gems: A Fundamental Analysis of S&P 500 Stocks

Stocks represent more than just a fluctuating price—they embody ownership in a company and a claim on its future growth and dividends. In the long run, a company's financial strength and expansion should be reflected in its stock price.
While analysts often focus on key metrics like earnings, profitability, EPS, and growth, stock prices can swing dramatically around earnings releases—highlighting the significance of fundamental data. However, accessing high-quality financial data is challenging with free sources. That’s why we leveraged Alpha Vantage, a paid data provider, to ensure accuracy and depth.
In this article, we’ll walk you through a step-by-step filtration process, narrowing down S&P 500 companies to identify a few with strong financial positions. Every metric serves as a directional indicator, and the sequence of steps plays a crucial role in pinpointing the most resilient businesses. Let’s dive in.

LINK TO THE CODE (interactive notebook in Colab): https://github.com/realmistic/PythonInvest-basic-fin-analysis/blob/master/colab_notebooks/Part17_SNP500_Fundamental_Analysis_using_AlphaVantage.ipynb
Discussion in Telegram
Screencasts on Youtube
Articles on Medium
Code on Github
Author: Ivan Brigida
Data Analyst and Financial Enthusiast
NOT INVESTMENT ADVICE
The Content is for informational purposes only, you should not construe any such information or other material as legal, tax, investment, financial, or other advice.

Intro

Many books on value investing exist—some of them over 70 years old. A great starting point is The Intelligent Investor, originally published in 1949. Another key figure to know is the "Oracle of Omaha," Warren Buffett, one of the most well-known investors.
Both Buffett and other value investors follow a fundamental valuation approach to selecting companies. While there is no single agreed-upon formula, the core principles and metrics are relatively few. The specific values of these metrics can vary over time and across industries, but they aim to identify the strongest companies relative to the market at any given moment.
One challenge of value investing is that smaller companies, even if financially strong and growing, may receive less media attention and remain under the radar of investors. As a result, their true strength may go unnoticed for some time.
A complementary approach is to combine value investing with technical analysis and earnings reports to refine entry points—especially when your investment horizon spans several quarters to a few years.

In this article, we will demonstrate how to download paid data and apply a step-by-step filtering process to identify promising companies from a large pool.
Executive Summary
This article explores the process of stock screening using paid data sources, providing a step-by-step methodology for investors seeking to identify high-quality stocks with strong profitability and growth metrics. The approach leverages advanced financial data—often only available through paid APIs or data providers—to set precise screening thresholds for key indicators such as Return on Equity (ROE), Earnings Growth, Revenue Growth, Operating Margin, and Profit Margin. Additional value-focused metrics like PEG Ratio and EV/EBITDA relative to industry medians are incorporated to refine the search for undervalued stocks with growth potential.

The article demonstrates how paid data unlocks deeper, more granular analysis, enabling investors to construct robust, custom screening filters that go beyond the capabilities of free screeners. By integrating quantitative thresholds and sector-specific benchmarks, users can systematically narrow the universe of stocks to those best positioned for outperformance. The methodology is supported by practical Python code examples, illustrating how to implement these screens and visualize results for further analysis.

Summary of Results

  • Financial Strength
    Step 1: Companies must be profitable and demonstrating growth to pass the first filter.
    01
  • Valuation Metrics
    Step 2: Companies must not be overvalued relative to the stock price (e.g., PEG ratio, EV/EBITDA).
    02
  • Technical Momentum
    Step 3: Companies should exhibit current market momentum and low volatility.
    03
  • Analyst Sentiment
    Step 4: Most analysts should predict growth and expect a higher target price for the stock.
    04
  • Deep Research
    Step 5: Perform deep analysis using OpenAI’s Reasoning functionality on a small subset of stocks that pass the first four steps.
    05

Data Sources

While it's possible to replicate this analysis using a free data source like the unofficial Yahoo Finance library (see video and GitHub repo), for today's exploration, we'll use the Alpha Vantage Paid Data API.

🔹 Free Tier Available: Includes 25 API calls per day.

I personally find Alpha Vantage to be more stable and consistently reliable compared to the occasional downtime with yfinance, but ultimately, the choice is yours.

Here is the link to the Company Overview endpoint:
🔗 Alpha Vantage Documentation – Fundamentals

Available Data Fields (Sample):
  • Financials: GrossProfitTTM, RevenueTTM, EBITDA, DilutedEPSTTM, ProfitMargin, ReturnOnEquityTTM
  • Valuation: PERatio, PEGRatio, PriceToBookRatio, PriceToSalesRatioTTM, EVToEBITDA, EVToRevenue
  • Technical: Beta, 50DayMovingAverage, 200DayMovingAverage, 52WeekHigh, 52WeekLow
  • Analyst Ratings: AnalystRatingBuy, StrongBuy, Hold, Sell, StrongSell, AnalystTargetPrice
  • Company Info: Name, Description, Sector, Industry, Exchange, Country, Currency, Address, OfficialSite

LINK TO THE CODE (interactive notebook in Colab): https://github.com/realmistic/PythonInvest-basic-fin-analysis/blob/master/colab_notebooks/Part17_SNP500_Fundamental_Analysis_using_AlphaVantage.ipynb

The Approach

We analyze approximately 500 U.S. companies from the S&P 500, based on the list available on Wikipedia as of early April 2025.

The analysis is done at a single point in time, using a step-by-step filtering method. We review the distribution of key metrics and apply well-known valuation and growth criteria.


Key Assumptions:
  • No historical tracking: We focus on current snapshot data — not trends, news, or past performance.
  • Not sector-specific: Some metrics aren’t directly comparable across different industries, and we don’t adjust for that.
  • Order matters: Changing the order of filters can lead to different outcomes.
  • Not the only method: This is one of many ways to screen for strong stocks — it’s more about the logic and structure than a definitive "right" approach.

Screening Steps:
  1. Fundamental Strength → Companies must show profitability and growth.
  2. Fair Valuation → Stocks shouldn’t appear overvalued relative to earnings (e.g., PE, PEG, EV/EBITDA).
  3. Technical Momentum → Capture those already showing upward price trends with manageable volatility.
  4. Analyst Sentiment → Look for positive analyst signals such as buy recommendations and higher target prices.

Goal:
To identify a few strong, overlooked companies outside of the usual top 10–20 by market cap — ones with solid fundamentals that may attract investor attention in the near future.

Step 1: Profitability and Growth

We begin the analysis with five key fundamental metrics, applying simple rules based on either exceeding the 25th percentile (top 75%) or just being positive. These filters are intentionally not too strict, designed to capture companies with solid but not necessarily exceptional performance.
Step 1 filter
# STEP 1: Profitability & Growth : select Q1(25%) or 0% values as the lower threshold

step1 = df[
    (df['ReturnOnEquityTTM'] > 0.085) &
    (df['QuarterlyEarningsGrowthYOY'] > 0) &
    (df['QuarterlyRevenueGrowthYOY'] > 0) &
    (df['OperatingMarginTTM'] > 0.114) &
    (df['ProfitMargin'] > 0.073)
]
💬 Metric Breakdown:
  • Return on Equity (ROE > 8.5%): Measures how efficiently a company uses shareholders’ equity to generate profits. Higher ROE = better financial performance.
  • Quarterly Earnings Growth YoY (> 0%): Positive earnings growth shows the company is improving profitability year-over-year.
  • Quarterly Revenue Growth YoY (> 0%): Indicates growing sales, a sign of demand and business expansion.
  • Operating Margin TTM (> 11.4%): Reflects operational efficiency — how much profit remains after covering operating costs.
  • Profit Margin (> 7.3%): The percentage of revenue that ends up as net profit. Higher values suggest strong cost control and pricing power.
Result: After applying these filters, 173 companies remain out of the original 503 in the S&P 500 list.
To better understand how these thresholds were chosen, you can look at the descriptive statistics (e.g., min, max, percentiles) for each of these metrics in the dataset:

Step 2: Apply Valuation Metrics

When analyzing stocks, valuation metrics help investors determine whether a stock is attractively priced relative to its earnings and growth potential. Two key metrics we're using in this scoring system are:

PEG Ratio < 1.5


PEG Ratio < 1.76 (median) — Growth at a Reasonable PriceThe PEG (Price/Earnings-to-Growth) ratio refines the traditional P/E ratio by accounting for a company’s earnings growth rate. It provides a clearer picture of whether a stock is truly undervalued or just cheap for a reason.
Formula:

Where:
  • P/E (Price-to-Earnings Ratio): Stock Price ÷ Earnings per Share (EPS)
  • Earnings Growth (%): Expected or historical EPS growth rate
Why it matters:
  • A PEG below 1 usually signals that a stock is undervalued relative to its growth.
  • A PEG between 1 and 1.5 suggests the stock is fairly valued.
  • A PEG above 1.5 may indicate overvaluation — the price may be too high for the level of growth expected.
By focusing on PEG ratios under 1.5, we aim to find stocks offering solid growth potential at a reasonable price — not overhyped, but not stagnant either.

EV/EBITDA < Industry Median — Better Value Than Peers.


EV/EBITDA (Enterprise Value to EBITDA) is a valuation metric that compares a company’s total value to its earnings before interest, taxes, depreciation, and amortization. It’s often more reliable than P/E when comparing companies with different debt levels.
Formula:

Where:
  • Enterprise Value (EV): Market Cap + Debt – Cash
  • EBITDA: A measure of operating profitability before non-cash and non-operating expenses

Why it matters:
  • EV/EBITDA accounts for debt, making it more comprehensive than P/E.
  • It’s useful when comparing companies across industries with different capital structures.
  • A lower EV/EBITDA suggests the company might be undervalued relative to its earnings.
General benchmarks:
  • EV/EBITDA under 10 → Often undervalued
  • Between 10 and 15 → Fairly valued
  • Over 15 → Possibly overvalued
Since norms vary by industry, we compare a company’s EV/EBITDA against its industry median to ensure we’re identifying value relative to peers.
New filtering rules for Step 2:

  • EV/EBITDA (EV/EBITDA < 14.9): The current (Q1 2025) median value was used to filter out expensive companies. This threshold is generally in line with the previous theoretical benchmark of 15.
  • PEG Ratio (PEG < 1.76): A generous filter based on the current median value of 1.8, which includes a segment of slightly overvalued stocks in the 1.5–1.8 range (compared to typical theoretical values).
Result:
After applying both Steps filters, 41 companies remain from the original 503 in the S&P 500 list.
(If you apply the Step 2 (Valuation metrics) alone, 180 companies remain out of the original 503.)

Step 3: Technical Strength and Low Risk

To further refine the stock selection, we apply two additional criteria focused on momentum and risk management:
While it's fairly straightforward to apply a simple bullish momentum rule — 50-Day Moving Average > 200-Day Moving Average — the inclusion of Beta may require a bit more explanation.
You can learn more about the Beta coefficient in the following section:
Beta Formula



Most platforms calculate Beta using historical data, so we typically use Beta directly from financial data sources rather than computing it manually.

📌 How to Interpret Beta?

Beta Value

Meaning

Risk Level

Example Stocks

β < 0

Moves opposite to the market (inverse correlation)

Very low

Gold, bonds

β = 0

No correlation to market movements

Low

Fixed-income assets

0 < β < 1

Moves less than the market (lower volatility)

Moderate

Utilities, consumer staples

β = 1

Moves in line with the market

Normal

S&P 500 index funds

β > 1

More volatile than the market

High

Tech stocks, growth stocks

β > 2

Highly volatile, significant price swings

Very high

Small-cap growth stocks, cryptocurrencies


Why Use Beta for Stock Selection?
  • For Stability: Low Beta (0.8 - 1.0) → Defensive stocks, less affected by market swings.
  • For Growth Potential: Moderate Beta (1.0 - 1.5) → Balanced risk-reward tradeoff.
  • For High Risk/High Reward: High Beta (>1.5) → Aggressive stocks, high volatility.
For a 5-month investment horizon, we typically prefer β between 0.8 and 1.5:
  • Avoids extreme volatility
  • Still offers growth potential
  • Balances risk vs. reward

Here is the distribution of metrics:
New filtering rules for Step 3:

  • 50-Day Moving Average > 200-Day Moving Average. This is a classic indicator of bullish momentum. It suggests that the stock’s short-term trend is stronger than its long-term trend—a sign of technical strength and potential upward price movement.
  • Beta Between 0.8 and 1.5. The Beta (β) coefficient measures a stock’s volatility relative to the overall market (typically the S&P 500). This range targets stocks with moderate risk: stable enough to avoid excessive volatility but dynamic enough to offer upside potential.
Result:
After applying all filters from Steps 1-3, 8 companies remain from the original 503 in the S&P 500 list.
(If you apply the Step 3 (Momentum and Risk) alone, 188 companies remain out of the original 503.)

Step 4: Analysts Sentiment

In this step, we incorporate analyst sentiment to further refine our stock selection. Analyst ratings offer a forward-looking, qualitative layer of insight based on deep research and earnings projections. To ensure we select stocks that are not only fundamentally and technically strong, but also favored by professionals, we apply two criteria:

More Buy Ratings than Sell/Strong Sell Combined
This condition ensures that the consensus view leans positively toward the stock’s future performance.

Analyst Target Price > 50-Day Moving Average
This acts as a simple valuation sanity check: analysts believe the stock has upside relative to its current short-term trend.

By applying this filter, we narrow the list down to companies that are not only quantitatively attractive but also have positive sentiment from Wall Street analysts—an additional confidence boost for potential investors.

Here is the distribution of metrics:
Result:
After applying all filters from Steps 1–4, 6 companies remain from the original 503 in the S&P 500 list.

(Note: If only Step 4 — the Analyst Sentiment Check — is applied, 488 companies remain out of the original 503.)

Selected Companies:
  1. [BKNG] Booking Holdings Inc. — An American travel technology company organized in Delaware and based in Norwalk, Connecticut. It owns and operates several travel fare aggregators and metasearch engines, including its flagship Booking.com, as well as Priceline.com, Agoda.com, Kayak.com, Cheapflights, Rentalcars.com, Momondo, and OpenTable.
  2. [CHTR] Charter Communications, Inc. — An American telecommunications and mass media company. Its services are marketed under the brand name Charter Spectrum.
  3. [FI] Frank’s International N.V. — Provides various tubular engineering services for oil and gas exploration and production companies. It operates in the United States, Europe, the Middle East, Africa, Latin America, the Asia-Pacific region, and internationally. The company is headquartered in Den Helder, the Netherlands.
  4. [LULU] Lululemon Athletica Inc. — A Canadian athletic apparel company headquartered in Vancouver, Canada.
  5. [META] Meta Platforms, Inc. — Develops products that enable people to connect and share through mobile devices, PCs, virtual reality headsets, wearables, and home devices. Headquartered in Menlo Park, California.
  6. [RL] Ralph Lauren Corporation — An American fashion company known for designing and marketing products across four categories: apparel, home, accessories, and fragrances. Its offerings range from mid-range to luxury segments.

Final Evaluation Using LLM Reasoning

The final step in our selection process is to apply the recently developed Reasoning Mode available in many popular LLMs (Large Language Models) to derive forward-looking expectations based on recent financial reports and news.

For example, you can use a prompt like this:
Prompt:
I have identified the following stocks using fundamental analysis. Here are their key metrics:
<INSERT KEY METRICS>
Instructions: Based on the above data, reason through which stock(s) present the best investment opportunity for long-term growth and/or value. Consider metrics such as profit margin, PE ratio, PEG ratio, earnings/revenue growth, analyst ratings, and target price. Explain your reasoning step by step, comparing the strengths and weaknesses of each stock. Conclude with a ranked list or a clear recommendation.
The final step in our selection process is to apply the recently developed Reasoning Mode available in many popular LLMs (Large Language Models) to derive forward-looking expectations based on recent financial reports and news.

For example, you can use a prompt like this:
Prompt:
I have identified the following stocks using fundamental analysis. Here are their key metrics:
<INSERT KEY METRICS>
Instructions: Based on the above data, reason through which stock(s) present the best investment opportunity for long-term growth and/or value. Consider metrics such as profit margin, PE ratio, PEG ratio, earnings/revenue growth, analyst ratings, and target price. Explain your reasoning step by step, comparing the strengths and weaknesses of each stock. Conclude with a ranked list or a clear recommendation.
Thought for 59 seconds (12 searches, 47 sources):

Booking Holdings (BKNG)
  • Fundamentals:
  • EV/EBITDA 16.3, EV/Revenue 6.4, PE 26.7, PEG 1.27, ROE 2.3%, profit margin 24.8%
  • Strong earnings growth (40.9% YoY), but revenue growth more modest (14.4%)
  • Strategic Positioning:
  • Connected Trip vision integrates planning, booking, payment and in‑trip experiences, powered by generative AI trip planners and price‑comparison tools TradingView.
  • Transformation Program (launched Nov 2024) to modernize systems and optimize procurement, targeting $400–450 M in annual savings over three years TradingView.
  • Capital return‐oriented: $6.5 B buybacks in 2024, $20 B authorization in Jan 2025; dividend up 10% for Q1 2025 TradingView.
  • Risks & Outlook:
  • Q1 2025 gross bookings growth guidance 5–7%; full‑year mid‑single‑digit bookings and revenue growth; operating income expected to rise TradingView.
  • Exposure to competitive online‑travel market, FX swings, and geopolitical travel disruptions.
Charter Communications (CHTR)
  • Fundamentals:
  • EV/EBITDA 6.7, EV/Revenue 2.6, PE 9.8, PEG 0.36, ROE 0.34%, profit margin 9.2%
  • Revenue barely grew (+0.9% in 2024), but earnings from operations +4.5% TradingView.
  • Strategic Positioning:
  • Subsidized rural broadband build‑out: $5.5 B invested since 2022, activating 813 k passings; plans $8 B+ over next year TradingView.
  • Network evolution to DOCSIS 4.0 and multi‑gigabit speeds; launched symmetrical Internet and advanced Wi‑Fi TradingView.
  • New “Life Unlimited” brand platform and video bundles with ad‑supported streaming apps TradingView.
  • Risks & Outlook:
  • 2025 capex ~$12 B, debt $93.9 B (target leverage 4–4.5× EBITDA) TradingView.
  • Competitive pressures from fiber‑to‑the‑home, 5G fixed wireless, and regulatory scrutiny; subscriber attrition risk.
Fiserv (FI)
  • Fundamentals:
  • EV/EBITDA 16.1, EV/Revenue 7.0, PE 39.6, PEG 0.98, ROE 10.9%, profit margin 15.3%
  • Organic revenue growth 13% in Q4 2024, 16% for full year; merchant solutions +10% in Q4 2024 TradingView.
  • Strategic Positioning:
  • Realigned segments for operational focus; acquired Skytef and Sled to bolster distribution and direct‑payment capabilities; pending CCV and Payfare deals to broaden embedded‑finance offerings TradingView.
  • Returned $5.5 B via buybacks in 2024; issued $3.75 B senior notes for repurchases and debt paydown TradingView.
  • Risks & Outlook:
  • Competitive fintech landscape with Big Tech and nimble startups; integration risks from M&A; high capex on platforms.
  • Plans continued M&A, organic growth in digital payments, and free‑cash‑flow‑driven capital returns.
Lululemon Athletica (LULU)
  • Fundamentals:
  • EV/EBITDA 10.3, EV/Revenue 2.9, PE 17.5, PEG 1.05, ROE 42.4%, profit margin 17.1%
  • Q4 2024 comp‑store sales +3%; full‑year growth in DTC and men’s lines; 2025 revenue guide 5–7% Forbes.
  • Strategic Positioning:
  • “Power of Three ×2” to double revenue to $12.5 B by 2026 via men’s, digital and international expansion Lululemon Corporate.
  • Innovation pipeline: experiential store concepts, brand activations (e.g., “Ralph’s New York” pop-ups), and Canada/Europe expansion Lululemon Corporate.
  • Risks & Outlook:
  • Q1 2025 guide 6–7% growth; fiscal 2025 rev guide $11.15–11.30 B vs est $11.31 B; headwinds from U.S. consumer softness and 20 bp tariff impact Reuters.
  • Rising competition from Alo Yoga, Vuori; macro uncertainty in premium‑price athleisure.
Meta Platforms (META)
  • Fundamentals:
  • EV/EBITDA 15.2, EV/Revenue 8.0, PE 21.9, PEG 1.07, ROE 37.1%, profit margin 37.9%
  • Q4 2024 revenue $48.4 B (+21%), operating income +43%, free cash flow $13.2 B; capex $39 B Atmeta Investor.
  • Strategic Positioning:
  • Leading in generative AI across 4 M+ advertisers; integrating AI into ads (CPMs +14%), Reality Labs and AI‑powered tools underpinning future monetization Digital Marketing News | Marketing Dive.
  • Massive AI infrastructure spend (capex guide $60–65 B in 2025) to maintain leadership, supplemented by open‑source AI efforts (Llama) Reuters.
  • Risks & Outlook:
  • 2025 Q1 revenue guide $39.5–41.8 B vs est $41.7 B; cautious outlook due to AI spend ramp and antitrust/legal overhang Reuters.
  • User base maturity in North America/EMEA vs growth opportunity in emerging markets; regulatory and privacy headwinds.
Ralph Lauren (RL)
  • Fundamentals:
  • EV/EBITDA 11.2, EV/Revenue 1.9, PE 18.5, PEG 1.56, ROE 27.6%, profit margin 10.1%
  • FY 2024 sales +3%, net income +49%; Q3 2025 revenue +11% globally, Asia +20%, direct‑to‑consumer comps +12% corporate.ralphlauren.com.
  • Strategic Positioning:
  • “Next Great Chapter: Accelerate” focusing on brand elevation, premium full‑price selling, digital expansion and ecosystem programs (licensing alliances) SEC.
  • Strong performance in China/Europe; raised fiscal 2025 revenue guide to +6–7% constant currency on robust apparel demand Reuters.
  • Risks & Outlook:
  • Currency headwinds (~100–150 bp in 2025), economic sensitivity of luxury spending, inventory management.
  • Capital returned via dividends and opportunistic buybacks; CFO succession enhances governance.

Recommendation & Ranking:

Tier

Growth Focus

Value Focus

1

Meta Platforms (META)

Charter (CHTR)

2

Lululemon (LULU)

Ralph Lauren (RL)

3

Fiserv (FI)

4

Booking Holdings (BKNG)

  1. Meta (META) – Unparalleled AI leadership, best‐in‐class margins and cash flow underpin long‑term dominance.
  2. Lululemon (LULU) – Strong brand, digital‑first model, clear path to $12.5 B. Watch consumer resilience.
  3. Fiserv (FI) – Robust fintech growth via M&A and digital‑payments tailwinds; valuation rich but justified by recurring revenues.
  4. Booking (BKNG) – Attractive travel recovery play with tech differentiation but mid‑single‑digit growth profile.
  5. Charter (CHTR) – Compelling value (PE <10) with secular broadband tailwinds; debt and competition warrant caution.
  6. Ralph Lauren (RL) – Solid luxury rebound and pricing power; economic sensitivity and currency headwinds temper upside.
Conclusion
Stock screening with paid data empowers investors to make more informed, data-driven decisions by providing access to comprehensive, high-quality financial metrics and industry comparisons. The article’s systematic approach—grounded in profitability, growth, and value criteria—enables the identification of stocks with superior fundamentals and attractive valuations. While free screeners offer basic filtering, paid data unlocks advanced analytics and customization, giving investors a competitive edge in portfolio construction.

Ultimately, the integration of paid data into the stock screening process enhances both the precision and reliability of investment decisions. By combining rigorous quantitative filters with sector and industry context, investors can efficiently target opportunities that align with their strategic objectives, manage risk, and improve long-term returns. The methodology outlined serves as a blueprint for leveraging premium data sources to elevate the quality of stock selection and portfolio management in today’s data-rich investment landscape

Do you find the article useful?

Do you like the content?
Consider to make a donation
Whether you're grateful for the content (Buy Me A Coffee page), or you wish to support me coding (GitHub sponsorship page)

Leave your feedback on the article

For example, is it easy to understand?
For example, could you run the code?
For example, do you have idea to improve the article ?

Here you'll find the best articles from PythonInvest. Only useful digests, no spam.