After writing the code for a basic backtest I got the feedback that a stock scanner would be useful to find the signals validated with backtests. And here it is: The instructions how to code a stock scanner.
In the first steps we use only one stock for backtesting or scanning. Because for scanning the whole market you will need all the data for 500 (S&P 500) or 6000-8000 stocks. In my opinion you can do that just with a server running the data loading over night.
But now let’s start with our little scan code:
Getting the stock data
Like for the backtest we need to download or import the stock data as csv-file. I could present you a file on my blog server but that wouldn’t make sense because you want to scan the stock for the current day and for tomorrow, …
Therefore we need a solution to get the daily data for a stock symbol. Again you can use the data of your broker or other free or cheap APIs. For our example I will use a manual method. You will learn automatic methods later for loading many stocks without “doing” anything.
The 4 steps to download historical data online:
- Visit the Yahoo Finance website.
- Click in the search field at the top and type your stock symbol (e.g. GE).
- Click on the tab Historical Data.
- The time period is already set to a year and the frequency to daily data, so you just click the “Download Data”-link to get your csv-file.
If you have problems getting the data (or anything changed with the Yahoo Finance services) write me a comment below and download a sample file here.
Loading data in variable
Like in the last article we use the library pandas
for the financial calculations:
import pandas as pd
data = pd.read_csv("GE.csv")
And during the coding process it’s always interesting to get the first and the last lines for checking the content:
print(data.head())
print(data.tail())
Setting up the strategy
I am sure you’re interested in other indicators than the SMA and you want to code strategies with EMA, stochastics, MACD, ATR and many others. Am I right?
But that’s complex and I have to explain you how to use a function with a DataFrame
(the variable type of the pandas
library). So you have to wait for the next articles.
Our strategy is still with two simple moving averages crossing each other. But we will add the form of the candle.
Please notice: The strategies in the basic articles are not to make money. They are just examples for our code!
Crossing of two moving averages
Here the 20 and the 50 SMA
data['SMA20'] = data.Close.rolling(20).mean()
data['SMA50'] = data.Close.rolling(50).mean()
and the crossing variables for long and short positions:
data['long'] = (data.SMA20 > data.SMA50) & (data.SMA20.shift(1) <= data.SMA50.shift(1))
data['short'] = (data.SMA20 < data.SMA50) & (data.SMA50.shift(1) >= data.SMA50.shift(1))
Now you will get the long-signal, when the 20 SMA is above the 50 SMA and the 20 SMA was below the 50 SMA the day before.
Green body bigger than the last five bodies
To add the condition for a green candle with a body bigger than the body of the last 5 candles (red candle for the short signal) you do not have to set it for the whole dataset. It’s much easier to write it for the last line:
lastrow = data.iloc[-1]
green = lastrow.Close > lastrow.Open
red = lastrow.Open > lastrow.Close
maxBody5 = (df.Close.iloc[-5:] - df.Open.iloc[-5:]).abs().max()
bigbody = abs(lastrow.Close - lastrow.Open) > maxBody5
The lastrow
is checked for a green
body. And then the biggest body of the last 5 candles (maxBody5
) is compared with the current body, resulting in the variable bigbody
.
Scan the stock
To scan the stock (here GE) wether our strategy is showing us an entry signal or not, you can simply type:
long_signal = data['long'].iloc[-1] and green and bigbody
short_signal = data['short'].iloc[-1] and red and bigbody
Output of the result
The last step is to show the result. And you just write:
if long_signal:
print("Today there's a buy signal for GE.")
elif short_signal:
print("Today there's a short signal for GE.")
else:
print("No signals for GE today.")
That’s it. I hope again you learned some coding possibilities with this articles to open the world for all your ideas one step more.
Tell me what you like and what not, what’s missing and where you had problems. I will help you in the comments section to get your program done.
Good results for your scans, huge profits with your strategy development and fun with your coding!