SPY Swing Trading Strategy: 82% Winners Using 3 Lines of Code



  • Home
  • /
  • Blog
  • /
  • SPY Swing Trading Strategy: 82% Winners Using 3 Lines of Code

It's time to stop treating your spy swing trading as a hobby, it's time to get serious.

Understanding the exact odds of every trade you make is the only way to make consistent money swing trading stocks.

Therefore, I want to share three lines of code in a simple swing trading strategy that you can use to time the S&P 500 with amazing odds.

And the best part is you don't even need a computer, but some basic counting is required.

Let's get started!


The Trend Is Your Friend When Swing Trading SPY

I used to listen to TV personalities and internet gurus, but I never made any money.

Actually, I lost a lot.  

How could so many "pro traders" be so wrong all the time?  

I still remember the day, around 2006, when I threw up my hands in disgust over another "pro trader's" opinion that lost me a ton of money.

I decided then and there that I was going to TEST any and all trading ideas I could get my eager hands on before I risked another dime of my hard-earned money.

Of all the ideas I tested, gleaned off internet forums and blowhards on TV, only one was true:

"The trend is your friend."

The "trend" is which way a market is moving, and there are three directions, sideways, down, or up.  

You only want to trade in the direction of the trend.

Sounds intuitive, but I've known plenty of traders that fight the trend trying to call tops bottoms.

They don't make money, they just want to brag to their friends or resentful spouse about how they were "right".  

Betting against a market's direction is the stupidest thing you can do with your money, besides heading to Vegas.

The simplest way to determine the trend is with a moving average.  

The 200 and 100-day moving averages are standard for many swing traders, but we're going to use a non-standard one to stay away from the herd.

Let's use the SPY ETF (which tracks the S&P 500) to demonstrate the first line of code in this SPY swing trading strategy.  

Looking at closing prices only, let's ask the computer if SPY is above its 66-day moving average:

	If close > average (close, 66)

If this expression is true, we want to look for swing trades in the long direction.  

You only want to buy if the price is above the 66-day moving average (this also works on individual stocks and many commodities).

Now, let's move on to the second part of our swing trading strategy, when exactly do you trade SPY?

Only Buy Dips in SPY in Uptrends

Once you establish that the market is moving higher, you want to buy dips.

You never want to short an up-trending market because you will get your head handed to you.

I don't know why so many amateur traders love to short stocks.

Humans tend to overestimate their abilities and this is where I think a lot of that psychology comes from.

Check yourself if you are thinking "I'm smarter than the markets".

Nope, you aren't, and neither am I, that's why we test our ideas first.

OK, so how do you tell a computer what a dip is?

You must use absolute quantifiable terms here; you can't just say "the market should find support here."

Also, you must keep your definition of a dip super simple.

You don't want to over-optimize and run the risk of curve-fitting your SPY swing trading strategies.

So, let's look at SPY and ask the computer a simple question, is today's close the lowest in 3 days?  

(You can play around with this number, but I've found 3 works well)

	If close < lowest(close, 3)

If this expression is true you have yourself a "dip".

You now have an uptrend established and a dip in the uptrend and it's time to buy!

(This proves to be remarkably profitable as you will see in a minute)

The SPY Trading System Sell Signal

Do you know what the hardest part of trading really is?  

It's not knowing when to buy, it's knowing when to sell.  

You might intuitively already know that.  

How many stocks have you held onto for too long?

Anecdotally, my brother once showed me his portfolio and it was full of losers!  

I asked him what was going on, and he responded: "I just never know when to sell."

This is why it is so important to have a trading system in place, especially when swing trading stocks. 

Getting in is easy, getting out is hard.

So how do you know when to sell your position in SPY once you bought the dip?  

You have to let the market mean-revert to the upside and then sell into that rally.

But what is a "rally" and how do you think like a computer to give it exact instructions?  

Well, let's use the inverse of how we defined a dip above.

Let's ask the computer to tell us when SPY has made a close higher than the previous 19 days.

	If close  >= highest(close, 19)

If this expression is true, it's time to sell SPY and most likely bank a nice profit.  

Okay, let's wrap these three simple ideas into a swing trading strategy for SPY.  

Then let's plug it into the computer and see what happens.

Computers don't lie to your face like the suits on Wall Street or internet grifters selling doom and gloom and "technical analysis".  

Let's recap what we've put together so far in visual form:

Simple SPY Swing Trading Strategy Flowchart:

spy swing trading strategy flowchart

It's truly that simple, these trading strategy rules are about as basic as they come.

Let's look at how unbelievably powerful this little SPY swing trading strategy is.

SPY 3 Lines of Code Performance Graph 2024

Each of those green dots is a new equity high for this trading model.  

Incredible isn't it?  

This is the power of testing ideas before jumping headfirst into the stock market.

Let's look at some example trades produced by this simple SPY swing trading strategy:

SPY 3 Lines of Code Examples 2024

You can see when SPY dips it's usually very profitable to be a buyer.  

I often get asked if this is the best SPY Options Trading Strategy.

I usually recommend people stay away from options unless they really know what they are doing.

There are too many variables for my liking, and also wow that leverage can absolutely kill your portfolio.

I like to keep it relaxed as you know, so I stick with stocks and ETFs.

Continuing on, let's look at the statistics of this simple SPY swing trading strategy:

SPY 3 Lines of Code Performance Statistics 2024

Can you believe such simple rules can time the stock market with such great odds?

Next time you are about to trade, ask yourself if you truly know the odds of making or losing money.

Because if you don't know the exact odds how do you even know how much money to risk?

So, I implore you to always test your ideas before you risk another dime.

Learning From This SPY Swing Trading Strategy

  • Only trade in the direction of the trend, never against it!
  • Buy dips in up-trends and sell into rallies
  • A tested trading system can unlock massive profits

This is a long only system, imagine what the profits would be if you added shorting to it; play around with it, see if you can make it even better!

Happy Trading!

Want The Code?

Start developing and trading your own strategies today!

About the Author

Hello! I'm Kurt, the "Relaxed Trader" writing the stuff on this website. Shoot me an email at kurt@relaxedtrader.com or leave a comment below. Cheers!

  • David Gates says:

    Kurt I would really like to try out your spy strategy. I just opened up a trade station account and would like to know if you could send me an email on where I would enter the code at on trade station. Also I would like to find out if I can also use it in the paper trading account.
    Your help would be greatly appreciated.

    Thank you
    David Gates

  • What are your thoughts on adding another rule: ONLY sell if the sale is profitable? I ran an analysis using the past few years of SPY prices and it looks like that rule makes a big difference in beating the performance of straight buy and hold in a sideways market

  • Do you have the short swing trading flowchart for SPY? TIA

  • Great article! What are the position sizes for each trade? Do the sell conditions also need to be above the 66 moving average? Where can we also find the code? Thanks a bunch!

  • Great system!!! Are the buys triggered at the close (on the day the condition is triggered) or at the open the next trading day?
    Thanks very much!

    • Hi Brad!

      The system buys at the open of the next trading day.

  • Don’t forget get to import Pandas, haha. Pretty good article, I will try this out and let you know how it goes!

    • Glad you like it, Levi.

      Let me know how it goes!

  • North Star says:

    TS is off-limits to residents in Canada. MC is pricey. Do the parameters work at *StockCharts.com*?

    • Yup! Should work exactly the same.

  • Sorry if I’m misunderstanding, total newbie here. Does this code run all the time by itself and buys and sells for you automatically, or does it just create the chart that you have to monitor and buy or sell when you see the signal?

  • Ed Davison says:

    Thanks! This is amazing. How do I use and input this code?

    • Hi Ed!
      You can use this code in TradeStation or Multicharts.
      I’m also working on porting this over to TradingView.
      Stay tuned!

      • I’ve ported this over to TradingView if you haven’t yet. I’ve also implemented a stop loss. Feel free to email me and I’ll be happy to send it to you.

      • Did you ever get your code ported to Pine Script for TV? Your post/comments don’t have dates, so not sure how old/relevant this is.

      • Hi Kurt. Thanks for this. Did you ever get a TradingView version for this?

  • Kurt are you active on any other websites or platforms?

  • What if s&p closes below 66 sma while in position?

    • The code will stay in the trade until the sell condition is met.
      i.e. the daily close is above the highest close in 19 days.

  • Hello Kurt, For your Simple Swing Trading Strategy for SPY….

    Would you have system performance and statistics for 2022 YTD?

    Also, would you have an excel worksheet available for the system?

    Thank you in advance.

  • In what time span were the 441 trades made? Or is this strictly yearly?

  • Kurt, is 19 an arbitrary number or is there any rationale behind it ?

    • Hi Pearl.
      The number 19 comes from thorough back-testing, walk-forward testing, and real-time testing.

  • What was your starting capital? And how does this compare to buying and holding SPY500 over the same time period?

    • Hi Rob,
      Starting capital is $5,000.
      Buy and hold of SPY from 1993 – present, returned ~900%
      This system returned 5,817% over the same time period.

      • Nice! Thanks for the informative post and answers.


    Could this be used with a leveraged etf like upro?

    • Yes, leveraged funds like SSO and UPRO would work with this strategy. But remember, leverage can cut both ways.

  • Is the 66 average simple or exponential?

    • Also does the system keep buying everyday if the market is trending down since it is continously at 3 day low?

      • Once the system is in a trade it does not do any more buying until the trade has been sold and closed out. Cost averaging down is a losing strategy.

    • This strategy uses the 66 simple moving average.

      • Hi Kurt, this is super helpful. Why use the 66 SMA instead of the more commonly used 50 SMA?

  • Super script. Thanks for the excellent idea. Is there anyway you could write similar script for Tradingview please?

    • Hi Syed. I code in TradeStation. However, porting the code over to TradingView shouldn’t be a hard exercise.

  • What to do with a buy trade and SPY continues to drop? There is never a stop loss?

    • Hi Antonio,
      The S&P 500 (i.e. SPY) is a mean-reverting market and loves to bounce around its average price.
      Counterintuitively, stops in mean-reverting markets actually hurt your results as your account will be chopped to bits each time your stop is hit and the market then rallies.
      Thus if SPY falls it is best to sell into the next rally.
      Here’s an example of adding a stop below the last low (where most traders, unfortunately, put their stops):

  • Angie Smith says:

    How do I use that code? Is it for tos? Thanks for a great system. I just need to know how to put it to use. Thank you!

    • Hi Angie,
      This code is for TradeStation or MultiCharts
      Let me know if you have any other questions.

  • {"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}