Coding Double Triangular MA Cross with Extrapolation (Python)

Female Software Engineer Coding on Computer
# Importing the libraries needed for data manipulation and plotting (numpy and matplotlib).
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# Generate sample data (replace with actual close prices)
np.random.seed(0)
dates = pd.date_range('2020-01-01', periods=100)
close_prices = np.random.randn(100).cumsum() + 100
data = pd.DataFrame({'Date': dates, 'Close': close_prices})

# Settings for the first TMA. Defining the length, shift, and color for the first TMA.
length1 = 15
shift1 = -15
cl1 = 'green'

# Assigning a function to calculate the triangular moving average (TMA).
def tma(data, length):
return data.rolling(window=length, center=True).mean()

# Plotting the first TMA (data['TMA1'] is a single line. Too long for the blog)
data['TMA1'] = tma(tma(data['Close'], np.ceil(length1 / 2).astype(int)), np.floor(length1 / 2).astype(int) + 1)
plt.plot(data['Date'], data['TMA1'], label='TMA1', color=cl1, linewidth=2)

# Function to extrapolate the TMA
def extrapolate_tma(data, length, i):
x = tma(tma(data['Close'], np.ceil((length - i) / 2).astype(int)), np.floor((length - i) / 2).astype(int) + 1)
out = (x * (length - i) + data['Close'] * i) / length
return out

# Plotting the extrapolated values for the first TMA as circles.
for i in range(1, 18):
data[f'TMA1_extrapolated_{i}'] = extrapolate_tma(data, length1, i)
plt.scatter(data['Date'].iloc[-1:], data[f'TMA1_extrapolated_{i}'].iloc[-1:], color=cl1, s=100, edgecolor='black')

# Settings for the second TMA. Defining the length, shift, and color for the second TMA.
length2 = 30
shift2 = -10
cl2 = 'red'

# Plotting the second TMA
data['TMA2'] = tma(tma(data['Close'], np.ceil(length2 / 2).astype(int)), np.floor(length2 / 2).astype(int) + 1)
plt.plot(data['Date'], data['TMA2'], label='TMA2', color=cl2, linewidth=2)

# Plotting the extrapolated values for the second TMA as circles.
for i in range(1, 16):
data[f'TMA2_extrapolated_{i}'] = extrapolate_tma(data, length2, i)
plt.scatter(data['Date'].iloc[-1:], data[f'TMA2_extrapolated_{i}'].iloc[-1:], color=cl2, s=100, edgecolor='black')

# Finalizing and displaying the plot.
plt.title('Double Triangular MA Cross')
plt.xlabel('Date')
plt.ylabel('Close Price')
plt.legend()
plt.grid(True)
plt.show()

Download and see more projects at my GitHub page.

Now, let’s check out how well it back tests!

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top