Thursday, May 25, 2023

Making some modifications on my article "How I will trade using MACD as indicator"

 This is in reference to my previous post(How I will trade using MACD as indicator). Based on the video, to use the MACD, it should be also checked against the 200 Exponential Moving Average indicator. For details, pls watch the said video on the article which I made as reference. I believe in his formula becasue it is based on actual historical data and also I had made the same observation as he did. 

So in this article, I modified the program accordingly to include the 200-EMA in the plot and I also use matplotlib to make it more presentable. Here is the output:



Other changes made to the program:
  1. Generate Buy/Sell Signals
  2. Red Triangle - Indicates a Buy Signal
  3. Blue Inverted Triangle - Indicates a Sell Signal
  4. Criteria for a Buy Signal :  close price is above the 200ema and the macd and signal crosses below the zero line and the histogram is positive
  5. Criteria for a Sell Signal :  close price is below the 200ema and the macd and signal crosses above the zero line and the histogram is negative
  6. Prints Buy/Signal and the Date at the command prompt

And 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
import yfinance as yf
import matplotlib.pyplot as plt
import numpy as np

# Retrieve historical data of AAPL from Yahoo Finance
data = yf.download('AAPL', period='1y')

# Calculate 200-day EMA
data['EMA_200'] = data['Close'].ewm(span=200, adjust=False).mean()

# Calculate MACD
data['ema_12'] = data['Close'].ewm(span=12, adjust=False).mean()
data['ema_26'] = data['Close'].ewm(span=26, adjust=False).mean()
data['MACD'] = data['ema_12'] - data['ema_26']
data['Signal'] = data['MACD'].ewm(span=9, adjust=False).mean()
data['Histogram'] = data['MACD'] - data['Signal']

# Define colors based on histogram values and trends
colors = np.where((data['Histogram'] > 0) & (data['Histogram'].diff() > 0), 'green',   # Increasing and positive
                  np.where((data['Histogram'] > 0) & (data['Histogram'].diff() <= 0), 'lightgreen',  # Decreasing and positive
                           np.where((data['Histogram'] < 0) & (data['Histogram'].diff() < 0), 'red',  # Decreasing and negative
                                    'lightcoral')))  # Increasing and negative

# Find the indices where conditions are met for the blue dot
blue_dot_indices = np.where(
    (data['Close'] < data['EMA_200']) &
    (data['MACD'] > 0) &
    (data['Signal'] > 0) &
    (data['Histogram'] < 0)
)[0]

# Find the indices where conditions are met for the red dot
red_dot_indices = np.where(
    (data['Close'] > data['EMA_200']) &
    (data['MACD'] < 0) &
    (data['Signal'] < 0) &
    (data['Histogram'] > 0)
)[0]

# Plot the closing price, EMA 200, MACD line, Signal line, and Histogram
plt.figure(figsize=(12, 8))
plt.subplot(2, 1, 1)
plt.plot(data.index, data['Close'], label='Close')
plt.plot(data.index, data['EMA_200'], label='EMA 200')
plt.scatter(data.index[blue_dot_indices], data['Close'].iloc[blue_dot_indices], marker='v', c='blue', s=50, label='Sell Signal')
plt.scatter(data.index[red_dot_indices], data['Close'].iloc[red_dot_indices], marker='^', c='red', s=50, label='Buy Signal')
plt.title('AAPL Stock Price')
plt.xlabel('Date')
plt.ylabel('Price')
plt.legend()

plt.subplot(2, 1, 2)
plt.plot(data.index, data['MACD'], label='MACD')
plt.plot(data.index, data['Signal'], label='Signal')
plt.bar(data.index, data['Histogram'], label='Histogram', color=colors, alpha=0.8, width=0.8)
plt.title('MACD')
plt.xlabel('Date')
plt.ylabel('MACD')
plt.legend()

# Adjust line thickness and magnify the histogram
ax = plt.gca()
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['bottom'].set_linewidth(2.0)
ax.spines['left'].set_linewidth(2.0)
ax.bar(data.index, data['Histogram'], color=colors, alpha=0.8, width=0.8)
ax.margins(0, 0.2)

# Print "Buy" and "Sell" labels
for idx in blue_dot_indices:
    print('Sell', data.index[idx].date())
for idx in red_dot_indices:
    print('Buy', data.index[idx].date())

plt.tight_layout()
plt.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...