Temporal Performance Analysis SuperTrend Optimization Strategy

ATR supertrend Profit Factor Winrate Performance Analytics Strategy Optimization
Created on: 2025-07-25 13:30:18 Modified on: 2025-07-25 13:30:18
Copy: 2 Number of hits: 280
avatar of ianzeng123 ianzeng123
2
Follow
319
Followers

 Temporal Performance Analysis SuperTrend Optimization Strategy  Temporal Performance Analysis SuperTrend Optimization Strategy

Overview

This strategy is a trading system based on the SuperTrend indicator, combined with a comprehensive daily performance analysis framework that tracks and analyzes strategy performance across different time periods. The strategy generates trading signals through ATR (Average True Range) and SuperTrend indicators while incorporating a powerful performance analysis tool that statistically analyzes trading results for different days of the week and different dates of the month. This provides traders with data-driven decision support, helping to identify optimal trading times and optimize trading strategies.

Strategy Principle

The core of this strategy consists of two parts: the trading signal generation mechanism and the performance analysis system.

  1. Trading Signal Generation Mechanism:

    • Generates entry signals based on the SuperTrend indicator
    • SuperTrend is a trend-following indicator that combines ATR with a custom factor
    • Trading signals are triggered when the SuperTrend indicator direction changes
    • When direction changes from negative to positive, a long position is executed
    • When direction changes from positive to negative, a short position is executed
  2. Performance Analysis System:

    • Creates a specialized data structure (DayStats) to record statistics for each trading day
    • Tracked metrics include: win/loss trade count, gross profit, gross loss
    • Calculates derivative indicators: net profit, profit factor, win rate
    • Separately tracks performance metrics for each day of the week (Monday through Sunday)
    • Simultaneously monitors trading performance for each day of the month (1-31)
    • Visualizes performance data through tables, including different colors to indicate profit/loss status

The strategy utilizes the object-oriented features of Pine Script, creating a DayStats class to store and update trading statistics, achieving efficient data management and calculation. Through the update_all_stats() function, relevant statistics are updated after each trade, ensuring that performance data reflects the latest trading results in real-time.

Strategy Advantages

  1. Comprehensive Temporal Dimension Analysis: The most significant advantage of this strategy is its ability to deeply analyze trading performance from a temporal dimension, helping traders identify which specific dates or days of the week yield the best trading results, providing a solid data foundation for time-filtering strategies.

  2. Data-Driven Decision Support: By detailed statistical analysis of key indicators such as win rate, profit factor, and net profit for each trading day, traders can make trading decisions based on objective data rather than subjective feelings, reducing the interference of emotional factors.

  3. Enhanced Risk Management: By identifying historically underperforming trading days, traders can choose to avoid trading on these days or adjust position sizes, effectively reducing systemic risk.

  4. Visualized Performance Display: The built-in table display function intuitively presents trading performance across various time periods, using different colors to identify profit and loss status, allowing traders to grasp strategy performance at a glance.

  5. High Customization: The strategy provides multiple input parameters, including ATR period, SuperTrend factor, table position, and color settings, allowing traders to adjust according to personal preferences and market characteristics.

  6. Flexible Integration Capability: The performance analysis portion of the code is designed to be easily integrated into other trading strategies, enhancing the strategy’s practicality and extensibility.

Strategy Risks

  1. Insufficient Sample Data Risk: When trading samples are limited, statistical results for certain dates may not be statistically significant. Decisions based on this limited data may lead to incorrect optimization directions. The solution is to ensure a sufficiently long backtesting period to obtain more trading samples and improve statistical reliability.

  2. Overfitting Risk: Excessive reliance on historical performance for specific dates may cause the strategy to overfit historical data and fail when future market environments change. Traders should use temporal analysis as a reference factor rather than the sole decision basis and regularly verify the stability of analysis results.

  3. Signal Generation Mechanism Limitations: The SuperTrend indicator may produce frequent false signals in oscillating markets, leading to overtrading and unnecessary losses. It is recommended to use this in strong trend markets or combine with other confirmation indicators to filter out false signals.

  4. Computational Resource Consumption: As the number of trades increases, the amount of data that needs to be stored and processed by the performance analysis system also increases, potentially affecting strategy operating efficiency. Attention should be paid to resource usage in long-term backtesting or live trading.

  5. Seasonal Factor Influence: Some markets have seasonal patterns, and analyzing solely by day of week or month may ignore the influence of longer-cycle seasonality. Consider adding quarterly or annual level analysis to capture longer-cycle patterns.

Strategy Optimization Directions

  1. Multiple Timeframe Analysis: The current strategy only analyzes performance within a single timeframe. It can be extended to simultaneously analyze trading performance across multiple timeframes, such as examining performance differences between daily, 4-hour, and 1-hour charts, to gain more comprehensive temporal dimension insights.

  2. Add Market Condition Classification: Incorporate market condition classification into performance analysis, such as distinguishing performance in trending versus oscillating markets, or differences between high and low volatility environments, to help discover the strategy’s advantages and disadvantages in specific market environments.

  3. Signal Quality Scoring System: Introduce a signal quality scoring mechanism based on factors such as technical indicator consistency, price structure, volume confirmation, etc., to score each trading signal and incorporate signal quality dimension into performance analysis, helping to identify characteristics of high-quality signals.

  4. Adaptive Parameter Optimization: Automatically adjust SuperTrend’s ATR period and factor parameters based on historical performance data, enabling the strategy to adapt to changes in different market conditions, improving strategy adaptability and robustness.

  5. Integrate Economic Calendar Data: Integrate information about important economic data releases, central bank decisions, and other events into performance analysis, studying patterns in trading performance before and after specific economic events, providing event-driven decision support for traders.

  6. Expand Statistical Indicators: Add more statistical indicators, such as maximum consecutive profitable/losing trades, average profit/loss ratio, Sharpe ratio, etc., to provide deeper performance evaluation and help traders more comprehensively understand strategy characteristics.

  7. Machine Learning Pattern Recognition: Introduce simple machine learning algorithms to automatically identify potential temporal patterns and regularities from historical performance data, predict possible performance for future trading days, and provide forward-looking guidance for trading decisions.

Summary

The Temporal Performance Analysis SuperTrend Optimization Strategy is an innovative solution that combines a trend-following trading system with comprehensive temporal dimension performance analysis. This strategy not only provides trading signals based on the SuperTrend indicator but, more importantly, builds a powerful analytical framework capable of systematically evaluating strategy performance differences across various time periods.

By detailed tracking of trading results across different days of the week and month, traders can identify time patterns with statistical advantages and specifically optimize trading strategies. The value of this analytical framework is not limited to the current SuperTrend strategy but can be easily integrated into other trading systems, providing temporal dimension optimization ideas for various strategies.

This data-driven approach elevates intuitive trading to the level of quantitative analysis, allowing traders to make more rational decisions based on objective statistical data. As trading samples accumulate and analytical dimensions expand, the value of this strategy will further increase, providing traders with increasingly precise temporal optimization guidance.

Strategy source code
/*backtest
start: 2024-07-25 00:00:00
end: 2025-07-23 08:00:00
period: 1d
basePeriod: 1d
exchanges: [{"eid":"Futures_Binance","currency":"SOL_USDT"}]
*/

//@version=6
strategy("Daily Performance Analysis [Mr_Rakun]", overlay=true)

atrPeriod = input(10, "ATR Length")
factor = input.float(3.0, "Factor", step = 0.01)

[st, direction] = ta.supertrend(factor, atrPeriod)

if ta.change(direction) < 0
    strategy.entry("My Long Entry Id", strategy.long)

if ta.change(direction) > 0
    strategy.entry("My Short Entry Id", strategy.short)

plot(st, title="SuperTrend", color=st < close ? color.green : color.red, linewidth=2)

//-------------------------------------------------------------
// Copy the rest of this line and add it to your own strategy.

// Daily Performance
type DayStats
    int wins = 0
    int losses = 0
    float gross_profit = 0.0
    float gross_loss = 0.0

update(DayStats ds, float profit) =>
    if profit > 0
        ds.wins += 1
        ds.gross_profit += profit
    else
        ds.losses += 1
        ds.gross_loss += math.abs(profit)

net_profit(DayStats ds) => ds.gross_profit - ds.gross_loss
profit_factor(DayStats ds) => ds.gross_loss > 0 ? ds.gross_profit / ds.gross_loss : na
winrate(DayStats ds) =>
    total = ds.wins + ds.losses
    total > 0 ? (ds.wins / total) * 100 : na

// ================== GLOBAL OBJECTS ==================

var DayStats monday    = DayStats.new()
var DayStats tuesday   = DayStats.new()
var DayStats wednesday = DayStats.new()
var DayStats thursday  = DayStats.new()
var DayStats friday    = DayStats.new()
var DayStats saturday  = DayStats.new()
var DayStats sunday    = DayStats.new()
var array<DayStats> monthStats = array.new<DayStats>()

// ================== UPDATE METHOD ==================
update_all_stats() =>
    if barstate.isfirst
        for i = 0 to 30
            array.push(monthStats, DayStats.new())

    if strategy.closedtrades > strategy.closedtrades[1]
        idx = strategy.closedtrades - 1
        profit = strategy.closedtrades.profit(idx)
        poz_time = strategy.closedtrades.entry_time(idx)
        dom = dayofmonth(poz_time)
        day = dayofweek(poz_time)

        DayStats day_stats = switch day
            dayofweek.sunday    => sunday
            dayofweek.monday    => monday
            dayofweek.tuesday   => tuesday
            dayofweek.wednesday => wednesday
            dayofweek.thursday  => thursday
            dayofweek.friday    => friday
            dayofweek.saturday  => saturday

        if na(day_stats) == false
            update(day_stats, profit)

        if dom >= 1 and dom <= 31
            DayStats mstats = array.get(monthStats, dom - 1)
            update(mstats, profit)
        day_stats

update_all_stats()

 
// Table positioning inputs
weekly_position = input.string("Top Center", "Weekly Table Position", 
     options=["Top Left", "Top Center", "Top Right", "Middle Left", "Middle Center", "Middle Right", "Bottom Left", "Bottom Center", "Bottom Right"])
monthly_position = input.string("Top Right", "Monthly Table Position", 
     options=["Top Left", "Top Center", "Top Right", "Middle Left", "Middle Center", "Middle Right", "Bottom Left", "Bottom Center", "Bottom Right"])

// Color inputs
header_bg_color = input.color(color.gray, "Header Background Color")
profit_color = input.color(color.lime, "Profit Color")
loss_color = input.color(color.red, "Loss Color")
neutral_color = input.color(color.gray, "Neutral Color")
row_bg_color = input.color(color.new(color.gray, 60), "Row Background Color")

// Function to get table position
get_table_position(string pos) =>
    switch pos
        "Top Left" => position.top_left
        "Top Center" => position.top_center
        "Top Right" => position.top_right
        "Middle Left" => position.middle_left
        "Middle Center" => position.middle_center
        "Middle Right" => position.middle_right
        "Bottom Left" => position.bottom_left
        "Bottom Center" => position.bottom_center
        "Bottom Right" => position.bottom_right
        => position.top_center

// TABLE PRINTING 
draw_table_headers(table weekly, table monthly) =>
    table.cell(weekly, 0, 0, "DAY",          text_color=color.white, text_size=size.small, bgcolor = header_bg_color)
    table.cell(weekly, 1, 0, "W/L (Count)",  text_color=color.white, text_size=size.small, bgcolor = header_bg_color)
    table.cell(weekly, 2, 0, "NET PROFIT",   text_color=color.white, text_size=size.small, bgcolor = header_bg_color)
    table.cell(weekly, 3, 0, "PROFIT FACTOR",text_color=color.white, text_size=size.small, bgcolor = header_bg_color)
    table.cell(weekly, 4, 0, "WINRATE",      text_color=color.white, text_size=size.small, bgcolor = header_bg_color)

    table.cell(monthly, 0, 0, "DAY",          text_color=color.white, text_size=size.small, bgcolor = header_bg_color)
    table.cell(monthly, 1, 0, "W/L (Count)",  text_color=color.white, text_size=size.small, bgcolor = header_bg_color)
    table.cell(monthly, 2, 0, "NET PROFIT",   text_color=color.white, text_size=size.small, bgcolor = header_bg_color)
    table.cell(monthly, 3, 0, "PROFIT FACTOR",text_color=color.white, text_size=size.small, bgcolor = header_bg_color)
    table.cell(monthly, 4, 0, "WINRATE",      text_color=color.white, text_size=size.small, bgcolor = header_bg_color)

fill_weekly_row(table tbl, int row, string day_name, DayStats ds) =>
    net_p = net_profit(ds)
    pf = profit_factor(ds)
    wr = winrate(ds)
    status_color = net_p > 0 ? profit_color: (net_p < 0 ? loss_color : neutral_color)

    table.cell(tbl, 0, row, day_name, text_color=status_color, text_size=size.small, bgcolor = row_bg_color)
    table.cell(tbl, 1, row, str.tostring(ds.wins) + "/" + str.tostring(ds.losses), text_color=status_color, text_size=size.small, bgcolor = row_bg_color)
    table.cell(tbl, 2, row, str.tostring(net_p, '#,###.##'), text_color=status_color, text_size=size.small, bgcolor = row_bg_color)
    table.cell(tbl, 3, row, str.tostring(pf, '0.00'), text_color=status_color, text_size=size.small, bgcolor = row_bg_color)
    table.cell(tbl, 4, row, str.tostring(wr, format.percent), text_color=status_color, text_size=size.small, bgcolor = row_bg_color)

fill_monthly_row(table tbl, int row, int day, DayStats ds) =>
    net_p = net_profit(ds)
    pf = profit_factor(ds)
    wr = winrate(ds)
    status_color = net_p > 0 ? profit_color : (net_p < 0 ? loss_color : neutral_color)

    table.cell(tbl, 0, row, str.tostring(day), text_color=status_color, bgcolor=row_bg_color, text_size=size.tiny)
    table.cell(tbl, 1, row, str.tostring(ds.wins) + "/" + str.tostring(ds.losses), text_color=status_color, bgcolor=row_bg_color, text_size=size.tiny)
    table.cell(tbl, 2, row, str.tostring(net_p, '#,###.##'), text_color=status_color, bgcolor=row_bg_color, text_size=size.tiny)
    table.cell(tbl, 3, row, str.tostring(pf, '0.00'), text_color=status_color, bgcolor=row_bg_color, text_size=size.tiny)
    table.cell(tbl, 4, row, str.tostring(wr, format.percent), text_color=status_color, bgcolor=row_bg_color, text_size=size.tiny)

var table weekly_table = table.new(get_table_position(weekly_position), 5, 8)
var table monthly_table = table.new(get_table_position(monthly_position), 5, 32)

if barstate.isconfirmed
    draw_table_headers(weekly_table, monthly_table)

    fill_weekly_row(weekly_table, 1, "MON", monday)
    fill_weekly_row(weekly_table, 2, "TUE", tuesday)
    fill_weekly_row(weekly_table, 3, "WED", wednesday)
    fill_weekly_row(weekly_table, 4, "THU", thursday)
    fill_weekly_row(weekly_table, 5, "FRI", friday)
    fill_weekly_row(weekly_table, 6, "SAT", saturday)
    fill_weekly_row(weekly_table, 7, "SUN", sunday)

    for i = 0 to 30
        DayStats ms = array.get(monthStats, i)
        if ms.wins + ms.losses > 0
            fill_monthly_row(monthly_table, i + 1, i + 1, ms)