Algorithmic Trading with Python.
By: Scott Andersen
Tags: Python, Dashboard, Finance, Algorithmic Trading, Stock Analysis

Beginner level coding with advanced techniques.

TABLE OF CONTENTS:

Pull data from Kraken Api

Format DataFrame

Calculate Daily Returns

Generate Exponential Moving Averages (short / long window)

Plot Closing Prices of Bitcoin with EMA

Calculate daily volatility

Construct Bollinger Bands

Introduction:

To begin, let’s first understand the purpose of this article, which is to provide the average retail investor with a quick and easy way to import data, use that data to highlight key indicators and plot an informative graph for us to evaluate our positions.

In this article we will cover a three fundamental trading signals using various technical indicators.

# Import libraries and dependencies

import pandas as pd

import numpy as np

from pathlib import Path

%matplotlib inline import warnings

warnings.filterwarnings('ignore') # Set path to CSV and read in CSV

csv_path = Path('../Medium/kraken_btc_1hr.csv')

btc_df=pd.read_csv(csv_path)

btc_df.head()

The data we will be using for this example is from Kraken, you will have to create an account and get an API Key if you would like to use their live data. However, you can find the exact data used in this article by going to my GitHub and downloading the csv.file.

# Set index as datetime object and drop columns btc_df.set_index(pd.to_datetime(btc_df['Timestamp'], infer_datetime_format=True), inplace=True) btc_df.drop(columns=['Timestamp'], inplace=True)

btc_df.head()

After we have our dataset cleaned with the columns we want, its important to drop ‘NaN’ values in this case and calculate the daily percentage return.

We are also going to add a new column to our DataFrame called ‘daily return’.

# Drop NAs and calculate daily percent return btc_df['daily_return'] = btc_df['Close'].dropna().pct_change()

btc_df

Trading Signal #1: Exponential Moving Average

In contrast to a simple moving average (SMA), an exponential moving average (EMA) of closing prices represents a moving average with more weight or focus given to the most recent of prices.

# Set short and long windows

short_window = 1

long_window = 10 # Construct a `Fast` and `Slow` Exponential Moving Average from short and long windows, respectively

btc_df['fast_close'] = btc_df['Close'].ewm(halflife=short_window).mean()

btc_df['slow_close'] = btc_df['Close'].ewm(halflife=long_window).mean() # Construct a crossover trading signal

btc_df['crossover_long'] = np.where(btc_df['fast_close'] > btc_df['slow_close'], 1.0, 0.0)

btc_df['crossover_short'] = np.where(btc_df['fast_close'] < btc_df['slow_close'], -1.0, 0.0)

btc_df['crossover_signal'] = btc_df['crossover_long'] + btc_df['crossover_short'] btc_df.head()

Plotting the EMA of Bitcoin ‘Close Prices’

Trading Signal #2: EMA of Daily Return Volatility

# Set short and long volatility windows

short_vol_window = 1

long_vol_window = 10 # Construct a `Fast` and `Slow` Exponential Moving Average from short and long windows, respectively

btc_df['fast_vol'] = btc_df['daily_return'].ewm(halflife=short_vol_window).std()

btc_df['slow_vol'] = btc_df['daily_return'].ewm(halflife=long_vol_window).std() # Construct a crossover trading signal

btc_df['vol_trend_long'] = np.where(btc_df['fast_vol'] < btc_df['slow_vol'], 1.0, 0.0)

btc_df['vol_trend_short'] = np.where(btc_df['fast_vol'] > btc_df['slow_vol'], -1.0, 0.0)

btc_df['vol_trend_signal'] = btc_df['vol_trend_long'] + btc_df['vol_trend_short']

PLOT:

When a short-window (fast) EMA of daily return volatility is greater than a long-window (slow) EMA of daily return volatility, the crossover suggests that a short opportunity exists where daily return volatility is expected to rise.

Trading Signal #3: Bollinger Bands

Bollinger Bands describe a middle, upper, and lower band, in which the middle is a simple moving average (SMA) of closing prices, while the upper and lower bands describe the rolling standard deviation above and below the SMA, respectively.

# Set bollinger band window

bollinger_window = 20 # Calculate rolling mean and standard deviation

btc_df['bollinger_mid_band'] = btc_df['Close'].rolling(window=bollinger_window).mean()

btc_df['bollinger_std'] = btc_df['Close'].rolling(window=20).std() # Calculate upper and lowers bands of bollinger band

btc_df['bollinger_upper_band'] = btc_df['bollinger_mid_band'] + (btc_df['bollinger_std'] * 1)

btc_df['bollinger_lower_band'] = btc_df['bollinger_mid_band'] - (btc_df['bollinger_std'] * 1) # Calculate bollinger band trading signal

btc_df['bollinger_long'] = np.where(btc_df['Close'] < btc_df['bollinger_lower_band'], 1.0, 0.0)

btc_df['bollinger_short'] = np.where(btc_df['Close'] > btc_df['bollinger_upper_band'], -1.0, 0.0)

btc_df['bollinger_signal'] = btc_df['bollinger_long'] + btc_df['bollinger_short']

PLOT Bollinger Bands:

# Plot the Bollinger Bands for BTC/USD closing prices btc_df[['Close','bollinger_mid_band','bollinger_upper_band','bollinger_lower_band']].plot(figsize=(20,10))

When the price moves toward either the upper band or lower band, it bounces back toward its average.This is because those upper and lower bands represent a certain standard deviation away. Therefore, the price is more likely to go back to its average than remain at an improbable range away from the mean.

Therefore, when the Bitcoin closing price is less than the lower band, a long opportunity exists: the signal suggests that the price action will tend to move upward and more in line with where the price should be within the negative standard deviation.

A short opportunity exists for the opposite scenario, in which the asset closing price is greater than the upper band, suggesting that the price action will tend to move downward and within the positive standard deviation.

Thank you for reading!

If you found this article useful, feel welcome to download my personal codes on GitHub. You can also email me directly at scottandersen23@gmail.com and find me on LinkedIn. Interested in learning more about data analytics, data science and machine learning applications? Follow me on Medium.

Gain Access to Expert View — Subscribe to DDI Intel