What happens if you buy one share of SPY every month?

ByJames Burnett

This code will simulate the purchase of one share of stock every thirty days for as much historical data as the data provider can provide. In the case of the SPY index fund, the data goes back to 1999 and we can see a clear picture for what would have happened if we purchased one share of spy every thirty days.

Even with three major stock market events investors who consistently invested into a major index fund like SPY would be sitting on a pretty pile of cash (provided they liquidate their position).

The major 2000 dot-com crash, the bankers crash of 2008 and 2020 COVID-19 pandemic crash shows that, according to historical data, consistent investing has always lead to a positive outcome. With that said, history won’t necessarily always repeat itself. This experiment was merely a way to get some practice back-testing some of my investing strategies.

For the image above you can see what you would have paid for SPY with the orange line and what SPY would be worth today with the blue-ish (colorblind person here…) line.

Instead of testing in a stock trading platform I simply wrote a Python program to back-test the idea for me, saving me hours of work.

The Code.

To run this code you will need to install the pandas Python module (pip install pandas) as well as the MatPlot graphing module for Python (pip install matplotlib). You’ll also need an API key to down the stock data from Alpha advantage. You can read up on how I download stock data with Python here.

import pandas as pd
import sys
import matplotlib.pyplot as plt
import studies
import mykeys


api_key = mykeys.api_key

ticker = sys.argv[1]  

api_url = 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=' + ticker + '&apikey=' + api_key + '&outputsize=full&datatype=csv'

data = pd.read_csv(api_url)

stock_data = pd.DataFrame(index=range(0,len(data)),columns=['timestamp', 'open','high','low','close','volume'])

stock_data = stock_data.reindex(index=stock_data.index[::-1])

for i in range(0,len(data)):
    #if "2020" in data['timestamp'][i]:
    ts = data['timestamp'][i]
    stock_data['timestamp'][i] = data['timestamp'][i]
    stock_data['close'][i] = float(data['close'][i])
    stock_data['high'][i] = float(data['high'][i])
    stock_data['low'][i] = float(data['low'][i])
    stock_data['open'][i] = float(data['open'][i])
    stock_data['volume'][i] = int(data['volume'][i])

stock_data.index = stock_data.timestamp

stock_data = stock_data.dropna()

timestamp = stock_data['timestamp']

close = stock_data['close']

high = stock_data['high']

low = stock_data['low']

open = stock_data['open']

volume = stock_data['volume']

share_count = 0

stock_price_sum = 0

last_price = close[len(close)-1]

net_values = []

spent_values = []

close_values = []

ts_values = []

counter = 1

total_cost = 0

total_val = 0

for now in range(0,len(close)):
    if counter == 30:
        share_count = share_count + 1

        stock_price_sum = round(stock_price_sum + close[now],2)

        net_value = round(share_count * close[now],2)

        net_values.append(net_value) 

        spent_values.append(stock_price_sum)

        close_values.append(close[now])

        ts_values.append(timestamp[now])

        total_val = net_value

        total_cost = stock_price_sum

        print(timestamp[now],close[now]," - Total Shares:", share_count, " Spent: ", stock_price_sum, " Net Value: ", net_value)

        counter = 1
    else:
        counter = counter + 1


gain = 100 - ((total_cost / total_val) * 100)

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"})

#Define our chart with 2 subcharts and a size of 1200x1200.
fig, axs = plt.subplots(1, 1,figsize=(18,9))




####Sub Graph 1

axs.set_title('Cost/Value: $' + str(total_cost) + '/' + str(total_val) ,color='white')
axs.set_facecolor('#000000')
axs.plot(ts_values,net_values)
axs.plot(ts_values,spent_values)
l = len(close_values)-1
axs.set_xticks([0,l * 0.20,l * 0.40,l * 0.60,l * 0.80, l], minor=False)
#axs[1].set_yticks([0, 30,50, 70, 100], minor=False)
axs.tick_params(axis='x', colors='red')
axs.tick_params(axis='y', colors='green')
axs.grid(True,color='#292b2e')
axs.set_ylabel('NET VALUE v.s. NET SPENT',fontsize=18,color='white')
axs.spines['bottom'].set_visible(False)
axs.spines['top'].set_visible(False)
axs.spines['right'].set_visible(False)
axs.spines['left'].set_visible(False)
#axs.set_xticklabels([])
#axs.set_yticklabels([])

print("Done.")

plt.show()

%d bloggers like this: