In this article I want to show you how you can write the code for an indicator using functions.
In our last two coding articles about backtesting and scanning we used the Python library pandas
for financial data. And in Python you can use your own functions instead of the ones in the libraries.
Here an easy example:
def calculateTarget(entry, stop, multiple):
return entry + (entry - stop) * multiple
EP = 46.3
SL = 44.96
# target should be at 2R
TP = calculateTarget(EP, SL, 2)
print("EP: {:5.2f}\nSL: {:5.2f}\nTP: {:5.2f}".format(EP, SL, TP))
Now we can use a function to integrate the SMA for making the usage in our code much easier:
def sma(data_series, period):
return data_series.rolling(period).mean()
A Series
is a column (like Close, Low, Volume) in a pandas
DataFrame
(used as object for our whole candlestick package) and with the above code we just can use sma(data.Close, 200)
to get the 200 SMA which is based on the close of each candle but we can also write sma(data.Volume, 30)
to get the average volume of the last 30 days.
With the knowledge about functions we can also create an indicator for the exponential moving average (EMA):
def ema(data_series, period):
return data_series.ewm(span=period).mean()
Easy, right? Yes. It’s a function of the library pandas
and we can use it so easily. Now you can write ema(data.Close, 20)
to get the 20 EMA.
But for all the following calculations or usage of our DataFrame
we have to pay attention on the first rows according to the number of the biggest moving average. If it’s the 200 SMA or 200 EMA the first 200 rows will contain a “nan
” or “NaN
“.
That’s a placeholder because for the first 200 rows the functions cannot compute the SMA or EMA.
Of course, there is a solution for this problem:
If our DataFrame
is called data
we simply add data = data.iloc[200:]
and the first 200 rows will not be included in your variable.
For your overview I wrote the following little code (warning: not for real trading, just as an example!!). You can see how you combine the implementation of the libraries, the functions and your main code:
# import of libraries
import pandas as pd
# functions
def sma(data_series, period):
return data_series.rolling(period).mean()
def ema(data_series, period):
return data_series.ewm(span=period).mean()
# variables
filename = "SPY.csv"
# preparing the data
data = pd.read_csv(filename)
data['SMA200'] = sma(data.Close, 200)
data['EMA20'] = ema(data.Close, 20)
data['EMA50'] = ema(data.Close, 50)
data['AvgVol'] = sma(data.Volume, 60)
# little strategy
data['trend'] = (data.EMA20 > data.EMA50) & (data.EMA50 > data.SMA200)
data['minVol'] = data.AvgVol > 200000
data['green'] = data.Close > data.Open
# checking the last date in our data (mostly the current date)
current = data.iloc[-1]
if current.trend and current.minVol and current.green:
print("Yes, you should get in.")
else:
print("Nothing to do. Enjoy your day!")
If you not just read the article but wrote the code and tried around with it you reached the next step in programming financial data. I am happy to teach you all the elements and you can subscribe the RSS-feed or the newsletter to get informed about new articles and other news about market-and-us.com!
Please, write me about your experiences and questions in the comments below and I will answer every question. Thanks for being in my community!
2 Comments
Alessandro
(9. November 2019 - 14:28)dear Alexander, many thanks for your work and your precious help!
I’m looking for a solution on how to place orders on interactive brokers using a python application, how to retrieve candlestick data automatically from IB, how to cancel those orders, how to modify them, and all this by using the official IB API, and not IBPY.
this would be very interesting and useful, as I’m struggling on finding clear explanation online.
thank you again and looking forward for your next articles)))))
Alexander
(10. November 2019 - 01:08)It’s my pleasure.
I like writing about my knowledge and it’s also a reflection for myself.
Wonderful that you are naming exact wishes for new articles. With your impulse in mind I published a new article this moment about how to get historical stock data. So, the first wish is fulfilled. 🙂
And I am confident that there will be articles about order setting and controlling your current trades.
Thanks for reading the articles!