OPEN-SOURCE SCRIPT

Hour/Day/Month Optimizer [CHE]

127
Hour/Day/Month Optimizer [CHE] — Bucketed seasonality ranking for hours, weekdays, and months with additive or compounded returns, win rate, simple Sharpe proxy, and trade counts

Summary

This indicator profiles time-of-day, day-of-week, and month-of-year behavior by assigning every bar to a bucket and accumulating its return into that bucket. It reports per-bucket score (additive or compounded), win rate, a dispersion-aware return proxy, and trade counts, then ranks buckets and highlights the current one if it is best or worst. A compact on-chart table shows the top buckets or the full ranking; a last-bar label summarizes best and worst. Optional hour filtering and UTC shifting let you align buckets with your trading session rather than exchange time.

Motivation: Why this design?

Traders often see repetitive timing effects but struggle to separate genuine seasonality from noise. Static averages are easily distorted by sample size, compounding, or volatility spikes. The core idea here is simple, explicit bucket aggregation with user-controlled accumulation (sum or compound) and transparent quality metrics (win rate, a dispersion-aware proxy, and counts). The result is a practical, legible seasonality surface that can be used for scheduling and filtering rather than prediction.

What’s different vs. standard approaches?

Reference baseline: Simple heatmaps or average-return tables that ignore compounding, dispersion, or sample size.
Architecture differences:

Dual aggregation modes: additive sum of bar returns or compounded factor.
Per-bucket win rate and trade count to expose sample support.
A simple dispersion-aware return proxy to penalize unstable averages.
UTC offset and optional custom hour window.
Deterministic, closed-bar rendering via a lightweight on-chart table.
Practical effect: You see not only which buckets look strong but also whether the observation is supported by enough bars and whether stability is acceptable. The background tint and last-bar label give immediate context for the current bucket.

How it works (technical)

Each bar is assigned to a bucket based on the selected dimension (hour one to twenty-four, weekday one to seven, or month one to twelve) after applying the UTC shift. An optional hour filter can exclude bars outside a chosen window. For each bucket the script accumulates either the sum of simple returns or the compounded product of bar factors. It also counts bars and wins, where a win is any bar with a non-negative return. From these, it derives:

Score: additive total or compounded total minus the neutral baseline.
Win rate: wins as a percentage of bars in the bucket.
Dispersion-aware proxy (“Sharpe” column): a crude ratio that rises when average return improves and falls when variability increases.
Buckets are sorted by a user-selected key (score, win rate, dispersion proxy, or trade count). The current bar’s bucket is tinted if it matches the global best or worst. At the last bar, a table is drawn with headers, an optional info row, and either the top three or all rows, using zebra backgrounds and color-coding (lime for best, red for worst). Rendering is last-bar only; no higher-timeframe data is requested, and no future data is referenced.

Parameter Guide

UTC Offset (hours) — Shifts bucket assignment relative to exchange time. Default: zero. Tip: Align to your local or desk session.
Use Custom Hours — Enables a local session window. Default: off. Trade-off: Reduces noise outside your active hours but lowers sample size.
Start / End — Inclusive hour window one to twenty-four. Defaults: eight to seventeen. Tip: Widen if rankings look unstable.
Aggregation — “Additive” sums bar returns; “Multiplicative” compounds them. Default: Additive. Tip: Use compounded for long-horizon bias checks.
Dimension — Bucket by Hour, Day, or Month. Default: Hour. Tip: Start Hour for intraday planning; switch to Day or Month for scheduling.
Show — “Top Three” or “All”. Default: Top Three. Trade-off: Clarity vs. completeness.
Sort By — Score, Win Rate, Sharpe, or Trades. Default: Score. Tip: Use Trades to surface stable buckets; use Win Rate for skew awareness.
X / Y — Table anchor. Defaults: right / top. Tip: Move away from price clusters.
Text — Table text size. Default: normal.
Light Mode — Light palette for bright charts. Default: off.
Show Parameters Row — Info header with dimension and span. Default: on.
Highlight Current Bucket if Best/Worst — Background tint when current bucket matches extremes. Default: on.
Best/Worst Barcolor — Tint colors. Defaults: lime / red.
Mark Best/Worst on Last Bar — Summary label on the last bar. Default: on.

Reading & Interpretation

Score column: Higher suggests stronger cumulative behavior for the chosen aggregation. Compounded mode emphasizes persistence; additive mode treats all bars equally.
Win Rate: Stability signal; very high with very low trades is unreliable.
“Sharpe” column: A quick stability proxy; use it to down-rank buckets that look good on score but fluctuate heavily.
Trades: Sample size. Prefer buckets with adequate counts for your timeframe and asset.
Tinting: If the current bucket is globally best, expect a lime background; if worst, red. This is context, not a trade signal.

Practical Workflows & Combinations

Trend following: Use Hour or Day to avoid initiating trades during historically weak buckets; require structure confirmation such as higher highs and higher lows, plus a momentum or volatility filter.
Mean reversion: Prefer buckets with moderate scores but acceptable win rate and dispersion proxy; combine with deviation bands or volume normalization.
Exits/Stops: Tighten exits during historically weak buckets; relax slightly during strong ones, but keep absolute risk controls independent of the table.
Multi-asset/Multi-TF: Start with Hour on liquid intraday assets; for swing, use Day. On monthly seasonality, require larger lookbacks to avoid overfitting.

Behavior, Constraints & Performance

Repaint/confirmation: Calculations use completed bars only; table and label are drawn on the last bar and can update intrabar until close.
security()/HTF: None used; repaint risk limited to normal live-bar updates.
Resources: Arrays per dimension, light loops for metric building and sorting, `max_bars_back` two thousand, and capped label/table counts.
Known limits: Sensitive to sample size and regime shifts; ignores costs and slippage; bar-based wins can mislead on assets with frequent gaps; compounded mode can over-weight streaks.

Sensible Defaults & Quick Tuning

Start: Hour dimension, Additive, Top Three, Sort by Score, default session window off.
Too many flips: Switch to Sort by Trades or raise sample by widening hours or timeframe.
Too sluggish/over-smoothed: Switch to Additive (if on compounded) or shorten your chart timeframe while keeping the same dimension.
Overfit risk: Prefer “All” view to verify that top buckets are not isolated with tiny counts; use Day or Month only with long histories.

What this indicator is—and isn’t

This is a seasonality and scheduling layer that ranks time buckets using transparent arithmetic and simple stability checks. It is not a predictive model, not a complete trading system, and it does not manage risk. Use it to plan when to engage, then rely on structure, confirmation, and independent risk management for entries and exits.

Disclaimer

The content provided, including all code and materials, is strictly for educational and informational purposes only. It is not intended as, and should not be interpreted as, financial advice, a recommendation to buy or sell any financial instrument, or an offer of any financial product or service. All strategies, tools, and examples discussed are provided for illustrative purposes to demonstrate coding techniques and the functionality of Pine Script within a trading context.

Any results from strategies or tools provided are hypothetical, and past performance is not indicative of future results. Trading and investing involve high risk, including the potential loss of principal, and may not be suitable for all individuals. Before making any trading decisions, please consult with a qualified financial professional to understand the risks involved.

By using this script, you acknowledge and agree that any trading decisions are made solely at your discretion and risk.

Do not use this indicator on Heikin-Ashi, Renko, Kagi, Point-and-Figure, or Range charts, as these chart types can produce unrealistic results for signal markers and alerts.

Best regards and happy trading

Chervolino

Aviso legal

As informações e publicações não devem ser e não constituem conselhos ou recomendações financeiras, de investimento, de negociação ou de qualquer outro tipo, fornecidas ou endossadas pela TradingView. Leia mais em Termos de uso.