If you follow me on Medium, you are probably aware I’m very interested in crypto trading and machine learning. I read that linear regression channels can be very effective in commodity trading. Because Bitcoin and other crypto currencies are not considered as securities, they can be freely traded on traditional asset markets, as well as cryptocurrency exchanges.
So as usual I tried to do some research into what linear regression channels are, how to use them, and how to code them. I struck a blank. I only found some basic explanations on what linear regression channels are at a high level but not enough to actually develop something practically.
What is a Linear Regression Channel?
At a basic level linear regression channels can identify trends and the trend direction. The use of standard deviation gives traders an indication as to when markets are becoming overbought or oversold relative to the long term trend. Typically I would use Moving Average Convergence Divergence (MACD) to identify trends and Relative Strength Index (RSI) to determine if a market is overbought or undersold. For a longer term trend I would normally use the “Golden Cross” and “Death Cross” patterns. If you are unfamiliar with these terms it is when the SMA50 is above or below the SMA200. This is still used heavily in institutions but linear regression channels can offer an alternative or confirmation.
A linear regression channel consists of three components:
- Linear Regression Line — A line that best fits all the data points of interest. If you are familiar with machine learning this is a standard linear regression model with a line of best fit.
- Upper Channel Line — A line that runs parallel to the Linear Regression Line and is usually one to two standard deviations above the Linear Regression Line. In this example I’ve just plotted one standard deviation above but it’s easily adjusted to two if you wish.
- Lower Channel Line — This line runs parallel to the Linear Regression Line and is usually one to two standard deviations below the Linear Regression Line. In this example I’ve just plotted one standard deviation below but it’s easily adjusted to two if you wish.
Interpreting a Linear Regression Channel
One standard deviation from the “Linear Regression Line” means that 68% of all prices are contained within these lines. Two standard deviations means that 95% of all prices are contained between these lines. I’m using one standard deviation.
- Buy Signal — The price drops below the “Lower Channel Line” and a continuation of a trend is expected.
- Sell Signal — The price raises above the “Upper Channel Line” and a continuation of a trend is expected.
If the price spends a significant amount of time outside of the channel it be an early warning that a significant trend reversal may be near.
Python code walkthrough
The first step is to load the necessary libraries and setup your environment.
import datetime
import requests
import timeimport numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as pltfrom sklearn import datasets, linear_model
from sklearn.metrics import mean_squared_error, r2_score%matplotlib inline
You will need some data to work with. I created a function to retrieve market data from the Coinbase Pro exchange and return a Pandas dataframe.
def get_market_data(market, granularity):
resp = requests.get('https://api.pro.coinbase.com/products/' + market + '/candles?granularity=' + str(granularity))
if resp.status_code != 200:
raise Exception(format(resp.json()['message']))
else:
df = pd.DataFrame(resp.json(), columns=[ 'epoch', 'low', 'high', 'open', 'close', 'volume' ])
df = df.iloc[::-1].reset_index()
return df
Retrieving the last 300 days of Bitcoin data from the Coinbase Pro exchange.
df = get_market_data('BTC-GBP', 86400)
Taking a peak at the first 5 rows of our data…
df.head()
Visualising our data with a Seaborn regression plot.
sns.set(font_scale=1.5)
plt.figure(figsize=(12,10))
sns.regplot(x=df.index, y='close', data=df, ci=None, color='r')
Now let’s add our linear regression channel with one standard deviation.
sns.set(font_scale=1.5)
plt.figure(figsize=(12,10))
rp = sns.regplot(x=df.index, y='close', data=df, ci=None, color='r')y_rp = rp.get_lines()[0].get_ydata()
x_rp = rp.get_lines()[0].get_xdata()
sns.lineplot(x=x_rp, y=y_rp + np.std(y_rp), color='b')
sns.lineplot(x=x_rp, y=y_rp - np.std(y_rp), color='b')tsidx = pd.DatetimeIndex(pd.to_datetime(df['epoch'], unit='s'), dtype='datetime64[ns]', freq='D')
rp.set_xticklabels(tsidx, rotation=45)plt.xlabel('')
plt.ylabel('Price')
plt.show()
What is this telling us?
As you can see and you are probably aware Bitcoin and the crypto markets have crashed again. This time it was because Elon said that Tesla will not be accepting Bitcoin as a payment method due to not being environmentally friendly! I mean it’s not the only reason for the crash but this is what set things off. Pretty irresponsible but this is just how things go.
Based on the graph above with the prices closing below the “Lower Channel Line” this could be a buy signal or an early warning of a significant trend reversal. It all really depends how long the prices stay below the line. It’s not looking terrible promising and I think we may be in for a tough few months. My personal opinion is it may get a lot worse before it gets better. The trend will continue down for maybe 6 months or so and then we’ll see the next bull run.
It’s not all bad…
I’ve been trading cryptos for over four years now and been through at least three of four of these crashes already. It seems to be a yearly occurrence after a long bull run. Each time it bounces back even higher. I’m a firm believer that crypto currencies and crypto trading is here to stay. We just need to be patient and weather the storm. There are however some alt coins which are doing really well despite the crash. Cardano (ADA) for example is really solid option and under £1 now. This is definitely one to hold for the future as it has potentially to join one top currencies.
The free open-source crypto trading bot (“PyCryptoBot”) that I developed is still doing well despite the market conditions. I setup a Telegram group chat which is very active with over 300 people chatting about the bot and strategies. You are welcome to join and get involved.
The invite link to the main group chat is:
https://t.me/joinchat/09hYKfelbRY2MDNk
Google Colab
I’ve provided all the code for you already above but if you would like the source code I’ve created a notebook which can be easily run in Google Colab.
- Go to “https://colab.research.google.com”
- Click the GitHub tab
- For “Enter a GitHub URL or search by organisation or user” enter “https://github.com/whittlem/colabnotebooks” and press enter
- Repository: “whittlem/colabnotebooks”, Branch: “main”
- Click on “LinearRegressionChannel.ipynp”
- Click on “Runtime” from the menu, then “Run all”
Good luck and I hope you have found this useful.
- '
- "
- active
- ADA
- All
- asset
- BEST
- Bitcoin
- Bot
- Bull Run
- buy
- Cardano
- Cardano (ADA)
- channels
- code
- coinbase
- Coinbase Pro
- Coins
- commodity
- continue
- Crash
- crypto
- Crypto Markets
- crypto trading
- cryptocurrency
- Cryptocurrency Exchanges
- currencies
- CZ
- data
- develop
- Early
- Effective
- Environment
- exchange
- Exchanges
- Firm
- First
- fit
- follow
- Free
- FS
- function
- future
- GitHub
- Group
- GV
- here
- High
- hold
- How
- How To
- HTTPS
- identify
- index
- institutions
- interest
- involved
- IP
- IT
- join
- learning
- Level
- LG
- Line
- LINK
- load
- Long
- machine learning
- Market
- Markets
- medium
- Metrics
- model
- months
- offer
- open
- Opinion
- Option
- Other
- payment
- People
- press
- price
- Pro
- raises
- research
- Run
- Search
- Securities
- set
- So
- stay
- Storm
- Telegram
- Tesla
- The Source
- time
- top
- Traders
- Trading
- Trends
- us
- volume
- within
- Work
- years