$3000 profit SPY strategy discovered via Python back-testing.

$3000 profit SPY strategy discovered via Python back-testing.

I was making a youtube video about a strategy I heard about on twitter and some other stock market chat rooms. The strategy consisted of buying a stock (SPY) at the end of the day and selling at at opening bell. I decided to write a Python script to back-test this strategy and I found out that the strategy is profitable but has a very low win to loss ratio (1.26).

While I was creating the video to show this I discovered that by buying at the lowest possible point during the day (instead of the end of the day) and then selling at the opening the next day we can increase that profit to loss ratio to over 14.0!

In terms of numbers, that’s $400 vs $3000 in the same time perio d for 100 shares of SPY.

While it’s exciting to discover something like please keep in mind that I am not advising you to act on this. Always speak to a financial expert before purchasing stocks.

The Code

import alpaca_trade_api as tradeapi
import pandas as pd
from datetime import datetime
import time
import sys 
import matplotlib.pyplot as plt
import mykeys


shares = 100

days = 20

api = tradeapi.REST(mykeys.KEY, mykeys.SECRET_KEY, base_url='https://paper-api.alpaca.markets', api_version='v2') 

ticker = sys.argv[1]

barset = api.get_barset(ticker, 'day', limit = days)

timestamp = []
low = []
high = []
close = []
open = []
volume = []


results = []


for bar in barset[ticker]:
    timestamp.append(bar.t)
    low.append(bar.l)
    high.append(bar.h)
    open.append(bar.o)
    close.append(bar.c)
    volume.append(bar.v)


count_wins = 0
count_losses = 0



for now in range(len(timestamp)):
    if now >=1:
        pl_day = (open[now] - low[now-1]) * shares 

        if pl_day > 0:
            count_wins = round(count_wins + pl_day,2)
        else:
            pl_day_pos = pl_day * -1.0  #Multiple by negative one to convert the negative value to a positive value for diplay purposes.
            count_losses = round(count_losses + pl_day_pos,2)

        results.append(pl_day) 
        

results_title = 'Results: Wins:' + str(count_wins) + " Losses:" + str(count_losses) + "  W/L Ratio:" + str(round(count_wins / count_losses,2)) + "  Profit:" + str(round(count_wins - count_losses,2))

#results = close

plt.rcParams.update({
    "lines.color": "white",
    "patch.edgecolor": "white",
    "text.color": "white",
    "axes.facecolor": "black",
    "axes.edgecolor": "lightgray",
    "axes.labelcolor": "white",
    "xtick.color": "white",
    "ytick.color": "white",
    "grid.color": "lightgray",
    "figure.facecolor": "black",
    "figure.edgecolor": "black",
    "savefig.facecolor": "black",
    "savefig.edgecolor": "black"})



fig, axs = plt.subplots(1, 1,figsize=(12,6))

zero = []
for i in range(0,len(results)):
    zero.append(0)

axs.set_title(results_title,color='white')
axs.set_facecolor('#000000')
axs.plot(results)
axs.plot(zero)
#axs.set_xticks([0,len(pl_day)-1], minor=False)
#axs.set_ylabel(ticker + ' TEST RESULTS',fontsize=18,color='white')
axs.tick_params(axis='x', colors='red')
axs.tick_params(axis='y', colors='green')
axs.grid(True,color='#111111')
fig.tight_layout()
#plt.subplots_adjust(bottom=.1,top=.75,wspace=5,hspace=.3)

plt.show()

Leave a Reply