Technical Analysis Using Python - Detecting EMA Crosses - Steemit
Technical Analysis Using Python - Detecting EMA Crosses - Steemit
html) Sign up
(/) (https://signup.steemit.com) (/search) (/submit.html)
My Profile On GitHub
You can nd code used in this tutorial as well as other tools and examples
in the GitHub repositories under my pro le:
https://github.com/imwatsi
Requirements
Python 3.6+
Dependencies:
/
requests
bfxhfindicators
An active internet connection
Di iculty
Intermediate
Definitions of Terms
Here are a few de nitions of technical terms used in this tutorial:
/
Tutorial Content
In this tutorial, we will use the bfxfhindicators technical analysis library
to calculate EMA values for two periods (10 and 20) and then use a
historical window of 10 periods to detect markets in which an EMA cross
has occured. 10-period EMA will be the primary dataset and 20-period
EMA will be the secondary dataset.
To get market data, we will use the HitBTC exchange API and extract 15
minute candle data for 20 USD symbols (BTCUSD, ETHUSD, etc...). Let's
begin!
Install dependencies
Before we start writing code, let's make sure we have the necessary
modules installed. Only two external dependencies need to be installed,
the rest are already included as part of the standard Python library.
Install requests
On Linux, run the following command:
Install bfxhfindicators
For technical analysis, We will use bfxhfindicators , an open source
module developed by Bit nex. You can download the module from
Bit nex's GitHub Repository .
1. Extract the contents, "cd" into the directory on a terminal and run
python3 setup.py install --user on Linux or just python setup.py
install --user if on Windows or MacOS.
/
2. Extract the contents and copy the folder "bfxh ndicators" folder to
your project's working directory.
import requests
import json
import time
from bfxhfindicators import EMA
from threading import Thread
BASE_URL = 'https://api.hitbtc.com'
historic_window = 10
symbols = []
candles = {}
ema_values = {}
ema_periods = [10,20]
go_on = False
/
historic_window : the number of historic EMA values to include when
detecting EMA crosses
symbols and candles store the market data (market symbols and 15m
candles, respectively)
go_on boolean is used to create a delay till all candle data for all
symbols is loaded
/
def import_candles(symbol):
global candles
# get candles
resp = requests.get(BASE_URL + '/api/2/public/candles/%s?period=M
%(symbol))
raw_candles = json.loads(resp.content)
# parse candles and save to memory
parsed_candles = []
for raw_c in raw_candles:
new_candle = {
'timestamp': raw_c['timestamp'],
'close': float(raw_c['close']),
'low': float(raw_c['min']),
'high': float(raw_c['max'])
}
parsed_candles.append(new_candle)
candles[symbol] = parsed_candles[:]
/
def show_progress():
global go_on
#wait for symbols to load
while True:
time.sleep(0.2)
print('Importing candles: %s/%s symbols loaded'
%(len(candles), len(symbols)), end='\r')
if len(candles) == len(symbols): # break when equal
break
go_on = True
Initial code
Next we write code that will execute rst when the script is run. The rst
thing we need to do is get the 20 symbols from the exchange.
/
Once we have the list of symbols, we can begin importing candle data for
all of them. The code for this should create a new thread for each symbol,
to make the process synchronous.
To stop the script from executing the next sections until all candle data has
been loaded, we put a loop that waits for the boolean go_on to be True.
/
# calculate EMA values
print('Calculating EMA values and scanning for crosses...', end='', f
for sym in symbols:
for period in ema_periods:
iEMA = EMA([period]) # define EMA object
for candle in candles[sym]:
iEMA.add(candle['close']) # add all close prices
lst_ema = []
lst_ema.append(iEMA.v()) # add current EMA value
for i in range(historic_window):
# add historic EMA values
lst_ema.append(iEMA.prev(i+1))
if sym not in ema_values: # add symbol key to dictionary
ema_values[sym] = {}
ema_values[sym][period] = lst_ema # save EMA values
All EMA values are saved in the ema_values variable, with symbol and EMA
period as keys for the dictionary.
For each market symbol, check to see what kind of cross we are
looking for. By taking the oldest EMA values for both EMA periods and
comparing them, we can determine whether we are looking for
moments when the primary EMA crosses downwards to go below the
secondary EMA, or vice versa.
When the primary EMA is initially above the secondary, we are looking
for a cross when the primary eventually reverses the situation and goes
below the secondary, and vice versa for the other scenario.
Scan all historic EMA values and lter out the symbols that meet the
criteria for an EMA cross.
/
Save the symbols in memory, according to the type of EMA cross
detected.
/
# identify EMA crosses
ema_results = {
'cross-downs': [],
'cross-ups': []
}
for sym in symbols:
# get primary and secondary EMA lists, and reverse for oldest fir
ema_first = ema_values[sym][ema_periods[0]][:]
ema_second = ema_values[sym][ema_periods[1]][:]
ema_first.reverse()
ema_second.reverse()
/
del tmp
print('done')
# print results
print('Primary EMA Period: %s' %(ema_periods[0]))
print('Secondary EMA Period: %s\n' %(ema_periods[1]))
print('EMA(%s) cross below EMA(%s):\n' %(ema_periods[0], ema_periods[
for x_down in ema_results['cross-downs']:
print(x_down)
print('\nEMA(%s) cross above EMA(%s):\n' %(ema_periods[0], ema_period
for x_up in ema_results['cross-ups']:
print(x_up)
And that's it! When you run the script, it should produce output similar to
the one shown below. Di erent market conditions will produce di erent
results.
/
Find the complete Python script on GitHub: ta_ema_cross.py
crosses)
Start Trading
(https://poloniex.com/)
Sort: Trending
/
portugalcoin (72) (/@portugalcoin) last year (/utopian-io/@portugalcoin/re-imwatsi-technical- [-]
analysis-using-python-detecting-ema-crosses-20190510t210817354z#@portugalcoin/re-imwatsi-technical-
analysis-using-python-detecting-ema-crosses-20190510t210817354z)
Thank you for your contribution @imwatsi (/@imwatsi)
A er reviewing your contribution, we suggest you following points:
Excellent tutorial, but we were waiting to see more features in your tutorial. In the next we thank you for
developing more features.
The final GIF with running the script looks great to show the results.
Your contribution has been evaluated according to Utopian policies and guidelines , as well as a predefined set
of questions pertaining to the category.
To view those questions and the relevant answers related to your post, click here .
[utopian-moderator]
$6.23 26 votes Reply
Hi @imwatsi (/@imwatsi)!
Your post was upvoted by @steem-ua (/@steem-ua), new Steem dApp, using UserAuthority for algorithmic post
curation!
Your post is eligible for our upvote, thanks to our collaboration with @utopian-io (/@utopian-io)!
Feel free to join our @steem-ua Discord server
/
$0.00 Reply
$0.00 Reply