Tuesday, October 18, 2022

Backtesting My planned MACD Trading Strategy

As promised, I will post here the python code I used to back test my trading strategy using MACD indicator.

After I run the code and visualize it resulted in the following figure:

As can be seen from the graph, Using historical data from Jan 1, 2022 up to Oct 19, 2022, my python code program generated 2 signals and to compute the income earned:

Buy Signal:

   Entry: Feb 23, 2022  - $254.68

   Exit: March 3, 2022 - $279.63

   Profit: $279.63 - 254.68 = $25.03

Sell Signal:

  Entry: March 3, 2022 - $279.63

  Current Price: (Oct 19, 2022) : $220.19

  Profit:  $279.63 - $220.19 = $59.44

Total Profit:  $25.03 + $59.44 = $84.47

The initial code I implemented yield some profit($84.47/$220.19) * 100 = 38.36%). The reason why it was not able to capture the golden opportunities during the period is historical data never met the stop conditions I implemented. It will still need some revision to optimize the profit. But on the contrary, 38.36% is huge profit. And it is just for 1 share. Way better than putting the money in the bank which mostly offer 4% per year and there will be auto deduction of 20% on the earned interest.

Here is the code:

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
import pandas_ta as ta
import yfinance as yf
import pandas as pd
import numpy as np
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import datetime as dt
start = dt.datetime(2022, 1, 1)
end = dt.datetime.now()

df = yf.Ticker('TSLA').history(start=start,  end=end)[map(str.title, ['open', 'close', 'low', 'high', 'volume'])]

df.ta.macd(close='close', fast=12, slow=26, append=True)

df.columns = [x.lower() for x in df.columns]

MACD_Buy=[]
MACD_Sell=[]

position=False
risk = 0.025
for i in range(0, len(df)):     
        if df['macd_12_26_9'][i] < df['macds_12_26_9'][i] and df['macd_12_26_9'][i] < 0 and df['macd_12_26_9'][i-1] > df['macds_12_26_9'][i-1]:
            MACD_Sell.append(np.nan)
            if position ==False:
                MACD_Buy.append(df['close'][i])
                position=True
            else:
                MACD_Buy.append(np.nan)
        elif abs(df['macd_12_26_9'][i]) > abs(df['macds_12_26_9'][i]) and df['macd_12_26_9'][i] > 0 and abs(df['macd_12_26_9'][i-1]) < abs(df['macds_12_26_9'][i-1]):
            MACD_Buy.append(np.nan)
            if position == True:
                MACD_Sell.append(df['close'][i])
                                    
                position=False
            else:
                MACD_Sell.append(np.nan)
        elif position == True and df['close'][i] > MACD_Sell[-1] * (1 - risk):
            MACD_Sell.append(df['close'][i])
            MACD_Buy.append(np.nan)
            position = False
        elif position == True and df['close'][i] < MACD_Buy[-1] * (1 - risk):
            MACD_Sell.append(df['close'][i])
            MACD_Buy.append(np.nan)
            position = False
        elif position == True and df['close'][i] < df['close'][i - 1] * (1 - risk):
            MACD_Sell.append(df["close"][i])
            MACD_Buy.append(np.nan)
            position = False
        else:
            MACD_Buy.append(np.nan)
            MACD_Sell.append(np.nan)


df['MACD_Buy_Signal_price'] = MACD_Buy
df['MACD_Sell_Signal_price'] = MACD_Sell
df.to_csv('tsla_stock.csv')
macd_plot = make_subplots(rows=3, cols=1)


macd_plot.append_trace(
    go.Scatter(
        x=df.index,
        y=df['close'],
        line=dict(color='#ff9900', width=1),
        name='close',
        legendgroup='1',
    ), row=1, col=1
)


macd_plot.append_trace(
    go.Candlestick(
        x=df.index,
        open=df['open'],
        high=df['high'],
        low=df['low'],
        close=df['close'],
        increasing_line_color='green',
        decreasing_line_color='red',
        showlegend=False
    ), row=1, col=1
)


#  (%k)
macd_plot.append_trace(
    go.Scatter(
        x=df.index,
        y=df['macd_12_26_9'],
        line=dict(color='#ff9900', width=2),
        name='macd',
        legendgroup='2',
    ), row=2, col=1
)
# (%d)
macd_plot.append_trace(
    go.Scatter(
        x=df.index,
        y=df['macds_12_26_9'],
        line=dict(color='#000000', width=2),
 
        legendgroup='2',
        name='signal'
    ), row=2, col=1
)

design = np.where(df['macdh_12_26_9'] < 0, '#000', '#ff9900')

macd_plot.append_trace(
    go.Bar(
        x=df.index,
        y=df['macdh_12_26_9'],
        name='histogram',
        marker_color=design,
    ), row=2, col=1
)
macd_plot.append_trace(
    go.Scatter(
        mode = 'markers',
        x=df.index,
        y=df['MACD_Buy_Signal_price'],
        
        name='Buy Signal',
        legendgroup='1',
        marker = dict(color = 'black', size = 10),
    ), row=1, col=1
)

macd_plot.append_trace(
    go.Scatter(
        mode = 'markers',
        x=df.index,
        y=df['MACD_Sell_Signal_price'],
        
        name='Sell Signal',
        legendgroup='1',
        marker = dict(color = 'blue', size = 10),
    ), row=1, col=1
)

layout = go.Layout(
    plot_bgcolor='#efefef',
    font_family='Monospace',
    font_color='#000000',
    font_size=20,
    autosize=True,
    xaxis=dict(
        rangeslider=dict(
            visible=False
        )
    )
)

macd_plot.update_layout(layout)
macd_plot.show()


No comments:

Post a Comment

Managing Trading Risks by Knowing Calendar Events That Affect Market Volatility

  Introduction to Trading Risks In Forex and other financial markets, risk management is one of the most critical aspects of successful trad...