create account

Attempting to improve on the MACD strategy in python by chasmic-cosm

View this thread on: hive.blogpeakd.comecency.com
· @chasmic-cosm ·
$1.47
Attempting to improve on the MACD strategy in python
In my [previous post](https://leofinance.io/hive-167922/@chasmic-cosm/automated-trading-with-the-macd-in-python) I introduced a rudimentary trading strategy based on the [MACD](https://leofinance.io/hive-167922/@chasmic-cosm/calculating-the-macd-in-python). This strategy produced lots of spurious trading signals and would probably not be particularly effective in the wild. In this post I'll explore some attempts to improve the quality of signal produced by the MACD strategy.

# Baseline results

In order to evaluate the performance of each approach, we need to have a reference. The naïve MACD strategy produces lots of bad trade signals over the test data.

![macd reference1.png](https://images.hive.blog/DQmUKPq2bNviTCYYSVK1KTc2CxV3qkzhpLwRX1nDFzhNfsS/macd%20reference1.png)

# Approach 1: Positivity of the MACD

We can try to filter out bad trade signals by insisting that the MACD be positive in order to trigger a trade.

```python
import numpy as np

def macd_strategy2(ohlcv):
    """
    Calculate the macd of a stock, decide whether to buy, sell, or hold based on signal behaviour
    Inputs:
        ohlcv:  numpy array -   A 5 x N matrix with rows corresponding to
                                o, h, l, c, v respectively
    Outputs:
        status: string      -   "BUY", "SELL", or "HOLD"
    """
    typical = typical_price(ohlcv)
    macd, macd_sig, macd_hist = macd(typical)
    macd_hist = macd_hist[::-1] # reversed MACD histogram
    macd = macd[::-1]

    if macd_hist[0] > 0 and macd_hist[1] <= 0 and macd[0] >= 0:
        return "BUY"
    elif macd_hist[0] < 0 and macd_hist[1] >= 0:
        return "SELL"
    else:
        return "HOLD"
```

This seems to filter out quite a few of the bad buy signals, however this strategy isn't applicable for sell signals.

![approach 1.png](https://images.hive.blog/DQmZ7rtr2eJLPqK3Q4GijyLtp14nMRvyvpc73jAk66s5ESo/approach%201.png)

# Approach 2: Positivity of the derivative

Another potential way to filter out signals from the MACD is to look at the sign of the first derivative. In order to calculate the first derivative, we can use a rudimentary method such as a finite difference scheme: 

```python
import numpy as np

def first_deriv(signal, dt):
    """
    Calculate the first derivative using finite difference method
    Inputs:
        signal: numpy array -   A sequence of price points in time
        dt:     int         -   Bucket size in seconds
    Outputs:
        dx:     numpy array -   First derivative at each point in points
    """
    dx = np.zeros(len(signal))
    dx[0] = (signal[1] - signal[0]) / dt
    dx[-1] = (signal[-1] - signal[-2])
    for i in range(1, len(dx) - 1):
        dx[i] = (signal[i + 1] - signal[i - 1]) / (2 * dt)
    return dx
```

Then integrating this into the MACD strategy:

```python
def macd_strategy3(ohlcv):
    """
    Calculate the macd of a stock, decide whether to buy, sell, or
    hold based on signal behaviour
    Inputs:
        ohlcv:  numpy array -   A 5 x N matrix with rows corresponding to
                                o, h, l, c, v respectively
    Outputs:
        status: string      -   "BUY", "SELL", or "HOLD"
    """
    typical = ta.typical_price(ohlcv)
    macd, macd_sig, macd_hist = ta.macd(typical)
    dx = ta.first_deriv(typical, 1)[::-1]
    macd_hist = macd_hist[::-1] # reversed MACD histogram
    if macd_hist[0] > 0 and macd_hist[1] <= 0 and dx[0] > 0:
        return "BUY"
    elif macd_hist[0] < 0 and macd_hist[1] >= 0 and dx[0] < 0:
        return "SELL"
    else:
        return "HOLD"
```

![approach 2.png](https://images.hive.blog/DQmRGtjx5wBztBNJq1fnx6NyHNo2sYmFgubzERM1bBCSCqc/approach%202.png)

I had high hopes for this approach, but it didn't seem to have much effect at all.

# Results

Neither of these approaches do a particularly good job of cleaning up the signals generated by the original [MACD strategy](https://leofinance.io/hive-167922/@chasmic-cosm/automated-trading-with-the-macd-in-python). Usually the MACD is used in conjunction with other indicators in order to provide more reliable trading signals.

Posted Using [LeoFinance](https://leofinance.io/@chasmic-cosm/attempting-to-improve-on-the-macd-strategy-in-python)
👍  , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , and 312 others
properties (23)
authorchasmic-cosm
permlinkattempting-to-improve-on-the-macd-strategy-in-python
categoryhive-167922
json_metadata{"tags":["investing","trading","finance","maths","programming","python","leofinance"],"image":["https://images.hive.blog/DQmUKPq2bNviTCYYSVK1KTc2CxV3qkzhpLwRX1nDFzhNfsS/macd%20reference1.png","https://images.hive.blog/DQmZ7rtr2eJLPqK3Q4GijyLtp14nMRvyvpc73jAk66s5ESo/approach%201.png","https://images.hive.blog/DQmRGtjx5wBztBNJq1fnx6NyHNo2sYmFgubzERM1bBCSCqc/approach%202.png"],"links":["https://leofinance.io/hive-167922/@chasmic-cosm/automated-trading-with-the-macd-in-python","https://leofinance.io/hive-167922/@chasmic-cosm/calculating-the-macd-in-python"],"app":"leofinance/0.1","format":"markdown","canonical_url":"https://leofinance.io/@chasmic-cosm/attempting-to-improve-on-the-macd-strategy-in-python"}
created2020-08-10 19:11:12
last_update2020-08-10 19:11:12
depth0
children1
last_payout2020-08-17 19:11:12
cashout_time1969-12-31 23:59:59
total_payout_value0.748 HBD
curator_payout_value0.718 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length4,213
author_reputation4,159,775,155,640
root_title"Attempting to improve on the MACD strategy in python"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id99,000,637
net_rshares4,283,006,182,173
author_curate_reward""
vote details (376)
@upvotebank ·
<center>UpvoteBank</center> | <center>Your upvote bank</center>
------------ | -------------
![__2.jpg](https://steemitimages.com/DQmfDxvv4NLs3knYT7B2mHgE5ArnkheNmDSLydKKTfBwokj/__2.jpg) | This post have been upvoted by the @UpvoteBank service. Want to know more and receive "free" upvotes click [here](https://steemit.com/steemit/@upvotebank/gzsr5aw6)
👎  
properties (23)
authorupvotebank
permlink20200810t191136430z
categoryhive-167922
json_metadata{"tags":["comment"],"app":"steemjs/comment"}
created2020-08-10 19:11:36
last_update2020-08-10 19:11:36
depth1
children0
last_payout2020-08-17 19:11:36
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length354
author_reputation44,533,286,469,385
root_title"Attempting to improve on the MACD strategy in python"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id99,000,644
net_rshares-5,347,465,312
author_curate_reward""
vote details (1)