How to Maximize Your Profit in Cryptocurrency Using Python?

Technical analysis of a cryptocurrency

Photo by Austin Distel on Unsplash

The year 2020 might have been the worst year for us however it was a golden year for cryptocurrency. 2020 has been the year of Bitcoin.2021 would be the start of the decade of Altcoins. The year saw ETH give 4.5x returns, Bitcoin testing its ATH and breaking it.2020 was the year when Bitcoin went mainstream with institutional investors dipping their hands in the crypto gold.

But what lies ahead? Will the crypto bubble burst just like the internet bubble of the ’90s or will it attain new heights?

2021 reminds us to look beyond Bitcoin. Dodge coin and Ethereum leading the band.

Well-known investors have differing opinions if Bitcoin is an investment, or not. Warren Buffett said

Cryptocurrencies basically have no value and they don’t produce anything. They don’t reproduce, they can’t mail you a check, they can’t do anything, and what you hope is that somebody else comes along and pays you more money for them later on, but then that person’s got the problem. In terms of value: zero.

Some in the public dismiss Bitcoin as a currency for pirates and criminals. Some are increasingly worried about its energy consumption, which is higher than all of Argentina’s electricity consumption. Many still do not understand what it is and how its underlying technology, the blockchain works. And some have bought cryptocurrency just through the sheer fear of missing out!

Whatever your stance is on the matter, Bitcoin has certainly produced no shortage of opinions. What does matter now is that we can improve our data science skills by learning some technical analysis?

Basic statistics

Let’s dive deeper into ETH

We visualize the data in the table above with a box plot. A box plot shows the quartiles of the dataset with points that are determined to be outliers using a method of the inter-quartile range (IQR). In other words, the IQR is the first quartile (25%) subtracted from the third quartile (75%).

On the box plot below, we see that the ETH closing hourly price was most of the time between $500 and $1700 in the last 3 months.

import seaborn as sns
ax = sns.boxplot(data=hist['close'], orient="h")
import datetime
import json
import numpy as np
from fbprophet import Prophet
from neuralprophet import NeuralProphet
import pandas as pd
import requests
import matplotlib.pyplot as plt
from fbprophet.plot import plot_cross_validation_metric
import math
from sklearn.model_selection import train_test_split
endpoint = ‘https://min-api.cryptocompare.com/data/histoday'
res = requests.get(endpoint + ‘?fsym=ETH&tsym=USD&limit=180’)
hist = pd.DataFrame(json.loads(res.content)[‘Data’])
hist = hist.set_index(‘time’)
hist.index = pd.to_datetime(hist.index, unit=’s’)
target_col = ‘close’
hist.describe()

Histogram of ETH closing price

Let’s estimate the frequency distribution of ETH closing prices. The histogram shows the number of hours ETH had a certain value.

Observations

  • ETH closing price was not over $2000 for many hours.
  • it has right-skewed distribution because a natural limit prevents outcomes on one side.
  • The blue dashed line (median) shows that half of the time closing prices were under $1200.
hist[‘close’].plot(grid=True, figsize=(15, 10))
df_return = hist[‘close’]/hist[‘close’].shift(90)-1
df_return=df_return.dropna()
df_return.plot(grid=True, figsize=(15, 10)).axhline(y = 1, color = "black", lw = 2)Trading strategy

Trading Strategy

A trading strategy is a set of objective rules defining the conditions that must be met for trade entry and exit to occur.

We are going to apply the Moving Average Convergence Divergence (MACD) trading strategy, which is a popular indicator used in technical analysis. MACD calculates two moving averages of varying lengths to identify trend direction and duration. Then, it makes the difference in values between those two moving averages (MACD line) and an exponential moving average (signal line) of those moving averages.

We will start by understanding the Moving Average Convergence Divergence (MACD) indicator. The MACD indicator is one of the most popular technical oscillator indicators.

MACD helps us understand the relationship between the moving averages. Convergent is when the lines move closer to each other and divergence is when the lines move away from each other. The lines here are the moving averages.

MACD is a trend-following momentum indicator. It can help us assess the relationship between two moving averages of prices. Subsequently, the MACD indicator can be used to compute a trading strategy that signals us when to buy or sell a stock. I will demonstrate it in this article.

Before I begin, it’s worth mentioning that a moving average is a rolling average value of a predefined historic period. For instance, the simple 10-day moving average is computed by calculating the past 10 days period. The exponential moving average, on the other hand, assigns higher importance to the recent values. It can help us capture the movements of a stock price better.

There are 3 main steps required to compute MACD:

Step 1: Calculate the MACD line:

  1. Calculate the 26-day exponentially weighted moving average of the price. This is the long-term line.
  2. Calculate the 12-day exponentially weighted moving average of the price. This is the short-term line.
  3. Calculate the difference between the 26-day EMA and 12-day EMA lines. This is the MACD line.

Step 2: Calculate the Signal line from the MACD line:

  1. Calculate the 9 days exponentially weighted moving average of the MACD line. This is known as the signal line.

Step 3: Compute the histogram: Distance between MACD and the Signal

  1. We can then calculate the difference between the MACD and the Signal line and then plot it as a histogram. The histogram can help us find when the cross-over is about to happen.

The histogram is the difference between MACD and the Signal line

Including MACD Oscillator In Trading Strategy

MACD oscillator offers a visual representation of when the trend is changing. MACD signal line crossover is the most common indication used by traders to identify a bullish or bearish trend. The signal line trails MACD and makes it easier to spot a turn. A bullish crossover happens when the MACD line crosses the signal line from below. Similarly, chartists record a bearish crossover when the MACD line crosses below the signal line. When it happens, a crossover lasts for few days to few weeks.

It is important to learn to use MACD trend identifying oscillator in your trading strategy. Here is why,

– It is a simple trading indicator that can offer accurate trading signals

– Sometimes MACD offer trend reversal signals in advance

– The 9-day EMA further smooths out the noise

– MACD offers additional signal regarding trend strength

– It offers updated signals compared to the moving average

However, while using MACD in your trading strategy, the caveat remains the same as for other charting tools.

One main problem with the MACD oscillator is that it shows too many crossovers, which adds to the confusion. The MACD line can cross the signal line even without an actual reversal happening — causing a situation called false positive. On the other hand, it also lacks in forecasting all reversals. To say it, the MACD oscillator indicates too many reversals that don’t occur and not enough reversals that happen.

The crossover happens even when there is only sideways movement in stock price. But the MACD chart will show a false positive. Traders need to wait out to see if the crossover is an actual change in trend or a false reversal. In case of a false reversal, the MACD line will eventually fall back to the zero lines.

Therefore, traders study the MACD oscillator along with other charting tools to confirm a reversal. Another pitfall is signal line crossovers at positive or negative extremes. It takes significant movement in underlying stock volume to push momentum to an extreme. Chartists use historical data to confirm the validity of such extremities.

Strategy

We can use the cross-over between MACD and the Signal line to create a simple trading strategy. This is where the MACD line and the signal line cross over each other.

  • Sell Signal: The cross-over: When the MACD line is below the signal line.
  • Buy Signal: The cross over: When the MACD line is above the signal line

Bullish vs Bearish:

  • Bearish: When the MACD and Signal lines are below 0 then the market is bearish.
  • Bullish: When the MACD and Signal lines are above 0 then the market is bullish.

Key Points:

MACD is based on moving averages which imply that the past can impact the future. This is not always true. Additionally, there is a lag present due to the moving averages hence the generated signals are after the move has started.

The standard setting for MACD is the difference between the 12- and 26-period EMAs. We could use MACD(5,35,5) for more sensitive data and MACD(12,26,9) might be better suited for weekly charts. It all depends on the investor.

One keynote to remember is to always analyze the short and long-term price trend along with other factors. And remember sometimes a stock that might appear overbought might still move upwards due to other market factors.

As we can see in the example below:

  • exit trade (sell) when the MACD line crosses below the MACD signal line,
  • enter the trade (buy) when the MACD line crosses above the MACD signal line.

Calculate the trading strategy

exp1 = hist[‘close’].ewm(span=12, adjust=False).mean()
exp2 = hist[‘close’].ewm(span=26, adjust=False).mean()
macd = exp1-exp2
exp3 = macd.ewm(span=9, adjust=False).mean()
plt.plot(hist.index, macd, label=’ETH MACD’, color = ‘green’)
plt.plot(hist.index, exp3, label=’Signal Line’, color=’red’)
plt.legend(loc=’upper left’)
plt.show()

Check the graph below. Were you correct? Remember, a bullish crossover happens when the MACD crosses above the signal line and a bearish crossover happens when the MACD crosses below the signal line.

Next, let’s study the strength and examine overbought or oversold conditions.

We start by implementing the exponential moving averages and MACD.

exp1 = hist[‘close’].ewm(span=12, adjust=False).mean()
exp2 = hist[‘close’].ewm(span=26, adjust=False).mean()
exp3 = hist[‘close’].ewm(span=9, adjust=False).mean()
macd = exp1-exp2
plt.plot(hist.index, hist[‘close’], label=’ETH’)
plt.plot(hist.index, macd, label=’ETH MACD’, color=’orange’)
#plt.plot(hist.index, exp3, label=’Signal Line’, color=’Magenta’)
plt.legend(loc=’upper left’)
plt.show()

Let’s recall our discussion of overbought and oversold from earlier. We can see the MACD stays pretty flat over time. But there are certain times where the MACD curve is steeper than others. These are instances of overbought or oversold conditions. We represent our oversold conditions with green circles and overbought with red circles. You can see that soon after the MACD shows an overbought or oversold condition the momentum slowed and the stock price reacted accordingly.

That’s It

We briefly discussed MACD and implemented it in Python to examine its use in crossovers and overbought/oversold conditions. Hopefully, this article helped you add another tool to your trading toolbox!

Full code here

Found this article useful? Follow me (Rahula Raj) on Medium! Please 👏 this article to share!

I will tell you the secret to getting rich on Wall Street. You try to be greedy when others are fearful. And you try to be fearful when others are greedy. — Warren Buffett

_________________________________*****_____________________________

Open to freelance opportunities
Contact me at rahular2020@iimbg.ac.in

_________________________________*****_____________________________


How to Maximize Your Profit in Cryptocurrency Using Python? was originally published in DataDrivenInvestor on Medium, where people are continuing the conversation by highlighting and responding to this story.