enter image description hereimport pandas as pd
import pandas_ta as ta
import math
import matplotlib.pyplot as plt
import numpy as np
# Parameters
length = 14
k = 1.0
method = 'Atr'
# Data
data = pd.read_csv('data.csv')
close = data['Close']
high = data['High']
low = data['Low']
src = close
# --- Pivot Highs / Lows ---
def find_pivot_highs(data, length):
pivot_highs = []
for i in range(length, len(data) - length):
if data[i] > max(data[i-length:i]) and data[i] > max(data[i+1:i+length+1]):
pivot_highs.append(i)
return pivot_highs
def find_pivot_lows(data, length):
pivot_lows = []
for i in range(length, len(data) - length):
if data[i] < min(data[i-length:i]) and data[i] < min(data[i+1:i+length+1]):
pivot_lows.append(i)
return pivot_lows
ph = find_pivot_highs(high, length)
pl = find_pivot_lows(low, length)
# --- Slope Calculation ---
def calculate_slope(method='Atr', length=length, k=k):
if method == 'Atr':
return ta.atr(high, low, close, length) / length * k
elif method == 'Stdev':
return ta.stdev(src, length) / length * k
else:
# Default fallback if Linreg is not defined
return pd.Series([0]*len(close), index=close.index)
slope = calculate_slope()
# --- Trendlines ---
slope_ph = [slope[i] if i in ph else 0 for i in range(len(close))]
slope_pl = [slope[i] if i in pl else 0 for i in range(len(close))]
upper = [0]*len(close)
lower = [0]*len(close)
for i in range(len(close)):
if i in ph:
upper[i] = src[i]
elif i > 0:
upper[i] = upper[i-1] - slope_ph[i]
if i in pl:
lower[i] = src[i]
elif i > 0:
lower[i] = lower[i-1] + slope_pl[i]
# --- Breakouts ---
upper_breakout = [close[i] > upper[i] for i in range(len(close))]
lower_breakout = [close[i] < lower[i] for i in range(len(close))]
# --- Trading strategy ---
trades = []
trade_type = None
entry_price = None
stop_loss = None
take_profit = None
for i in range(len(close)):
if trade_type is None:
if upper_breakout[i]:
trade_type = 'Long'
entry_price = close[i]
stop_loss = entry_price - 0.02*entry_price
take_profit = entry_price + 0.03*entry_price
elif lower_breakout[i]:
trade_type = 'Short'
entry_price = close[i]
stop_loss = entry_price + 0.02*entry_price
take_profit = entry_price - 0.03*entry_price
else:
if trade_type == 'Long' and (close[i] <= stop_loss or close[i] >= take_profit):
trades.append((entry_price, stop_loss, take_profit))
trade_type = None
elif trade_type == 'Short' and (close[i] >= stop_loss or close[i] <= take_profit):
trades.append((entry_price, stop_loss, take_profit))
trade_type = None
# --- Metrics ---
total_trades = len(trades)
positive_trades = sum(1 for t in trades if t[2] > t[0])
win_rate = positive_trades / total_trades if total_trades > 0 else 0
returns = np.array([(t[2]-t[0])/t[0] for t in trades])
cumulative_returns = returns.sum()
sharpe_ratio = (returns.mean() - 0.01) / (returns.std() + 1e-9) if len(returns)>1 else 0
sortino_ratio = (returns.mean() - 0.01) / (returns[returns<0].std() + 1e-9) if len(returns[returns<0])>0 else 0
profit_factor = sum([t[2]-t[0] for t in trades if t[2]>t[0]]) / max(abs(sum([t[2]-t[0] for t in trades if t[2]<t[0]])),1e-9)
print(f"Total Trades: {total_trades}")
print(f"Positive Trades: {positive_trades}")
print(f"Win Rate: {win_rate*100:.2f}%")
print(f"Cumulative Returns: {cumulative_returns*100:.2f}%")
print(f"Sharpe Ratio: {sharpe_ratio:.2f}")
print(f"Sortino Ratio: {sortino_ratio:.2f}")
print(f"Profit Factor: {profit_factor:.2f}")
# --- Plot ---
plt.figure(figsize=(12,6))
plt.plot(close, label='Close')
plt.plot(upper, label='Upper Trendline', color='#26a69a')
plt.plot(lower, label='Lower Trendline', color='#ef5350')
for i in range(len(close)):
if upper_breakout[i]:
plt.scatter(i, close[i], marker='^', color='r')
if lower_breakout[i]:
plt.scatter(i, close[i], marker='v', color='g')
plt.legend()
plt.show()