To find more accurate entry and exit points within the levels identified, we can incorporate additional indicators and refine entry criteria. One common method to enhance precision is by using a combination of technical indicators. For this example, we can use:
- RSI (Relative Strength Index): It helps in identifying overbought or oversold conditions.
- MACD (Moving Average Convergence Divergence): It helps in identifying momentum changes.
This enhanced code will:
- Use the Z-score to identify broader levels.
- Use RSI and MACD to fine-tune exact entry and exit points within those levels.
Here's the refined Python code:
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import yfinance as yf
# Fetching data
data = yf.download(tickers="GC=F", period="1mo", interval="1h")['Close']
# Dropping NaN values
data.dropna(inplace=True)
# Calculating Z-score
x = data
y = x.rolling(window=35).mean()
z = x.rolling(window=35).std()
score = (x - y) / z
# RSI Indicator
def compute_RSI(data, window=14):
diff = data.diff(1).dropna()
gain = 0.5 * (diff + abs(diff))
loss = 0.5 * (-diff + abs(diff))
RS = gain.rolling(window=window).mean() / loss.rolling(window=window).mean()
return 100 - 100 / (1 + RS)
rsi = compute_RSI(data)
# MACD Indicator
def compute_MACD(data, short_window=12, long_window=26, signal_window=9):
short_ema = data.ewm(span=short_window, adjust=False).mean()
long_ema = data.ewm(span=long_window, adjust=False).mean()
MACD_line = short_ema - long_ema
signal_line = MACD_line.ewm(span=signal_window, adjust=False).mean()
return MACD_line, signal_line, MACD_line - signal_line
macd_line, signal_line, macd_hist = compute_MACD(data)
# Fine-tuning entry and exit points
def fine_tune_trading_rule(scores, rsi, macd_hist, data):
buy_signals = []
sell_signals = []
for i in range(1, len(scores)):
# Buy condition: Z-score < -2.58 and RSI < 30 (oversold) and MACD histogram turning positive
if scores[i] < -2.58 and rsi[i] < 30 and macd_hist[i] > 0 and macd_hist[i-1] <= 0:
buy_signals.append(x.index[i])
# Sell condition: Z-score > 2.58 and RSI > 70 (overbought) and MACD histogram turning negative
elif scores[i] > 2.58 and rsi[i] > 70 and macd_hist[i] < 0 and macd_hist[i-1] >= 0:
sell_signals.append(x.index[i])
return buy_signals, sell_signals
buy_signals, sell_signals = fine_tune_trading_rule(score, rsi, macd_hist, data)
# Plotting
fig, ax1 = plt.subplots(figsize=(20,10))
color = 'tab:red'
ax1.set_xlabel('Date')
ax1.set_ylabel('Closing Prices', color=color)
ax1.plot(data.index, data, color=color)
ax1.tick_params(axis='y', labelcolor=color)
# Plot Buy/Sell signals on the primary axis
ax1.plot(data.loc[buy_signals].index, data.loc[buy_signals], '^', markersize=10, color='g', lw=0, label='Buy Signal')
ax1.plot(data.loc[sell_signals].index, data.loc[sell_signals], 'v', markersize=10, color='r', lw=0, label='Sell Signal')
ax1.legend()
ax2 = ax1.twinx()
color = 'tab:blue'
ax2.set_ylabel('Z-Score', color=color)
ax2.plot(score.index, score, color=color)
ax2.axhline(0, color='black')
ax2.axhline(1.96, color='red')
ax2.axhline(-1.96, color='green')
ax2.axhline(2.58, color='red')
ax2.axhline(-2.58, color='green')
ax2.axhline(3.26, color='red')
fig.tight_layout()
plt.title('Closing Prices, Z-Score, Fine-Tuned Buy/Sell Signals')
plt.show()
Explanation of the Code Enhancements:
-
RSI Calculation:
- The
compute_RSI function calculates the RSI over a 14-period window.
-
MACD Calculation:
- The
compute_MACD function calculates the MACD line, signal line, and histogram for momentum analysis.
-
Fine-tuning Entry/Exit Points:
- The
fine_tune_trading_rule function refines the buy and sell conditions using Z-score, RSI, and MACD histogram.
- Buy Condition: When Z-score < -2.58, RSI < 30 (indicating oversold conditions), and MACD histogram turns positive.
- Sell Condition: When Z-score > 2.58, RSI > 70 (indicating overbought conditions), and MACD histogram turns negative.
These modifications aim to improve the accuracy of the entry and exit points by incorporating RSI and MACD indicators along with the Z-score. Fine-tuning such algorithms are often iterative and may require adjustments to the parameters based on backtesting results and market conditions.