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()


Sunday, October 16, 2022

How I will trade using MACD as indicator

The Moving Average Convergence Divergence or MACD for short is a popular stock trading indicator that is used to generate buy or sell signals. It shows the momentum that can help detection of shift in trends.

To plot MACD, I need to see the computed MACD, the signal, the histogram, zero line and the actual closing value of the ticker. See below example:

I used Pandas Technical Analysis library(because it is very simple and will make the code clean and I love taking shortcuts) to get the MACD, Signal, Histogram, Zero Lines and got the historical close value from yahoo finance. I generated the above figure using plotly.

After watching several youtube videos regarding the topic "How to Trade using MACD",  the most notable video is below(but I think a lot of youtubers produced equally excellent tutorial):


From the above video, I have learned the following trading strategy:

1. A signal should be generated each time the Macd and Signal lines crosses, a sell signal is generated when the signal line is above the Macd line and a buy signal is generated when Macd line is above the signal line.

2. Observe if the market reacts to these generated signal. If the market goes the opposite direction most of the time, then don't trade using the said indicator.

3. Big waves indicates long trends that could last a few days or even years depending on the size.

4. A false signal is generated when the signal line is above the Macd line but the crossing occured below the Zero line or when the Macd line is above the signal line but the crossing occured above the zero line.

In case of Apple(APPL) as an example, it seems that MACD can be used as an indicator, see below figure:


I will soon update this post once I finish the python program to implement my trading strategy.

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
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



df = yf.Ticker('AAPL').history(period='1y')[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_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
)

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

macd_plot.update_layout(layout)
macd_plot.show()


Predicting The Next Day's Trend with Machine Learning

I have to make a short detour. Remember from last post that my next assignment is to create the trade back testing application? Well, I have set it aside for a while to give way for this new function. 

I have added a function to my python desktop application which is  also part of my original plan. This new function allows me to predict the next day's trend(whether the ticker will go down(Sell) or  up(Buy)). This is on its beta version. I have tested it with 30 days using historical data and along the fine tuned it on order for me to yield acceptable result. So far I got 85% accuracy. here is the screenshot of the new interface:


The code is not mine, I have based it from NeuralNine. Here is the video tutorial:


NeuralNine used Sequential model having LSTM(Long Short Term Memory) layers. He intentionally predicted the exact closing price of the following day which is quite impossible to do, he achieved 52% accuracy which is very low, but when I checked the chart, it seems that he can predict the trend more accurately than predicting the exact closing price that is why I decided to give it a try.

With this new function, my confidence level will go up by 5% because of the 85% accuracy, once I have achieved 98% the confidence level will go up by another 5%.

I will be testing this new function everyday and at the same time continue adding new functions to my desktop app. My plan is to redesign the layout (future plan) and probably the next assignment will be the technical analysis prediction. I want to work on this first(Technical Analysis Prediction function) because I feel that it is very useful(more useful than the trade back testing application).

Thursday, October 13, 2022

My Trading Rules Part 2(The First Rule)

First of all, I was not able to continue the previous post because I was busy with the creation of the python program that I will use for trading and now that it is useable(at least), I decided to continue the post now. 

But before the rules, let me show here the python app that I have created, please note that this is a work in progress so most features of the app is still not available. Here is the screenshot:

The particular feature of the desktop app ist that it is able to display 6 different indicators which I will use mainly for my weekly trading(yes, I will place/exit trade at least 5 days. The 6 indicators consist of trend reversals(MACD, Moving Average, Bollinger Bands) and oversold/overbought(Relative Volume, RSI, Stochastic Oscillator). And I just revealed my first trading ruile and I consider it to be the ultimate rule. 

So as my number 1 trading rule,  at least 4 of the 6 indicators should be enough to convince me to trade sell/buy position. But it would be best if 5 or 6 of them indicates otherwise. Using it as a rule builds 60% confidence on my part. I will also post separately how I interpret each of the indicators. 

What to expect in my upcoming posts?

Well, after working on the 6 indicators , the selection screen and the minor Ticker Stats(I choose the stats randomly, it really has no use for me, LOL!), my next assignment is to create a trade back testing platform. This new feature will allow me to simulate how profitable the trade will be using historical data. It should be able to compute how much I earn, show when the entry/exit on the chart. Of course it was just a simulation, but it will somehow build additional 10% confidence.

In case you are interested to ues the desktop app I created, I have uploaded the code at my github page. You may download it here. And if you are a developer and want to learn how the code works, I have severa sample program that I used to construct the screens and these are the links:

1. Combobox - Checkbox, Radiobutton and ComboBox in PyQt6

2.  Date Edit Box - Date Edit Box with calendar Dropdown in PyQt6

3.  Data Grid - Making Datagrid Read Only with PyQt6

4. Charts - Matplotlib with PyQt6

5. Labels - Label with PyQt6

 

The desktop app had unique scenarios not present in the blogposts I mentioned above so it will be a great learning programming experience for developers. Please do note that at this stage, I did not mind the perfrormance tuning of the program since it is on prototyping stage. It is not fancy either but it is useable.

Sunday, October 9, 2022

My Trading Rules

I have been researching for my trading strategies in the last couple of weeks.. I found youtube to be rich in information with this subject but is not perfect, I have to search in google for more information about a bunch of indicators and other stuffs for my technical analysis. 

Along the way, an idea sprung on my head to formulate my own trading rules. I have drafted initially the following rules and may change as my knowledge in stock trading advances. These youtube videos has influenced me so much(I do not promote her videos for advertisement purposes) to create the rules:



And from her 2 videos(the 2 videos are mainly my source but  other articles on the web contributed or helped me somehow to formulate the rules), I even imagined of creating/designing a python program to consolidate all these rules into 1 screen. Below is my initial design:


I will post chunks of the code on my other blog Python Bits and Pieces in the following days.


And now the rules:

1.  to be continued...

Friday, October 7, 2022

Introduction

This blog will document my stock trading using python. I decided to create this blog to help me monitor the performance of each algorithm I used as my trading strategy and continuously improve it over time. I am thinking of using eToro as my trading platform and I already have an account there which I created 2 years ago but never got serious about it, but now that I gained some knowledge in stock trading, I decided to get back at it.

 I tried to trade forex almost 15 years ago and I never gained any profit from it because forex trading is so unpredictable and it seems it does not have any pattern. Hopefully, stock trading will not be like that. 

My initial experience with stock trading for the last couple days using the virtual cash at eToro is that it seems to obey the technical Patterns and Indicators and it is not that chaotic. What made say thiss? So far, I gained $10 with $240 investment. I never got this experience with forex trading. If I gain $100 in the next 5 days, I will decide to use real money.

As a disclaimer, this for my own benefits and please do not consider this a financial advice.

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...