Skip to main content P/E Ratio Indicator For ThinkOrSwim - Custom Valuation Analysis Skip to main content Skip to content
Master the TTM Squeeze with our comprehensive 19-module course Start Learning →
TOS Indicators
  • Tools

    Categories

    • Indicators
    • Backtesters
    • Scans
    • Dashboards
    • thinkScript
    • Member Resources
    Browse Full Library

    Featured Tutorials

    Heiken Ashi Trend Indicator
    Heiken Ashi Trend Indicator
    Indicators

    Download our Custom Heiken Ashi indicator for ThinkOrSwim. Full ThinkScript code, formula...

    Learn more →
    Commodities Tracker
    Commodities Tracker
    Indicators

    For acceleration signals: trend-following strategies and buying pullbacks. For deceleration signals: short...

    Learn more →
    Build an Election Backtester in 10 Minutes
    Build an Election Backtester in 10 Minutes
    Backtesters

    Learn how to create a Post-Election Backtester in ThinkOrSwim to analyze market...

    Learn more →

    Popular Posts

    Unusual Volume
    Unusual Volume
    Scans

    Build 4 scans to easily find stocks with greater than...

    Learn more →
    Upcoming Earnings with High Short Interest
    Upcoming Earnings with High Short Interest
    Scans

    Build a scan to find stocks that are likely to...

    Learn more →
    Unusual Volume Pro Scans
    Unusual Volume Pro Scans
    Scans

    4 additional scans to find unusual volume overlapping with key...

    Learn more →
  • Courses
    Squeeze Course
    Squeeze Course
    19 Modules

    Scan, backtest, and trade the TTM Squeeze setup with precision.

    Unlock Course →
    Earnings Course
    Earnings Course
    3 Modules

    Master earnings plays with free indicators and proven strategies for ThinkOrSwim.

    Unlock Course →
    V-Shaped Reversals
    V-Shaped Reversals
    7 Modules

    Identify and trade powerful V-shaped reversal patterns with confidence and precision.

    Unlock Course →
    Fibonacci Trading
    Fibonacci Trading
    4 Modules

    Learn to trade Fibonacci retracements and extensions in ThinkOrSwim effectively.

    Unlock Course →
  • Products
    Futures Volatility Box Premium
    Futures Volatility Box

    Volatility models for 10 major futures markets, including micros & SPX.

    Explore Futures VB →
    Stock Volatility Box Premium
    Stock Volatility Box

    Dynamic support & resistance for 595+ stocks/ETFs, with a live scanner.

    Explore Stock VB →
    Opening Range Breakouts Premium
    Opening Range Breakouts

    Powerful live scanner & backtester for ORB strategies on 595+ stocks.

    Explore ORB Setups →
My Account
Back to Tutorials
Beginner 13 minutes ThinkOrSwim

P/E Ratio

Build a comprehensive P/E ratio indicator with historical context, median analysis, and automatic valuation signals for better fundamental analysis in ThinkOrSwim

Download Indicator
How to install in ThinkOrSwim →
Table of Contents
  • The Complete Guide to Building a P/E Ratio Indicator in ThinkOrSwim
  • Understanding the P/E Ratio and Its Significance
  • Why Traditional P/E Sources Fall Short
  • The ThinkOrSwim P/E Advantage
  • When is the P/E ratio most useful?
  • P/E Ratio Calculation Methodology
  • Building the P/E Ratio Indicator: Step-by-Step Guide
  • Advanced Features and Enhancements
  • Practical Trading Applications
  • Limitations and Important Considerations
  • Optimizing the Indicator for Different Trading Styles
  • Troubleshooting Common Issues
  • Advanced Customization Options
  • Integration with Other Fundamental Metrics
  • Market Cycle Considerations
  • Best Practices for P/E Analysis
  • Conclusion: Integrating Fundamental and Technical Analysis

Introduction

The P/E ratio is one of the more popular methods for valuing stocks. It is simple to calculate and easy to understand.

In this tutorial, I’ll show you how to build your own P/E ratio indicator inside of ThinkOrSwim.

P/E Ratio Indicator for ThinkOrSwim

While you can view P/E ratios on just about any financial website these days (think Yahoo Finance, WSJ, etc.), I think there are two key benefits to plotting the P/E ratio inside of ThinkOrSwim.

  1. Historical P/E Ratio Data – you can go back more than 10 years, and view how the P/E ratio has changed over time. This provides you with context.
  2. Ability to Interact with the Data – you can run calculations on the data (think basic statistical approaches, up to regressions and more complex analysis)

In future tutorials, we’ll work on more examples of #2, and start analyzing the data to find useful insights.

Before we start writing any code, let’s first understand when the P/E ratio is best used as a valuation method, and what type of stocks are best suited for it.

Let’s get started!

The Complete Guide to Building a P/E Ratio Indicator in ThinkOrSwim

Most traders rely solely on technical analysis, missing crucial fundamental insights that can dramatically improve their timing and stock selection. The price-to-earnings (P/E) ratio remains one of the most important valuation metrics, but seeing it in isolation on financial websites provides little context. In this comprehensive guide, you’ll learn how to build a powerful P/E ratio indicator that integrates seamlessly with your ThinkOrSwim charts, providing historical context and automated valuation analysis.

Understanding the P/E Ratio and Its Significance

The P/E ratio compares a company’s current stock price to its earnings per share (EPS), measuring how much investors are willing to pay for each dollar of earnings. The formula is straightforward:

P/E Ratio = Current Stock Price ÷ Earnings Per Share (TTM)

For example, if a stock trades at $24 and has EPS of $3 over the past twelve months, the P/E ratio is 8, meaning investors are paying 8 times annual earnings for the stock.

Why Traditional P/E Sources Fall Short

Financial websites like Yahoo Finance, Wall Street Journal, and Bloomberg provide current P/E ratios, but they lack critical context:

No Historical Perspective: Seeing that a stock has a P/E of 20 means little without knowing if it historically trades between 15-25 or 10-40. Historical context reveals whether current valuations represent opportunity or risk.

Limited Comparative Analysis: Static P/E numbers don’t show how valuations have evolved relative to business cycles, earnings growth, or market conditions.

Poor Integration: Fundamental data exists separately from technical analysis, making it difficult to identify opportunities where valuation and technical setups align.

The ThinkOrSwim P/E Advantage

Building P/E analysis directly into ThinkOrSwim provides several key advantages:

Historical Context: See how P/E ratios have fluctuated over multiple years, identifying patterns and extreme valuation levels.

Technical Integration: Combine valuation metrics with technical analysis to identify high-probability setups where both fundamentals and technicals align.

Real-Time Updates: As stock prices change throughout the day, see how P/E valuations shift in real-time.

Automated Analysis: Use conditional formatting and alerts to automatically identify when stocks reach historically attractive or expensive valuations.

When is the P/E ratio most useful?

I’ve found that the P/E ratio is a more useful valuation method, when trying to compare companies that are in the same industry, or a similar vertical.

These companies tend to have similar business models and operate under similar economic conditions, which makes comparisons “apples-to-apples.” Usually, they will have similar enough P/E ratios, with room to find inefficiencies that you can capitalize on.

For example… let’s say you’re trying to decide between two retail stocks, Walmart and Target. Both have dropped after their most recent earnings announcements, and dropped substantially at that.

WMT:

Walmart (WMT) PE Ratio Post Earnings

TGT:

Target (TGT) PE Ratio Post Earnings

They could be bargains at the current prices, but you’d like to see what their current valuation is, in relation to what it’s been previously.

Company Current P/E Lowest P/E Highest P/E Median P/E
Walmart (WMT) 19.50 10.28 37 27.78
Target (TGT) 12.62 8.85 25.32 17.63

 

While both are under their 200-day median P/E ratios, Target looks to currently be more “undervalued,” when compared to Walmart.

Using this as a starting point, you can dig deeper into respective companies to determine if they are ones you’d like to add to your portfolio.

To take it further, you could combine this ‘fundamental analysis’ with ‘technical analysis,’ focusing on finding bullish trades in undervalued companies, and bearish trades in overvalued companies.

It goes without saying – the P/E ratio is only one valuation method, and it should not be used in isolation.

P/E Ratio Calculation Methodology

Our indicator uses the trailing twelve months (TTM) approach, which calculates P/E based on the actual reported earnings from the past four quarters. This method provides several advantages over forward P/E calculations:

Accuracy: Based on actual reported earnings rather than estimates that may prove incorrect.

Consistency: TTM calculations use standardized reporting periods, making comparisons more reliable.

Timeliness: Updates automatically as new quarterly earnings are reported.

Building the P/E Ratio Indicator: Step-by-Step Guide

Step 1: Setting Up the Basic Structure

Start by creating a new custom study in ThinkOrSwim. Navigate to Studies > Create and name your indicator “P/E Ratio Analysis.” Since we want this indicator in the lower study area, begin with:

declare lower;

This ensures the P/E ratio plots in a separate panel below your price chart, providing clear visual separation between price action and valuation metrics.

Step 2: Handling Earnings Data

ThinkOrSwim provides earnings data through the GetActualEarnings() function, but this function returns values only on earnings announcement dates and NaN (not a number) on all other dates. We need to create a conditional structure to handle this:

def earningsValue = if IsNaN(GetActualEarnings()) then 0 else GetActualEarnings();

This creates a clean earnings value that equals the actual EPS on earnings dates and zero on non-earnings dates, preventing calculation errors.

Step 3: Calculating Trailing Twelve Months Earnings

To calculate TTM earnings, we sum the earnings values over the past year. The standard financial year contains approximately 252 trading days, so we use this period for our calculation:

def earningsTTM = Sum(earningsValue, 252);

This function adds up all earnings announcements over the past 252 trading days, providing the trailing twelve months earnings total needed for P/E calculation.

Step 4: Computing the P/E Ratio

With both price (current close) and TTM earnings available, we can calculate the P/E ratio:

plot PE = close / earningsTTM;

This creates the basic P/E calculation, but we need additional analysis to make it truly useful for trading decisions.

Step 5: Adding Historical Context

The real power comes from historical perspective. We’ll calculate the lowest, highest, and median P/E ratios over the visible chart period:

def lowestPE = LowestAll(PE);
def highestPE = HighestAll(PE);
def medianPE = median(PE, length = BarNumber());

These calculations provide crucial context for evaluating current valuations relative to historical norms.

Advanced Features and Enhancements

Dynamic Color Coding

To quickly identify valuation opportunities, we’ll implement dynamic color coding that changes based on current P/E relative to historical median:

AddLabel(yes, "Median PE: " + medianPE, 
         if PE <= medianPE then Color.LIGHT_GREEN else Color.LIGHT_RED);

This creates labels that turn green when the current P/E is below the historical median (potentially undervalued) and red when above (potentially overvalued).

Comprehensive Labeling System

Our indicator displays multiple labels for complete analysis:

  • Current P/E: Real-time valuation based on current price
  • Lowest P/E: Historical low point for context
  • Highest P/E: Historical high point for context
  • Median P/E: Middle point of historical range with color coding

Practical Trading Applications

Value Opportunity Identification

Use the P/E indicator to identify potential value opportunities:

Near Historical Lows: When current P/E approaches the historical lowest P/E, it may indicate oversold conditions and potential buying opportunities.

Below Median: Stocks trading below their historical median P/E may offer better risk-adjusted returns than those above median.

Technical Confirmation: Combine low P/E readings with technical support levels for high-probability value plays.

Risk Management Applications

Overvaluation Warnings: When P/E ratios approach historical highs, consider taking profits or avoiding new long positions.

Sector Rotation: Compare P/E levels across different sectors to identify where value opportunities may be migrating.

Market Timing: Use broad market P/E levels (SPY, QQQ) to gauge overall market valuation and adjust position sizing accordingly.

Limitations and Important Considerations

When P/E Analysis Doesn't Apply

Companies with losses (negative earnings) have undefined P/E ratios, making this analysis inappropriate for:

  • Loss-Making Companies: Early-stage growth companies or distressed situations
  • Cyclical Earnings Troughs: Companies experiencing temporary earnings weakness
  • One-Time Charges: Periods with significant non-recurring items affecting earnings

Industry Context Requirements

P/E ratios vary significantly across industries. Technology companies typically trade at higher P/E ratios than utilities or basic materials companies. Always compare P/E ratios within similar industries rather than across different sectors.

Optimizing the Indicator for Different Trading Styles

Swing Trading Applications

For swing traders holding positions for days to weeks:

  • Focus on stocks approaching historical P/E lows with technical support
  • Use P/E analysis to identify exit points when valuations become extended
  • Combine with earnings calendars to avoid holding through earnings announcements

Long-Term Investment Applications

For position traders and investors:

  • Build watchlists of quality companies trading below median P/E ratios
  • Use dollar-cost averaging strategies when P/E ratios are below historical medians
  • Set alerts for when favorite stocks reach attractive P/E levels

Troubleshooting Common Issues

P/E Calculation Discrepancies

You may notice slight differences between your ThinkOrSwim P/E calculations and those reported on financial websites. This occurs due to:

Timing Differences: Different sources may use different cut-off dates for TTM calculations.

Adjustment Methodologies: Some sources adjust for one-time items while others use raw reported earnings.

Share Count Variations: Different calculations for weighted average shares outstanding.

These differences are typically small and don't affect the relative analysis that makes this indicator valuable.

Missing or Inconsistent Data

If the indicator shows unusual values:

  • Verify the stock reports regular quarterly earnings
  • Check for recent stock splits or special dividends that may affect calculations
  • Ensure sufficient historical data exists for meaningful analysis

Advanced Customization Options

Timeframe Adjustments

Modify the historical analysis period by changing the LowestAll and HighestAll functions to use specific lookback periods:

def lowestPE5Years = Lowest(PE, 1260); // Approximately 5 years
def highestPE5Years = Highest(PE, 1260);

Alert Integration

Add automated alerts when stocks reach attractive valuations:

Alert(PE <= lowestPE * 1.1, "PE Near Historical Low", Alert.BAR);

This creates alerts when the current P/E drops within 10% of the historical low.

Integration with Other Fundamental Metrics

While P/E ratios provide valuable insights, combine them with other fundamental metrics for comprehensive analysis:

Price-to-Book Ratio: Provides asset-based valuation perspective

Price-to-Sales Ratio: Useful for companies with inconsistent earnings

Debt-to-Equity Ratio: Assesses financial leverage and risk

Return on Equity: Measures management effectiveness in generating returns

Market Cycle Considerations

P/E ratios behave differently across market cycles:

Bull Markets: P/E ratios tend to expand as optimism increases, making historically high P/E levels more common.

Bear Markets: P/E ratios contract as pessimism increases, creating opportunities at historically low levels.

Recession Periods: Earnings may be depressed, making P/E analysis less reliable during economic contractions.

Best Practices for P/E Analysis

Use Multiple Timeframes: Analyze P/E ratios on both daily and weekly charts to capture different perspectives.

Combine with Technical Analysis: The most effective approach combines attractive P/E levels with strong technical setups.

Maintain Watch Lists: Track quality companies and monitor when they reach attractive P/E levels.

Consider Earnings Quality: High P/E ratios may be justified for companies with strong earnings growth and quality.

Sector Context: Always evaluate P/E ratios relative to industry norms and competitors.

Conclusion: Integrating Fundamental and Technical Analysis

The P/E ratio indicator transforms static fundamental data into dynamic, actionable insights within your trading platform. By providing historical context and real-time updates, this tool enables you to identify value opportunities and avoid overvalued situations more effectively.

Remember that P/E analysis works best as part of a comprehensive approach that combines fundamental metrics with technical analysis and proper risk management. Use this indicator to enhance your stock selection process, improve entry and exit timing, and build a more disciplined approach to value-based investing.

The key to success lies in understanding that low P/E ratios don't automatically mean "buy" signals, just as high P/E ratios don't always mean "sell" signals. Context, industry comparisons, and earnings quality all play crucial roles in effective P/E analysis. Use this powerful tool to enhance your market awareness and improve your long-term trading results.

P/E Ratio Indicator.ts
# P/E Ratio for ThinkOrSwim

# Generated by TOS Indicators

# Full tutorial: tosindicators.com/indicators/p/e-ratio

# User Inputs

input length = 14;


// ... 23 more lines ...

Unlock This Code

Create a free account to access the full source code and download files.

Create Free Account Login
To build a P/E ratio indicator in ThinkOrSwim, create a custom study using GetActualEarnings() function with NaN protection, sum earnings over 252 trading days for TTM calculation, then divide current price by TTM earnings. Add historical context using LowestAll(), HighestAll(), and median() functions for comprehensive analysis.
P/E calculation differences occur due to timing variations in TTM periods, different adjustment methodologies for one-time items, and share count variations. These differences are typically small and don't affect the relative historical analysis that makes the indicator valuable for trading decisions.
Use daily charts for swing trading and weekly charts for long-term analysis. The indicator uses 252 trading days (approximately one year) for TTM earnings calculation, providing consistent results across timeframes. Historical context using LowestAll() and HighestAll() functions adapts to your chart's visible period.
P/E ratios work best for profitable companies with consistent earnings. They're not suitable for loss-making companies, early-stage growth companies, or during periods with significant one-time charges. Always verify positive TTM earnings before relying on P/E analysis for trading decisions.
Green labels indicate the current P/E is below the historical median, suggesting potential undervaluation. Red labels show P/E above median, indicating potential overvaluation. Use this as a starting point for analysis, but always combine with technical analysis and industry context for trading decisions.
For swing trading, look for stocks approaching historical P/E lows combined with technical support levels. Use P/E analysis to identify value opportunities and exit points when valuations become extended. Avoid holding through earnings announcements unless specifically trading earnings moves.
The P/E ratio updates in real-time as stock prices change throughout the trading day. TTM earnings update quarterly as companies report new earnings. The indicator automatically recalculates historical metrics (lowest, highest, median) as new data becomes available.
No, always compare P/E ratios within similar industries rather than across different sectors. Technology companies typically trade at higher P/E ratios than utilities or basic materials. Use industry-specific context and competitor comparisons for meaningful P/E analysis in your trading decisions.

Here are some resources that you may find useful:

  • How to import an indicator into ThinkOrSwim (video tutorial)
Featured Tools:
Stock Volatility Box

Stock Volatility Box

Spot reversal zones across 600 stocks & ETFs.

  • Hourly & daily models
  • Powerful Live Scanner
  • Built for day traders
Futures Volatility Box

Futures Volatility Box

Pinpoint reversal zones in 10 major futures markets.

  • 5 models (incl. Scalper)
  • ThinkOrSwim & TradingView
  • SPX traders
ORB Setups

ORB Setups

Find the best Opening Range Breakout setups.

  • Powerful real-time scanner
  • Instant backtests
  • 2+ years data

Get Free Access

Create a free account for downloads and new tutorial alerts.

Create Free Account

More Tutorials Like This

Market Pulse

Market Pulse

Beginner-Friendly • 40 mins
Parabolic SAR

Parabolic SAR

Intermediate • 65 minutes
Cash-Secured Put Calculator

Cash-Secured Put Calculator

Intermediate • 10 minutes

Ready to Trade With an Edge?

Join 40,000+ traders using institutional-grade tools for ThinkOrSwim.

Get the Bundle
TOS Indicators

Premium thinkorswim indicators, scans, and trading tools to help you trade smarter.

ThinkOrSwim Tools

  • Indicators
  • Scans
  • Backtesters
  • Dashboards
  • thinkScript
  • Browse All

Courses

  • Squeeze Course
  • Earnings Course
  • V-Shaped Reversals
  • Fibonacci Trading

Products

  • Futures Volatility Box
  • Stock Volatility Box
  • ORB Setups
  • Shop All

Guides

  • TTM Squeeze
  • Automated Trading
  • Volatility Trading
  • Opening Range Breakouts
  • Trade Reports
  • Contact Us

© 2026 TOS Indicators. All rights reserved.

Privacy Policy Terms of Service Disclaimer

The information contained on this website is solely for educational purposes, and does not constitute investment advice. The risk of trading in securities markets can be substantial. You must review and agree to our Terms of Service prior to using this site.

U.S. Government Required Disclaimer - Commodity Futures Trading Commission. Futures and options trading has large potential rewards, but also large potential risk. You must be aware of the risks and be willing to accept them in order to invest in the futures and options markets. Don't trade with money you can't afford to lose. This website is neither a solicitation nor an offer to Buy/Sell futures or options. No representation is being made that any account will or is likely to achieve profits or losses similar to those discussed on this website. The past performance of any trading system or methodology is not necessarily indicative of future results.

Individual results may vary, and testimonials are not claimed to represent typical results. All testimonials are by real people, and may not reflect the typical purchaser's experience, and are not intended to represent or guarantee that anyone will achieve the same or similar results.

TOS Indicator's Traders and employees will NEVER manage or offer to manage a customer or individual's options, stocks, currencies, futures, or any financial markets or securities account. If someone claiming to represent or be associated with TOS Indicator solicits you for money or offers to manage your trading account, do not provide any personal information and contact us immediately.

CFTC RULE 4.41 - HYPOTHETICAL OR SIMULATED PERFORMANCE RESULTS HAVE CERTAIN LIMITATIONS. UNLIKE AN ACTUAL PERFORMANCE RECORD, SIMULATED RESULTS DO NOT REPRESENT ACTUAL TRADING. ALSO, SINCE THE TRADES HAVE NOT BEEN EXECUTED, THE RESULTS MAY HAVE UNDER-OR-OVER COMPENSATED FOR THE IMPACT, IF ANY, OF CERTAIN MARKET FACTORS, SUCH AS LACK OF LIQUIDITY, SIMULATED TRADING PROGRAMS IN GENERAL ARE ALSO SUBJECT TO THE FACT THAT THEY ARE DESIGNED WITH THE BENEFIT OF HINDSIGHT. NO REPRESENTATION IS BEING MADE THAT ANY ACCOUNT WILL OR IS LIKELY TO ACHIEVE PROFIT OR LOSSES SIMILAR TO THOSE SHOWN.