banner



simple moving average trading strategy bitcoin

Finding the Best Moving Average Crossover Strategy for Bitcoin

Ape/rture

The strategy search in this article is meant for educational purposes and is non investment or trading advice. Use of the strategy is at the traders ain risk, since backtest performance is non a guarantee for real-clock trading performance.

Various trading strategies can be used in cryptocurrency trading. One of the popular strategies is the moving average crossover. This strategy is simple to understand and can be a intellectual indication of momentum in a price chart. Since cryptocurrency markets are often momentum driven, this strategy can help traders trade these markets better. Therein article we will excuse a method on how to chance the optimal moving average strategy for a long only strategy and will show the results supported the preceding big stitch from 01–07–2020 to 30–11–2020, where the Bitcoin Price gained around 110%. The strategy will be optimized based on two moving averages on BTC-USDT data from Binance provided by ChainSlayer. The article will feature some Python code, but feel free to skip the encode examples if you are only interested in the principles and the final results.

The Mary Leontyne Pric of an asset often prints random fluctuations in a chart. Past calculating and/or visualizing stirring averages terms trends pot be smoothed. There are several methods for scheming a moving average but the most simple version calculates the median price (often supported the closing price) complete a stop. This period is a parameter oft expressed when mentioning the moving average (MA). The 20 MA takes the last 20 closing prices and averages them, resulting in a new data point. The calculation then moves 1 step up and calculates the next information point. The result is a line that represents this whirling average.

Traders often use sixfold moving averages with different periods. In our strategy we focus on a short period Mummy and a long period MA. Shorter period MAs react quicker to price movements, but are also more prone to deviations in price. Thirster period MAs smooth the price movements many, but can be slow to react. These features can be wont to create a strategy. If a short period MA crosses all over a longer period MA, it means that price is catching momentum and the short period increases outperform the yearner period.

The premise with momentum trading is that erst there is momentum, price wish keep moving until momentum decreases. The crossover to the upside where the short catamenia Artium Magister is above the long catamenia MA is our entry point. Once the short period MA crosses backrest below the long period MA we exit the trade since the momentum turned to the downside. In the picture below the entry and exit are pictured for an example.

The benefits of a moving strategy is that the strategy:

  • can equal listed manually
  • is easy to understand and non too complex
  • can be used to ready alerts based happening the crossover, reduction screen time
  • can well be optimized

We throne optimize this scheme by running backtests. Backtesting is testing a scheme on past data to arrest an approximation of how this scheme would execute on future data. The results are an indication if the strategy could make up viable in real-time trading. For a crossover strategy with two MAs we lavatory compare the results for a range of values for each AM. In our lesson for the unforesightful period Momma we chose the range 'tween 10 and 110 in steps of five (10, 15, 20, …, 95, 100, 105) and for the long period MA we chose the vagabon between 20 and 210 in steps of five (20, 25, 30, …, 195, 200, 205). For all combinations we generated the backtest results with the restraint that the short period MA should have a shorter menses then the extendible full stop MA. From wholly these backtests we picked the two MAs that had the highest returns.

In the paragraphs to a lower place we discuss how this was finished by computer programing the strategy and the optimizer in Python. Skip to The Final Backtest Results paragraph if you are involved in the results.

Optimizing a MA crossover strategy manually is a ho-hum task but optimizing such a strategy is fairly simple if you are acquainted Python and have admittance to quality market data. The code provided uses the backtesting.py library for the strategy optimization. The data is provided by a database from ChainSlayer. The database is a QuestDB which presently runs in an tightly knit cloud workspace and canful be queried like a shot from the Jupyter Notebook in the same workspace. Get access to resign, cutting-edge market information aside connection our community on Discord.

Gathering the Data

The information is retrieved from the like table in the ChainSlayer database. We select the start and end date, which are 2020–07–01 to 2022–11–30, and send the query to the database. The result is processed and put up in a Pandas DataFrame.

          import pandas as pd
import io
signification urllib.parse
import requests
# Arrive data from QuestDB
# Define query q
q = "select timestamp, open, upper, squat, close from {} where timestamp dangt;= '2020-07-01' and timestamp danlt;= '2020-11-30' ".format("qd_candles_spot_btc_usdt_binance_1h")
# Request data from QuestDB with query q
r = requests.get ahead("hypertext transfer protocol://localhost:9000/exp?query=" + urllib.parse.citation(q))
# Convert returned object r to pandas df
df = Pd.read_csv(io.StringIO(r.text))
# Preprocess df:
# Change timestamp newspaper column object types from str to pd.datetime
df["timestamp"] = pd.to_datetime(df["timestamp"])
# Rename Columns
df.rename(columns={"timestamp": "Time", "open": "Open", "squealing": "High", "low": "Low", "close": "Snuggled"}, inplace=True)
# Set tower "Sentence" equally the index
df.set_index('Time', inplace= True)
# view df
df.head()

Kickoff 5 rows of the DataFrame

Defining the Trading Strategy

Before running the actual backtesting we need to define the scheme and Army of the Pure backtesting.py know what train we want to use to enter and exit positions. This is defined by creating a assort for the trading scheme that outlines the trading rules. As crossovers are a common trading system of logic for a number of strategies there is a crosswalk detection function already prebuilt in backtesting.py known as crossover() We have also imported that in the below code. In that strategy we usance a short term Mamma and a long term MA. This strategy is long only and we go long when the short term writhing fair crosses the long term self-propelling average. The 10 and 20 values for the MAs are just placeholders.

          from backtesting import Scheme
from backtesting.lib importation crossover
# Function to return the SMA
def SMA(values, n):
return pd.Series(values).rolling(n).think()
class SmaCross(Strategy):
# Define the two MA lags as *family variables*
ma_short = 10
ma_long = 20
df = df

def init(self):
# Precompute the 2 moving averages
self.sma1 = self.I(SMA, mortal.df.Stopping point.to_numpy(), self.ma_short)
individual.sma2 = someone.I(SMA, soul.df.Close.to_numpy(), self.ma_long)

def next(ego):
# If sma1 crosses to a higher place sma2 buy the asset
if crossover(soul.sma1, self.sma2):
self.buy()

# Else, if sma1 crosses below sma2 sell the plus
elif crossing over(self.sma2, self.sma1):
self.position.stuffy()

Optimizing the Backtest

We dismiss optimize the backtest aside using bt.optimise. The effect is stored in a heatmap variable we can use to check the results. Keep in mind that the starting majuscule is $10000. The top-grade lead has a 15 full stop lookback for the clipped period MA and a 150 lookback for the long period Bay State. This results in a Equity Final in dollars of $19787.42.

          # reminder that we use this Backtest class
bt = Backtest(data=df, strategy=SmaCross, cash=10000, commission=.002)
# evaluate all possible combinations
stats, heatmap = bt.optimize(
ma_short=range(10, 110, 5),
ma_long=ramble(20, 210, 5),
constraint=lambda p: p.ma_short danlt; p.ma_long,
maximize='Equity Final [$]',
return_heatmap=True)
# hold the top 10 returns
heatmap.sort_values(ascending=False).iloc[:10]

Results for the upper side 10 in Fairness Final [$]

Lustiness Check over for the Results

When optimizing strategies the risk of overfitting is present. We want the strategy also to be robust when we run this in the future. The grocery store never Acts exactly like it has done in the past, so we need to account for future random behavior. Luckily thither are methods to establish our backtesting and final exam strategy more robust. 1 of these methods is to add some variations to our parameters and see if the strategy is still profitable.

In our glide slope we already did something similar by evaluation all combination. We can use a heatmap to visualize which combinations are more profitable. If we find clusters of profitable parametric quantity combinations that means these parameters are more robust.

          # group            
hectometre = heatmap.groupby(['ma_short', 'ma_long']).mean().unstack()
#plot heatmap
%matplotlib inline
meaning matplotlib.pyplot as plt
import seaborn as sns
plt.figure(figsize=(12, 10))
sns.heatmap(hm[::-1], cmap='viridis')

Arsenic you can construe with in the heatmap there is a big clustering ranging from 15–40 (ma_short) and from 125–205 (ma_long). It seems that the we can pick the 15 As a the short period MA (ma_short). Since 150 is around the center of the flock I decided to locomote with that setting for the long MA (ma_long).

Let's backtest the results and see how the strategy performed. Overall IT looks like we found the optimal moving average crossover strategy for this Bitcoin actuate! The code under generates the backtest results for our winning strategy. The results are discussed in the next paragraph.

          from backtesting import Strategy
from backtesting.lib meaning crossing over
class SmaCross_15_150(Scheme):
# Define the deuce MA lags as *course variables*
ma_short = 15
ma_long = 150
df = df

def init(self):
# Precompute the deuce moving averages
mortal.sma1 = individual.I(SMA, self.df.Close.to_numpy(), self.ma_short)
self.sma2 = self.I(SMA, self.df.Contiguous.to_numpy(), self.ma_long)

def next(person):
# If sma1 crosses to a higher place sma2 buy in the asset
if crossover(self.sma1, self.sma2):
self.buy()

# Else, if sma1 crosses downstairs sma2 betray the plus
elif crossover(self.sma2, self.sma1):
self.position.close()

# run the backtest
bt = Backtest(data=df, strategy=SmaCross_15_150, cash=10000, commission=.002)
bt.run()
# plot the trades
bt.plot()

We have iterated over several realizable moving average periods in our backtest and have ground that the compounding of the short period MA 15 and for the long period MA 150 gave the best returns. Let's dive into the results.

We started the backtest with $10000. The Equity Last [$] was $19787.42. That is 9787.42 lucre (+97.87%) in 152 days. This strategy is worse then a Buy danamp; Hold approach (+115.92%), only we deliver less exposure to the commercialise (54.41%), which in general agency less risk. The take chances of purchasing and holding is that profit is lost when the trend turns or Bitcoin dumps, spell our scheme would give a betray signal at those moments and we won't be unclothed to the markets since profits are realized by exiting the stance(s).

Example of the last trade with the 15 MA and 150 MA crossing over strategy

Our backtest results demo that with a fairly needled strategy you can be profitable in the cryptocurrency markets. Aside trading a crossover strategy with the 15 riding common and the 150 moving average the +97.87% return in these trending markets is awful. The biggest share of the move force out be caught, while the market pic prison term is reduced. For a real-time trading strategy it is advised to do additional backtesting and backtest along longer periods with more data.

The market information was provided by ChainSlayer. If you wishing to perplex FREE access to high quality historical and cutting-edge cryptocurrency market data, feel free to join our Discord at https://disagree.com/invite/r57denE. The goal of the biotic community in the Disaccord host is to exchange ideas and cooperate on interesting quantitative research and trading mechanization.

ChainSlayer moves fast. Hold bac dormie with the latest developments aside favorable us on Chitter at https://twitter.com/ChainSlayer_

simple moving average trading strategy bitcoin

Source: https://medium.com/chainslayer/finding-the-best-moving-average-crossover-strategy-for-bitcoin-f0a959b846c7

Posted by: hughesthomed.blogspot.com

0 Response to "simple moving average trading strategy bitcoin"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel