- 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.
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.
- 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.
- 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)
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:
TGT:
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 for ThinkOrSwim
# Generated by TOS Indicators
# Full tutorial: tosindicators.com/indicators/p/e-ratio
# User Inputs
input length = 14;
// ... 23 more lines ...Here are some resources that you may find useful: