Skip to main content Post-Election Backtester For ThinkOrSwim (FREE) 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-Friendly 10 mins ThinkOrSwim

Post-Election Backtester

Backtest how often the markets rally after each U.S. election, to find common patterns post 30 days, 60 days, and 90 days.

Download Backtester
How to install in ThinkOrSwim →
Table of Contents
  • What Does the Post-Election Backtester Do?
  • Step 1: Input Historical Election Dates
  • Step 2: Create a Variable for Election Days
  • Step 3: Set the Holding Period
  • Step 4: Add Buy and Sell Orders
  • Step 5: Test and Analyze Results
  • Tips for Optimizing the Backtester
  • Conclusion

Understanding how markets react post-election can be a powerful tool for traders.

In this tutorial, I’ll walk you through creating a simple yet effective post-election backtester in ThinkOrSwim (TOS). This tutorial covers how to code the backtester, input election data, and interpret the results.

Whether you’re curious about volatility trends or exploring the viability of an election-based strategy, I think you’ll find that this thinkScript tutorial will open you up to a world of possibilities.

What Does the Post-Election Backtester Do?

This backtester is designed to analyze price movement after U.S. presidential elections. It uses historical election dates to test a strategy of holding a position for a set number of days after election results. Key metrics include:

  • Profit/Loss: Measures the performance of holding positions post-election.
  • Success Rate: Tracks how often the strategy yields positive results.
  • Timeframe Flexibility: Tests different holding periods (30, 60, or 90 days).

By comparing results across multiple elections, you’ll gain insights into whether this approach has a repeatable edge or is just market noise.

Step 1: Input Historical Election Dates

First, we need to define the election dates to use as reference points for the backtester. The code below lists U.S. presidential election dates from 2000 to 2020:


def election1 = 20201103;
def election2 = 20161108;
def election3 = 20121106;
def election4 = 20081104;
def election5 = 20041102;
def election6 = 20001107;

Why This Format?

The ThinkOrSwim function getYYYYMMDD() retrieves the date of each bar in the format YYYYMMDD. By storing election dates in this format, we can easily compare them to the current date and trigger actions in the backtester.

Step 2: Create a Variable for Election Days

Next, we need to identify if a particular bar matches any of our defined election dates. Here’s how:


def electionDay = getYYYYMMDD() == election1 or getYYYYMMDD() == election2 
                  or getYYYYMMDD() == election3 or getYYYYMMDD() == election4 
                  or getYYYYMMDD() == election5 or getYYYYMMDD() == election6;

How It Works

  • getYYYYMMDD(): Fetches the date for each bar in the chart.
  • Logical comparison: Checks if the date matches any of the six defined election dates.
  • Output: Returns true if the bar corresponds to an election date, otherwise false.

This variable serves as the foundation for triggering buy or sell orders in the strategy.

Step 3: Set the Holding Period

We’ll now create an input variable to define how many days to hold a position post-election:


input postElectionDays = 30;

Why Use an Input Variable?

The input keyword allows you to modify the holding period directly from the strategy settings, making the backtester flexible for testing different timeframes. While the default is set to 30 days, you can adjust it to 60 or 90 days based on your analysis goals.

Step 4: Add Buy and Sell Orders

With the election dates and holding period defined, we can now set up buy and sell orders:


AddOrder(OrderType.Buy_To_Open, electionDay[1], open);
AddOrder(OrderType.Sell_To_Close, electionDay[postElectionDays], close);

Breaking Down the Code

  • Buy Order: Executes on the bar after the election date (electionDay[1]), using the open price of that bar.
  • Sell Order: Closes the position after the specified holding period (postElectionDays), using the closing price of that bar.

This logic ensures that the strategy simulates buying immediately after election results and exiting after the desired holding period.

Step 5: Test and Analyze Results

Once the code is implemented, run the backtester on historical data. You’ll see a report summarizing the strategy’s performance for each election cycle. Key points to note:

  • Profitability: Compare the total P&L for each holding period (30, 60, and 90 days).
  • Bear Market Years: Notice how elections during 2000 and 2008 (bear market years) yielded poor results, highlighting the importance of market context.
  • Instrument Variability: Test the strategy across different instruments (e.g., SPY, QQQ, or Dow futures) to identify patterns.

Example Insights

In SPY, the 2020 election contributed significantly to positive P&L, but earlier elections showed mixed results. Extending the holding period to 60 or 90 days didn’t consistently improve profitability, suggesting that post-election volatility may not always follow a predictable pattern.

Tips for Optimizing the Backtester

Here are some ways to enhance and adapt the backtester for deeper analysis:

  • Market Context: Incorporate additional variables like pre-election market trends or volatility levels.
  • Party Analysis: Examine results based on which party won the election to identify potential biases.
  • Additional Instruments: Test leveraged ETFs (e.g., TQQQ) or sector-specific indices for more granular insights.
  • Holding Periods: Experiment with custom holding periods to find optimal timeframes for specific market conditions.

Conclusion

The Post-Election Backtester offers a straightforward way to analyze market behavior following U.S. presidential elections. While this tutorial provides a foundational strategy, you can expand it further to account for market context, instrument specificity, and alternative holding periods. Use this as a starting point to explore post-election volatility and refine your trading strategies. Good luck, and happy backtesting!

Election Backtester.ts
## Input Variables

input postElectionDays = 30;

## Election Dates Going Back to 2000

## Demoractic Party = 1; Republican Party = 2;

def election1 = 20201103;


// ... 27 more lines ...

Unlock This Code

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

Create Free Account Login
The most effective way is to use a trading platform like ThinkorSwim (TOS) and write a custom ThinkScript strategy. By inputting historical election dates (e.g., from 2000 to 2024), you can automate the process of "buying" the day after an election and "selling" after a set period, such as 30, 60, or 90 days, to measure the strategy's profitability.
Not necessarily. While many traders look for "post-election volatility" to drive prices higher, historical backtesting shows that results vary. For example, during the bear markets of 2000 and 2008, the strategy of holding stocks post-election resulted in losses rather than gains.
Based on the backtest in this video, increasing the holding period doesn't always improve results. Testing on the QQQ showed that extending the hold to 90 days actually caused the strategy's P&L to drop compared to shorter windows. It is crucial to test 30, 60, and 90-day intervals to see where the actual "edge" lies.
Yes. Many traders investigate using triple-leveraged ETFs like TQQQ to capitalize on post-election moves. However, because these ETFs may not have data going back to the year 2000, it is often better to run your backtest on the QQQ (Nasdaq 100) or Nasdaq Futures first to get a larger sample size of election cycles.
In ThinkScript, you can store dates in a variable using the format YYYYMMDD. For a backtest, you would create variables for each election year (e.g., election1 = 20201103) and then use the GetYYYYMMDD() function to tell the script to execute an order whenever the current chart candle matches one of those dates.
While some Reddit communities suggest using election volatility to grow small accounts, the data suggests caution. Backtesting across the SPY, QQQ, and Dow Jones shows that recent gains (like the 2020 election) drive a majority of the strategy's total profit, making the overall edge appear more "mediocre" when looking at the last six election cycles.
This is a common "quirk" of the ThinkorSwim platform. When coding a strategy to enter on the bar following a signal, the report may show the entry date as one day after the actual execution point. The script provided in the tutorial accounts for this to ensure the opening price of the post-election candle is used for an accurate P&L calculation.
The script includes an input variable called post_election_days, which is set to a default of 30. You can easily adjust this number in the ThinkorSwim "Edit Studies and Strategies" menu to instantly see how changing your holding period affects your win rate and total profit without rewriting the code.

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

Moving Average Crossover Backtester

Moving Average Crossover Backtester

Beginner • 14 minutes
SPY Meltdown Backtester

SPY Meltdown Backtester

Beginner-Friendly • 8 mins
Santa Claus Rally Backtester

Santa Claus Rally Backtester

Beginner • 14 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.