Skip to main contentSkip to content
Squeeze Setups A live squeeze scanner built around the Slingshot Squeeze, with 22 years of backtest results behind it. See it, $99/month →
TOS Indicators
  • Tools

    Categories

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

    Featured Tutorials

    Fair Value Gap Indicator
    Fair Value Gap Indicator
    Indicators

    Download our free Fair Value Gap indicator for ThinkorSwim. It shades every...

    Learn more →
    False Breakout Scanner for ThinkorSwim (Free Scan Pair)
    False Breakout Scanner for ThinkorSwim (Free Scan Pair)
    Scans

    A two-scan pair that flags failed breakouts and failed breakdowns with volume...

    Learn more →
    Heiken Ashi Trend Indicator
    Heiken Ashi Trend Indicator
    Indicators

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

    Learn more →

    Popular Posts

    Unusual Volume Pro Scans
    Unusual Volume Pro Scans
    Scans

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

    Learn more →
    High Short Interest Near 52 Week Highs (thinkScript)
    High Short Interest Near 52 Week Highs (thinkScript)
    Scans

    Build a simple scan in which to find stocks that...

    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 →
  • Courses
    Squeeze Course
    Squeeze Course
    19 Modules

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

    View Course →
    Earnings Course
    Earnings Course
    3 Modules

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

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

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

    View Course →
    Fibonacci Trading
    Fibonacci Trading
    4 Modules

    Learn to trade Fibonacci retracements and extensions in ThinkOrSwim effectively.

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

    Volatility models for 10 major futures markets, including the micros.

    Explore Futures VB →
    Stock Volatility Box Premium
    Stock Volatility Box

    Volatility levels for 600+ stocks and ETFs, with a live scanner.

    Explore Stock VB →
    Opening Range Breakouts Premium
    Opening Range Breakouts

    Scans 600+ stocks every 2 seconds for opening range breaks, with a backtester.

    Explore ORB Setups →
My Account
All Indicators
Beginner 13 minutes ThinkOrSwim

How to Plot the P/E Ratio in ThinkorSwim With 10 Years of History

A free P/E ratio indicator for ThinkorSwim. It plots the trailing 12-month P/E as a line, with labels for the current, lowest, highest and median P/E.

Download Indicator
How to install in ThinkOrSwim →
Table of Contents
  • Key Takeaways
  • What Is the P/E Ratio?
  • Why Plot the P/E Ratio in ThinkorSwim
  • How the P/E Ratio Code Works
  • How to Add the P/E Ratio Indicator to ThinkorSwim
  • Starbucks and Costco in the Video
  • Why ThinkorSwim’s P/E Differs From Yahoo Finance
  • Changing the Chart Length
  • Reading the Indicator on Other Stocks
  • How I Use the P/E Ratio
  • Common Problems and Fixes

In this tutorial I plot the P/E ratio in ThinkorSwim with a few lines of thinkScript. The indicator divides the closing price by the earnings reported over the past 252 trading days, draws that trailing 12-month P/E as a line under the chart, and adds labels for the current, lowest, highest and median P/E.

Sites like Yahoo Finance and the Wall Street Journal show you today’s P/E. In ThinkorSwim you also get the history behind it, 10 years or more, and you can line it up with the chart setups you already trade. It’s for investors and swing traders who value companies with steady earnings.

Key Takeaways

  • The P/E Ratio indicator divides the close by trailing 12-month earnings: the sum of GetActualEarnings() over the last 252 daily bars. It plots as a line in a lower pane.
  • The indicator’s 4 labels show the current P/E (white), the lowest and highest P/E on the chart (yellow), and the median P/E of the last 200 bars, light green when the current P/E is at or below it and light red when above.
  • In the video, Starbucks read a P/E of 21.6657 in ThinkorSwim, against 19.19 on Yahoo Finance and 19.26 on the Wall Street Journal.
  • On a 10-year daily chart, Starbucks’ lowest P/E was 10.7916, its highest 120.755 in April 2021 and its median 21.97. In March 2020 it fell to 19.70.
  • The P/E ratio is close to useless when earnings are negative. It works best on stocks with steady earnings.

What Is the P/E Ratio?

The P/E ratio, or price-to-earnings ratio, is a stock’s price divided by its earnings per share. A P/E of 20 means investors pay $20 for each $1 of yearly earnings. The trailing P/E uses the last 12 months of reported earnings, and the forward P/E uses estimates for the next 12 months. This indicator is a trailing P/E.

A P/E that’s low for the stock’s own history means the market is pricing its earnings more cheaply than usual. A high one means investors are paying up. Neither tells you why, so the P/E is a starting point for research.

The P/E ratio doesn’t fit every stock. If earnings are negative, the number is close to useless. It’s most useful where earnings are steady and the P/E has traditionally been a good way to value the company. For a valuation based on assets instead, see our price to book ratio indicator, and for income stocks, our dividend yield indicator.

Why Plot the P/E Ratio in ThinkorSwim

Plotting the P/E ratio in ThinkorSwim gives you 2 things a quote page doesn’t:

  • Context. Yahoo Finance or the Wall Street Journal show the P/E right now. On a chart you see how it has moved over 10 years or more, so you can tell whether today’s reading is high or low for that company.
  • Interaction. You can run calculations on the P/E, like its lowest, highest and median values, and line it up with technical setups on the same chart.

In the video I use Starbucks as the example. Its chart had a technical setup, and its P/E was near the level of its March 2020 low. Seeing both in one place is the reason to build this.

Visa 10-year daily chart with the P/E Ratio study in a lower pane, showing the P/E line and its four labels
The P/E Ratio study in the lower pane of a 10-year daily Visa (V) chart. The 4 labels in the top left show the current, lowest, highest and median P/E.

How the P/E Ratio Code Works

The P/E ratio formula has the price on top and trailing 12-month earnings on the bottom. ThinkorSwim already has the price: it’s close. Earnings take 2 steps.

Step 1: Earnings on Earnings Days

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

GetActualEarnings() returns the reported earnings per share on an earnings day and NaN (not a number) on every other bar. The if IsNan(...) then 0 part turns those empty bars into 0, so the sum in the next step works.

To check it, I plotted earningsValue in chart bubbles. They matched the earnings figures along the bottom of the Starbucks chart: 0.32, -0.46 and 0.51. The download keeps a commented-out bubble line at the bottom that prints the P/E in a bubble on every bar: delete the # to turn it on.

Step 2: Trailing 12-Month Earnings

def earningsTTM = Sum(earningsValue, 252);

Sum adds up the last 252 bars, one trading year on a daily chart, which normally covers the last 4 quarterly reports. In the video, Starbucks’ trailing 12-month earnings came to 3.32.

Step 3: The P/E Line

declare lower;
plot pe  = close / earningsTTM;

declare lower puts the study in its own pane under the price chart. I first wrote pe as a def and looked at it in chart bubbles. Changing it to plot draws a line, so you see how the P/E moved year by year.

Step 4: Lowest, Highest and Median

def LowestPE = LowestAll(pe);
def HighestPE = HighestAll(pe);
def MedianPE = Median(pe,200);

LowestAll and HighestAll read every bar loaded on the chart, so on a 10-year chart they give the cheapest and most expensive the stock has been in 10 years.

Median(pe,200) is the middle value of the last 200 bars, about 9 to 10 months of daily bars, so the median label covers the same window on a 10-year or a 20-year chart. For a longer median, raise the 200 (an edit that isn’t in the video).

Step 5: The Labels

AddLabel(yes, "P/E Ratio: " + pe, color.white);
AddLabel(yes, "Lowest P/E: " + LowestPE, color.yellow);
AddLabel(yes, "Highest P/E: " + HighestPE, color.yellow);

The first 3 labels print the current P/E in white and the lowest and highest P/E in yellow.

AddLabel(yes, "Median P/E: " + MedianPE, if pe <= MedianPE then color.light_green else color.light_red);

The median label is the one I read first. It turns light green when the current P/E is at or below the median and light red when it’s above, a first read on whether the stock is in cheaper territory than usual. If you’re new to labels, our AddLabel tutorial covers the syntax.

Label What it shows Color
P/E Ratio Close divided by trailing 12-month earnings White
Lowest P/E Lowest P/E on the chart Yellow
Highest P/E Highest P/E on the chart Yellow
Median P/E Median P/E of the last 200 bars Light green at or below the median, light red above

How to Add the P/E Ratio Indicator to ThinkorSwim

The P/E ratio indicator is one study, and these are the steps I follow in the video:

  1. Copy the code from the Code tab on this page, or download the .ts file.
  2. In ThinkorSwim, open the Charts tab, click the Studies icon and choose Create.
  3. Delete the default code, paste in the P/E code, name the study and click OK.
  4. Add it to a daily chart. It opens in a lower pane because of declare lower.
  5. Set the chart’s time frame to 10 years of daily bars, the setting I use in the video.

The download is the same code as the Code tab. To import the .ts file instead of pasting, follow our guide on how to import a study into ThinkorSwim.

Starbucks and Costco in the Video

Starbucks is the main P/E ratio example in the video, with Costco as a second check. These are the values from the day I recorded, on 10-year daily charts:

Stock Current P/E Lowest P/E Highest P/E Median P/E
Starbucks 21.6657 10.7916 120.755 (April 2021) 21.97
Costco 34 16 49 39.95

Starbucks had hit its 127.2% Fibonacci extension and pulled back to its 50% retracement. At the same time, its P/E of 21.67 was getting close to the 19.70 it fell to in March 2020, and it sat a little below its median. That pairing of a technical pullback with a P/E near past lows is how I look for undervalued spots. Our Fibonacci Trading Course covers those levels.

Costco was below its median of 39.95 too, at a P/E of 34. Against its lowest P/E of 16, though, it still had room to fall. The labels give you a baseline for what counts as cheap for each stock.

Why ThinkorSwim’s P/E Differs From Yahoo Finance

The P/E ratio in ThinkorSwim won’t always match other sites. In the video, Starbucks read 21.6657 in ThinkorSwim, 19.19 on Yahoo Finance and 19.26 on the Wall Street Journal: close, with a slight gap.

The benefit of the ThinkorSwim number is consistency. The indicator measures today’s P/E and every past P/E on the chart the same way, so comparing the stock with its own history is apples to apples.

Changing the Chart Length

The lowest and highest P/E labels change with the chart’s time frame, because LowestAll and HighestAll read every loaded bar. The current and median labels don’t. When I switched Starbucks from 10 years to 20 years, the lowest P/E reached further back, and the Highest P/E label stopped plotting, since the data didn’t go back before 2008. I went back to 10 years for the rest of the video.

The 252 in the code means 252 bars, one trading year on a daily chart, so keep the study on a daily chart.

Reading the Indicator on Other Stocks

The P/E ratio indicator works the same way on any stock that reports earnings. The screenshots below show it on Walmart and Target on May 20, 2022, each on a 10-year daily chart. In both, the price and the P/E line drop sharply at the right edge, and the median label is green, so the current P/E sits at or below its 200-bar median.

Walmart 10-year daily chart with the P/E Ratio study in the lower pane and a green Median P/E label
Walmart (WMT) on a 10-year daily chart on May 20, 2022. The price and the P/E line fall sharply at the right edge, and the green Median P/E label means the current P/E is at or below its 200-bar median.
Target 10-year daily chart with the P/E Ratio study in the lower pane and a green Median P/E label
Target (TGT) on a 10-year daily chart on May 20, 2022, with the same sharp drop in price and in the P/E line at the right edge, and a green Median P/E label.

A green median label is the first read. Next, compare the current P/E with the lowest and highest labels, and check the price chart for a setup.

How I Use the P/E Ratio

The P/E ratio indicator gives me a baseline for value, and the chart decides the timing. The setup I want is a P/E near the low end of the stock’s own range, with the median label green, plus a technical setup like Starbucks’ pullback to its 50% retracement.

A low P/E can get lower, so treat a green label as a read on value, not an entry. Decide where your stop goes before you buy, and size the position so a stop-out costs a small, fixed share of your account.

If you like working with data, you can take it further with range calculations on the same P/E series to define what you consider undervalued. For other ways to value a company, compare the P/E with our Dividend Discount Model for dividend payers, or with the price to book ratio for a view based on book value.

Common Problems and Fixes

Most P/E ratio indicator problems come from the data behind it:

  • Negative or strange readings. If a company lost money over the last 12 months, the P/E has no useful meaning. The fix is to value those stocks another way.
  • A different number from Yahoo Finance. Expected. Compare the stock with its own history in ThinkorSwim instead of matching another site to the decimal.
  • No Highest P/E label on a 20-year chart. In the video this happened on Starbucks, with no data before 2008. Go back to a 10-year chart.
  • Labels you’d like in other colors. Edit the color in each AddLabel line. I started the median label as color.cyan in the video before switching to the green and red version.
P/E Ratio Indicator.ts
#TOS Indicators
#Home of the Volatility Box
#Indicator: P/E Ratio
#Code written in 2022
#Full Tutorial: https://www.tosindicators.com/indicators/pe-ratio

declare lower;

def earningsValue = if IsNan(GetActualEarnings()) then 0 else GetActualEarnings();
def earningsTTM = Sum(earningsValue, 252);
plot pe  = close / earningsTTM;

def LowestPE = LowestAll(pe);
def HighestPE = HighestAll(pe);
def MedianPE = Median(pe,200);

AddLabel(yes, "P/E Ratio: " + pe, color.white);
AddLabel(yes, "Lowest P/E: " + LowestPE, color.yellow);
AddLabel(yes, "Highest P/E: " + HighestPE, color.yellow);
AddLabel(yes, "Median P/E: " + MedianPE, if pe <= MedianPE then color.light_green else color.light_red);


#AddChartBubble(pe, close, pe, color.yellow);

Want the .ts file and the one-click import? Both come with a free account.

Create Free Account Login
Open the Charts tab, click Studies, choose Create and paste in the code from this page. It sums GetActualEarnings() over 252 daily bars for trailing 12-month earnings, divides the close by that sum, and plots the P/E in a lower pane with labels for the current, lowest, highest and median P/E.
Divide the stock price by earnings per share. The trailing P/E uses the last 12 months of reported earnings. In the video, Starbucks' trailing 12-month earnings came to 3.32, and dividing the close by that gave a P/E of 21.6657 in ThinkorSwim.
The sources don't always agree. In the video, Starbucks read 21.6657 in ThinkorSwim, 19.19 on Yahoo Finance and 19.26 on the Wall Street Journal. The indicator's value is the history: it measures today's P/E and past P/E the same way, so comparing a stock with itself stays consistent.
It shows the median P/E of the last 200 bars. The label turns light green when the current P/E is at or below the median and light red when it's above. In the video, Starbucks had a median of 21.97 and a current P/E of 21.6657, so it was trading a little under its median.
As far back as the chart's time frame. On a 10-year daily chart, the lowest and highest labels cover 10 years. When I switched Starbucks to 20 years, the lowest P/E reached further back, but the Highest P/E label stopped plotting because the data didn't go back before 2008. The median label always uses the last 200 bars.
No. If a company's earnings are negative, the P/E ratio is close to useless. It works best on stocks with steady earnings, where the P/E has traditionally been a good valuation measure. For other angles, look at book value with our price to book ratio indicator, or at dividends.
There's no single number. A P/E means most against the stock's own history. In the video, Costco's P/E of 34 was below its median of 39.95 but well above its lowest of 16, while Starbucks at 21.67 was close to its March 2020 low of 19.70.
It returns the reported earnings per share on the bar where the company reported, and NaN on every other bar. The P/E indicator turns those NaN values into 0, so Sum() can add up the last 252 bars into trailing 12-month earnings.

Here are some resources that you may find useful:

  • How to import a study into ThinkOrSwim (video tutorial)
  • Price to Book Ratio indicator for ThinkOrSwim
  • Dividend Yield indicator for ThinkOrSwim
  • Dividend Discount Model
  • AddLabel function tutorial
  • More free ThinkOrSwim indicators
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

Related tutorials and research

Price to Book Ratio Indicator and Scan for ThinkorSwim

Price to Book Ratio Indicator and Scan for ThinkorSwim

Indicators · Beginner
How to Build a Fair Value Gap Indicator in ThinkorSwim

How to Build a Fair Value Gap Indicator in ThinkorSwim

Indicators · Beginner-Friendly
How to Build a Heiken Ashi Trend Dots Indicator in ThinkorSwim

How to Build a Heiken Ashi Trend Dots Indicator in ThinkorSwim

Indicators · Beginner-Friendly
How to Build a Commodities Tracker in ThinkorSwim

How to Build a Commodities Tracker in ThinkorSwim

Indicators · Beginner
Trend Squeeze Indicator for ThinkorSwim

Trend Squeeze Indicator for ThinkorSwim

Indicators · Beginner
Volume Intensity Indicator for ThinkorSwim

Volume Intensity Indicator for ThinkorSwim

Indicators · Beginner-Friendly

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 Accessibility

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.