EV Calculator [CHE]EV Calculator with Adjustable Boxes and Custom Colors for TradingView
Introduction:
As a trader, one of the key metrics you need to evaluate is the Expected Value (EV) of your trading strategy. Understanding EV helps you gauge whether your trades will be profitable in the long run. This TradingView script allows you to visualize your EV alongside customizable win rates and risk-to-reward ratios. With adjustable visual components, you can quickly determine whether your trading strategy has a positive or negative EV, and make informed decisions.
Features of the Script:
1. Customizable Inputs:
- Win Rate: Set your win probability (0.0 to 1.0), which represents how often your strategy is successful.
- Risk and Reward: Define how much you're risking and the potential reward for each trade.
2. Visual Representation:
- The script creates colored boxes representing different EV scenarios:
- Green Box: Indicates a good EV (>2), suggesting a highly profitable strategy.
- Yellow Box: Represents a neutral EV (between 0 and 2), where the strategy could work but is not optimal.
- Red Box: Shows a negative EV (<0), signaling that the strategy may lead to losses.
3. Adjustable Box Size:
- You can modify the width and height of the boxes to fit your chart display preferences, giving you better visual clarity based on your screen or chart style.
4. Dynamic Labels:
- Each bar in the chart includes dynamic labels showing:
- Win Rate: Displays the percentage chance of success.
- EV Value: Shows the calculated expected value based on the win rate and risk-reward ratio.
- Guide: Explains what each colored box means so that you can easily interpret the chart.
5. Scalability and Flexibility:
- The script only keeps a maximum of 20 recent entries, ensuring that your chart stays clean and organized.
- Both the number of labels and boxes adjust automatically to match your preferred settings, enhancing usability.
How the EV Calculation Works:
The formula for EV is based on a standard risk-to-reward model:
EV = (Win\ Rate \times Reward) - (Loss\ Probability \times Risk)
For example:
- If your win rate is 60% and your risk-to-reward ratio is 1:3, the script will calculate whether this strategy is expected to yield positive returns or result in long-term losses.
Example Use Case:
Let's say you are trading with a 60% win rate, risking 1 unit to gain 3 units. The script calculates that your EV is positive and represents this with a Green Box, showing you that your strategy has a high likelihood of being profitable. If your strategy slips and the win rate drops, the EV calculation will adjust, and you may see Yellow or Red Boxes, signaling a need for adjustment.
Final Thoughts:
This script is designed for traders who want to take their analysis beyond the basics. By providing real-time visualization of your EV, you can better assess whether your strategy is sound and make adjustments as needed.
How to Use:
- Adjust the input parameters for Win Rate, Risk, and Reward to match your trading strategy.
- Observe the colored boxes and labels to quickly understand if your current strategy is in a healthy EV zone.
- Use this visual feedback to refine your approach and stay on track towards profitability.
This tool simplifies the complex calculations behind EV and turns it into an intuitive and powerful decision-making aid for traders.
Now you're ready to integrate the EV Calculator with Adjustable Boxes and Custom Colors into your trading routine and start optimizing your strategies for long-term success!
Happy Trading and best regards Chervolino
Statistics
High/Low Breakout Statistical Analysis StrategyThis Pine Script strategy is designed to assist in the statistical analysis of breakout systems on a monthly, weekly, or daily timeframe. It allows the user to select whether to open a long or short position when the price breaks above or below the respective high or low for the chosen timeframe. The user can also define the holding period for each position in terms of bars.
Core Functionality:
Breakout Logic:
The strategy triggers trades based on price crossing over (for long positions) or crossing under (for short positions) the high or low of the selected period (daily, weekly, or monthly).
Timeframe Selection:
A dropdown menu enables the user to switch between the desired timeframe (monthly, weekly, or daily).
Trade Direction:
Another dropdown allows the user to select the type of trade (long or short) depending on whether the breakout occurs at the high or low of the timeframe.
Holding Period:
Once a trade is opened, it is automatically closed after a user-defined number of bars, making it useful for analyzing how breakout signals perform over short-term periods.
This strategy is intended exclusively for research and statistical purposes rather than real-time trading, helping users to assess the behavior of breakouts over different timeframes.
Relevance of Breakout Systems:
Breakout trading systems, where trades are executed when the price moves beyond a significant price level such as the high or low of a given period, have been extensively studied in financial literature for their potential predictive power.
Momentum and Trend Following:
Breakout strategies are a form of momentum-based trading, exploiting the tendency of prices to continue moving in the direction of a strong initial movement after breaching a critical support or resistance level. According to academic research, momentum strategies, including breakouts, can produce returns above average market returns when applied consistently. For example, Jegadeesh and Titman (1993) demonstrated that stocks that performed well in the past 3-12 months continued to outperform in the subsequent months, suggesting that price continuation patterns, like breakouts, hold value .
Market Efficiency Hypothesis:
While the Efficient Market Hypothesis (EMH) posits that markets are generally efficient, and it is difficult to outperform the market through technical strategies, some studies show that in less liquid markets or during specific times of market stress, breakout systems can capitalize on temporary inefficiencies. Taylor (2005) and other researchers have found instances where breakout systems can outperform the market under certain conditions.
Volatility and Breakouts:
Breakouts are often linked to periods of increased volatility, which can generate trading opportunities. Coval and Shumway (2001) found that periods of heightened volatility can make breakouts more significant, increasing the likelihood that price trends will follow the breakout direction. This correlation between volatility and breakout reliability makes it essential to study breakouts across different timeframes to assess their potential profitability .
In summary, this breakout strategy offers an empirical way to study price behavior around key support and resistance levels. It is useful for researchers and traders aiming to statistically evaluate the effectiveness and consistency of breakout signals across different timeframes, contributing to broader research on momentum and market behavior.
References:
Jegadeesh, N., & Titman, S. (1993). Returns to Buying Winners and Selling Losers: Implications for Stock Market Efficiency. Journal of Finance, 48(1), 65-91.
Fama, E. F., & French, K. R. (1996). Multifactor Explanations of Asset Pricing Anomalies. Journal of Finance, 51(1), 55-84.
Taylor, S. J. (2005). Asset Price Dynamics, Volatility, and Prediction. Princeton University Press.
Coval, J. D., & Shumway, T. (2001). Expected Option Returns. Journal of Finance, 56(3), 983-1009.
High Yield Spread Strategy with SMA FilterThis Pine Script strategy is designed for statistical analysis and research purposes only, not for live trading or financial decision-making. The script evaluates the relationship between financial volatility (measured by either the VIX or the High Yield Spread) and market positioning strategies (long or short) based on user-defined conditions. Specifically, it allows users to test the assumption that elevated levels of VIX or the High Yield Spread may justify short positions in the market—a widely held belief in financial circles—but this script demonstrates that shorting is not always the optimal choice, even under these conditions.
Key Components:
1. High Yield Spread and VIX:
• High Yield Spread is the difference between the yields of corporate high-yield (or “junk”) bonds and U.S. Treasury securities. A rising spread often reflects increased market risk perception.
• VIX (Volatility Index) is often referred to as the market’s “fear gauge.” Higher VIX levels usually indicate heightened market uncertainty or expected volatility.
2. Strategy Logic:
• The script allows users to specify a threshold for the VIX or High Yield Spread, and it automatically evaluates if the spread exceeds this level, which traditionally would suggest an environment for higher market risk and thus potentially favoring short trades.
• However, the strategy provides flexibility to enter long or short positions, even in a high-risk environment, emphasizing that a high VIX or High Yield Spread does not always warrant shorting.
3. SMA Filter:
• A Simple Moving Average (SMA) filter can be applied to the price data, where positions are only entered if the price is above or below the SMA (depending on the trade direction). This adds a technical component to the strategy, incorporating price trends into decision-making.
4. Hold Duration:
• The script also allows users to define how long to hold a position after entering, enabling an analysis of different timeframes.
Theoretical Background:
The traditional belief that high VIX or High Yield Spreads favor short positions is not universally supported by research. While a spike in the VIX or credit spreads is often associated with increased market risk, research suggests that excessive volatility does not always lead to negative returns. In fact, high volatility can sometimes signal an approaching market rebound.
For example:
• Studies have shown that long-term investments during periods of heightened volatility can yield favorable returns due to mean reversion. Whaley (2000) notes that VIX spikes are often followed by market recoveries as volatility tends to revert to its mean over time .
• Research by Blitz and Vliet (2007) highlights that low-volatility stocks have historically outperformed high-volatility stocks, suggesting that volatility may not always predict negative returns .
• Furthermore, credit spreads can widen in response to broader market stress, but these may overshoot the actual credit risk, presenting opportunities for long positions when spreads are high and risk premiums are mispriced .
Educational Purpose:
The goal of this script is to challenge assumptions about shorting during volatile periods, showing that long positions can be equally, if not more, effective during market stress. By incorporating an SMA filter and customizable logic for entering trades, users can test different hypotheses regarding the effectiveness of both long and short positions under varying market conditions.
Note: This strategy is not intended for live trading and should be used solely for educational and statistical exploration. Misinterpreting financial indicators can lead to incorrect investment decisions, and it is crucial to conduct comprehensive research before trading.
References:
1. Whaley, R. E. (2000). “The Investor Fear Gauge”. The Journal of Portfolio Management, 26(3), 12-17.
2. Blitz, D., & van Vliet, P. (2007). “The Volatility Effect: Lower Risk Without Lower Return”. Journal of Portfolio Management, 34(1), 102-113.
3. Bhamra, H. S., & Kuehn, L. A. (2010). “The Determinants of Credit Spreads: An Empirical Analysis”. Journal of Finance, 65(3), 1041-1072.
This explanation highlights the academic and research-backed foundation of the strategy and the nuances of volatility, while cautioning against the assumption that high VIX or High Yield Spread always calls for shorting.
Simplified Gap Strategy with SMA FilterThe Simplified Gap Strategy leverages price gaps as a trading signal, focusing on their significance in market behavior. Gaps occur when the opening price of a security differs significantly from the previous closing price, often signaling potential continuation or reversal patterns.
Key Features:
Gap Threshold:
This strategy requires a minimum percentage gap (defined by the user) to qualify for trading signals.
Directional Trading:
Users can select from various gap types, including "Long Up Gap" and "Short Down Gap," allowing for tailored trading approaches.
SMA Filter:
An optional Simple Moving Average (SMA) filter helps refine trade entries based on trend direction, increasing the probability of successful trades.
Hold Duration:
Positions can be held for a user-defined duration, providing flexibility in trade management.
Statistical Significance of Gaps:
Research has shown that gaps can provide insights into future price movements. According to studies such as those by Hutton and Jiang (2008), price gaps are often followed by momentum in the direction of the gap, indicating that they can serve as reliable indicators for traders. The "Gap Theory" suggests that gaps are filled approximately 90% of the time, emphasizing their relevance in market dynamics (Nikkinen, Sahlström, & Kinnunen, 2006).
Important Note:
This strategy is designed solely for statistical analysis and should not be construed as financial advice. Users are encouraged to conduct their own research and analysis before applying this strategy in live trading scenarios.
By understanding the underlying mechanisms of price gaps and their statistical significance, traders can enhance their decision-making processes and potentially improve trading outcomes.
References:
Hutton, A. W., & Jiang, W. (2008). "Price Gaps: A Guide to Trading Gaps."
Nikkinen, J., Sahlström, P., & Kinnunen, J. (2006). "The Gaps in Financial Markets: An Empirical Study."
This description provides an overview of the strategy while emphasizing its analytical purpose and backing it with relevant academic insights.
Streak-Based Trading StrategyThe strategy outlined in the provided script is a streak-based trading strategy that focuses on analyzing winning and losing streaks. It’s important to emphasize that this strategy is not intended for actual trading but rather for statistical analysis of streak series.
How the Strategy Works
1. Parameter Definition:
• Trade Direction: Users can choose between “Long” (buy) and “Short” (sell).
• Streak Threshold: Defines how many consecutive wins or losses are needed to trigger a trade.
• Hold Duration: Specifies how many periods the position will be held.
• Doji Threshold: Determines the sensitivity for Doji candles, which indicate market uncertainty.
2. Streak Calculation:
• The script identifies Doji candles and counts winning and losing streaks based on the closing price compared to the previous closing price.
• Streak counting occurs only when no position is currently held.
3. Trade Conditions:
• If the loss streak reaches the defined threshold and the trade direction is “Long,” a buy position is opened.
• If the win streak is met and the trade direction is “Short,” a sell position is opened.
• The position is held for the specified duration.
4. Visualization:
• Winning and losing streaks are plotted as histograms to facilitate analysis.
Scientific Basis
The concept of analyzing streaks in financial markets is well-documented in behavioral economics and finance. Studies have shown that markets often exhibit momentum and trend-following behavior, meaning the likelihood of consecutive winning or losing periods can be higher than what random statistics would suggest (see, for example, “The Behavior of Stock-Market Prices” by Eugene Fama).
Additionally, empirical research indicates that investors often make decisions based on psychological factors influenced by streaks. This can lead to irrational behavior, as they may focus on past wins or losses (see “Behavioral Finance: Psychology, Decision-Making, and Markets” by R. M. F. F. Thaler).
Overall, this strategy serves as a tool for statistical analysis of streak series, providing deeper insights into market behavior and trends rather than being directly used for trading decisions.
RSI (Kernel Optimized) | Flux Charts💎 GENERAL OVERVIEW
Introducing our new KDE Optimized RSI Indicator! This indicator adds a new aspect to the well-known RSI indicator, with the help of the KDE (Kernel Density Estimation) algorithm, estimates the probability of a candlestick will be a pivot or not. For more information about the process, please check the "HOW DOES IT WORK ?" section.
Features of the new KDE Optimized RSI Indicator :
A New Approach To Pivot Detection
Customizable KDE Algorithm
Realtime RSI & KDE Dashboard
Alerts For Possible Pivots
Customizable Visuals
❓ HOW TO INTERPRET THE KDE %
The KDE % is a critical metric that reflects how closely the current RSI aligns with the KDE (Kernel Density Estimation) array. In simple terms, it represents the likelihood that the current candlestick is forming a pivot point based on historical data patterns. a low percentage suggests a lower probability of the current candlestick being a pivot point. In these cases, price action is less likely to reverse, and existing trends may continue. At moderate levels, the possibility of a pivot increases, indicating potential trend shifts or consolidations.Traders should start monitoring closely for confirmation signals. An even higher KDE % suggests a strong likelihood that the current candlestick could form a pivot point, which could lead to a reversal or significant price movement. These points often align with overbought or oversold conditions in traditional RSI analysis, making them key moments for potential trade entry or exit.
📌 HOW DOES IT WORK ?
The RSI (Relative Strength Index) is a widely used oscillator among traders. It outputs a value between 0 - 100 and gives a glimpse about the current momentum of the price action. This indicator then calculates the RSI for each candlesticks, and saves them into an array if the candlestick is a pivot. The low & high pivot RSIs' are inserted into two different arrays. Then the a KDE array is calculated for both of the low & high pivot RSI arrays. Explaining the KDE might be too much for this write-up, but for a brief explanation, here are the steps :
1. Define the necessary options for the KDE function. These are : Bandwidth & Nº Steps, Array Range (Array Max - Array Min)
2. After that, create a density range array. The array has (steps * 2 - 1) elements and they are calculated by (arrMin + i * stepCount), i being the index.
3. Then, define a kernel function. This indicator has 3 different kernel distribution modes : Uniform, Gaussian and Sigmoid
4. Then, define a temporary value for the current element of KDE array.
5. For each element E in the pivot RSI array, add "kernel(densityRange.get(i) - E, 1.0 / bandwidth)" to the temporary value.
6. Add 1.0 / arrSize * to the KDE array.
Then the prefix sum array of the KDE array is calculated. For each candlestick, the index closest to it's RSI value in the KDE array is found using binary search. Then for the low pivot KDE calculation, the sum of KDE values from found index to max index is calculated. For the high pivot KDE, the sum of 0 to found index is used. Then if high or low KDE value is greater than the activation threshold determined in the settings, a bearish or bullish arrow is plotted after bar confirmation respectively. The arrows are drawn as long as the KDE value of current candlestick is greater than the threshold. When the KDE value is out of the threshold, a less transparent arrow is drawn, indicating a possible pivot point.
🚩 UNIQUENESS
This indicator combines RSI & KDE Algorithm to get a foresight of possible pivot points. Pivot points are important entry, confirmation and exit points for traders. But to their nature, they can be only detected after more candlesticks are rendered after them. The purpose of this indicator is to alert the traders of possible pivot points using KDE algorithm right away when they are confirmed. The indicator also has a dashboard for realtime view of the current RSI & Bullish or Bearish KDE value. You can fully customize the KDE algorithm and set up alerts for pivot detection.
⚙️ SETTINGS
1. RSI Settings
RSI Length -> The amount of bars taken into account for RSI calculation.
Source -> The source value for RSI calculation.
2. Pivots
Pivot Lengths -> Pivot lengths for both high & low pivots. For example, if this value is set to 21; 21 bars before AND 21 bars after a candlestick must be higher for a candlestick to be a low pivot.
3. KDE
Activation Threshold -> This setting determines the amount of arrows shown. Higher options will result in more arrows being rendered.
Kernel -> The kernel function as explained in the upper section.
Bandwidth -> The bandwidth variable as explained in the upper section. The smoothness of the KDE function is tied to this setting.
Nº Bins -> The Nº Steps variable as explained in the upper section. It determines the precision of the KDE algorithm.
China's stock market Limit up / Limit downThe price limit system in China’s stock market is a regulatory measure implemented by the Chinese securities authorities to curb excessive speculation. It refers to the maximum allowable daily price fluctuation of a stock, which cannot exceed a certain percentage of the previous trading day's closing price. For regular stocks, the daily price movement limit is 10%. For stocks under special treatment (ST stocks), the maximum daily price movement is restricted to 5%. There is no price limit on the listing day of newly issued stocks or stocks undergoing a rights issue. This indicator highlights the K-lines (candlesticks) of stocks that have hit the upper or lower price limits with different background colors and lists the recent number of instances of limit-up and limit-down occurrences in a table format.
Info DisplayThis indicator can display the code, time period and current date of the selected commodity in real time in the upper right corner of the screen.
The display size of the 3 display fonts can be adjusted in the options.
Winning and Losing StreaksThe Pine Script indicator "Winning and Losing Streaks" tracks and visualizes the length of consecutive winning and losing streaks in a financial series, such as stock prices. Here’s a detailed description of the indicator, including the relevance of statistical analysis and streak tracking.
Indicator Description
The "Winning and Losing Streaks" indicator in Pine Script is designed to analyze and display streaks of consecutive winning and losing days in trading data. It helps traders and analysts understand the persistence of trends in price movements.
Here’s how it functions:
Streak Calculation:
Winning Streak: A series of consecutive days where the closing price is higher than the previous day's closing price.
Losing Streak: A series of consecutive days where the closing price is lower than the previous day's closing price.
Doji Candles: The indicator also considers Doji candles, where the difference between the opening and closing prices is minimal relative to the high-low range, and excludes these from being counted as winning or losing days.
Statistical Analysis:
The indicator computes the maximum and average lengths of winning and losing streaks.
It also tracks the current streak lengths and maintains arrays to store the historical streak data.
Visualization:
Histograms: Winning and losing streaks are visualized using histograms, which provide a clear graphical representation of streak lengths over time.
Relevance of Statistical Analysis and Streak Tracking
1. Statistical Significance of Streaks
Tracking winning and losing streaks has significant statistical implications for trading strategies and risk management:
Autocorrelation: Streaks in financial time series can reveal autocorrelation, where past returns influence future returns. Studies have shown that financial time series often exhibit autocorrelation, which can be used to forecast future price movements (Lo, 1991; Jegadeesh & Titman, 1993). Understanding streaks helps in identifying and leveraging these patterns.
Behavioral Finance: Streak analysis aligns with concepts from behavioral finance, such as the "hot-hand fallacy," where investors may perceive trends as more persistent than they are (Gilovich, Vallone, & Tversky, 1985). Statistical streak analysis provides a more objective view of trend persistence, helping to avoid biases.
2. Risk Management and Strategy Development
Risk Assessment: Identifying the length and frequency of losing streaks is crucial for managing risk and adjusting trading strategies. Long losing streaks can indicate potential strategy weaknesses or market regime changes, prompting a reassessment of trading rules and risk management practices (Brock, Lakonishok, & LeBaron, 1992).
Strategy Optimization: Statistical analysis of streaks can aid in optimizing trading strategies. For example, understanding the average length of winning and losing streaks can help in setting more effective stop-loss and take-profit levels, as well as in determining the optimal position sizing (Fama & French, 1993).
Scientific References:
Lo, A. W. (1991). "Long-Term Memory in Stock Market Prices." Econometrica, 59(5), 1279-1313. This paper discusses the presence of long-term memory in stock prices, which is relevant for understanding the persistence of streaks.
Jegadeesh, N., & Titman, S. (1993). "Returns to Buying Winners and Selling Losers: Implications for Stock Market Efficiency." Journal of Finance, 48(1), 65-91. This study explores momentum and reversal strategies, which are related to the concept of streaks.
Gilovich, T., Vallone, R., & Tversky, A. (1985). "The Hot Hand in Basketball: On the Misperception of Random Sequences." Cognitive Psychology, 17(3), 295-314. This paper provides insight into the psychological aspects of streaks and persistence.
Brock, W., Lakonishok, J., & LeBaron, B. (1992). "Simple Technical Trading Rules and the Stochastic Properties of Stock Returns." Journal of Finance, 47(5), 1731-1764. This research examines the effectiveness of technical trading rules, relevant for streak-based strategies.
Fama, E. F., & French, K. R. (1993). "Common Risk Factors in the Returns on Stocks and Bonds." Journal of Financial Economics, 33(1), 3-56. This paper provides a foundation for understanding risk factors and strategy performance.
By analyzing streaks, traders can gain valuable insights into market dynamics and refine their trading strategies based on empirical evidence.
FED and ECB Interest RatesFED and ECB Interest Rates Indicator
This indicator provides a clear visual representation of the Federal Reserve (FED) and European Central Bank (ECB) interest rates, offering traders and analysts a quick way to track these crucial economic metrics.
• Displays both FED (red) and ECB (blue) interest rates on a single chart
• Shows rates in basis points in the status line for precise reading
• Uses daily data for up-to-date rate information
• Features robust error handling for consistent performance
How It Works:
• Fetches FED rate from FRED and ECB rate from ECONOMICS database
• Plots rates as percentage values on the chart
• Displays rates in basis points when hovering over the chart
Use Cases:
• Monitor central bank policies and their potential impact on markets
• Compare FED and ECB rate trends over time
• Analyze correlation between interest rates and asset prices
• Assist in fundamental analysis for forex, equities, and fixed income trading
Note:
This indicator is for informational purposes only. Always combine this data with other forms of analysis and stay informed about central bank announcements and economic events.
Enhance your trading strategy with real-time insights into two of the world's most influential interest rates!
Currency Futures StatisticsThe "Currency Futures Statistics" indicator provides comprehensive insights into the performance and characteristics of various currency futures. This indicator is crucial for portfolio management as it combines multiple metrics that are instrumental in evaluating currency futures' risk and return profiles.
Metrics Included:
Historical Volatility:
Definition: Historical volatility measures the standard deviation of returns over a specified period, scaled to an annual basis.
Importance: High volatility indicates greater price fluctuations, which translates to higher risk. Investors and portfolio managers use volatility to gauge the stability of a currency future and to make informed decisions about risk management and position sizing (Hull, J. C. (2017). Options, Futures, and Other Derivatives).
Open Interest:
Definition: Open interest represents the total number of outstanding futures contracts that are held by market participants.
Importance: High open interest often signifies liquidity in the market, meaning that entering and exiting positions is less likely to impact the price significantly. It also reflects market sentiment and the degree of participation in the futures market (Black, F., & Scholes, M. (1973). The Pricing of Options and Corporate Liabilities).
Year-over-Year (YoY) Performance:
Definition: YoY performance calculates the percentage change in the futures contract's price compared to the same week from the previous year.
Importance: This metric provides insight into the long-term trend and relative performance of a currency future. Positive YoY performance suggests strengthening trends, while negative values indicate weakening trends (Fama, E. F. (1991). Efficient Capital Markets: II).
200-Day Simple Moving Average (SMA) Position:
Definition: This metric indicates whether the current price of the currency future is above or below its 200-day simple moving average.
Importance: The 200-day SMA is a widely used trend indicator. If the price is above the SMA, it suggests a bullish trend, while being below indicates a bearish trend. This information is vital for trend-following strategies and can help in making buy or sell decisions (Bollinger, J. (2001). Bollinger on Bollinger Bands).
Why These Metrics are Important for Portfolio Management:
Risk Assessment: Historical volatility and open interest provide essential information for assessing the risk associated with currency futures. Understanding the volatility helps in estimating potential price swings, which is crucial for managing risk and setting appropriate stop-loss levels.
Liquidity and Market Participation: Open interest is a critical indicator of market liquidity. Higher open interest usually means tighter bid-ask spreads and better liquidity, which facilitates smoother trading and better execution of trades.
Trend Analysis: YoY performance and the SMA position help in analyzing long-term trends. This analysis is crucial for making strategic investment decisions and adjusting the portfolio based on changing market conditions.
Informed Decision-Making: Combining these metrics allows for a holistic view of the currency futures market. This comprehensive view helps in making informed decisions, balancing risks and returns, and optimizing the portfolio to align with investment goals.
In summary, the "Currency Futures Statistics" indicator equips investors and portfolio managers with valuable data points that are essential for effective risk management, liquidity assessment, trend analysis, and overall portfolio optimization.
Larry Conners Vix Reversal II Strategy (approx.)This Pine Script™ strategy is a modified version of the original Larry Connors VIX Reversal II Strategy, designed for short-term trading in market indices like the S&P 500. The strategy utilizes the Relative Strength Index (RSI) of the VIX (Volatility Index) to identify potential overbought or oversold market conditions. The logic is based on the assumption that extreme levels of market volatility often precede reversals in price.
How the Strategy Works
The strategy calculates the RSI of the VIX using a 25-period lookback window. The RSI is a momentum oscillator that measures the speed and change of price movements. It ranges from 0 to 100 and is often used to identify overbought and oversold conditions in assets.
Overbought Signal: When the RSI of the VIX rises above 61, it signals a potential overbought condition in the market. The strategy looks for a RSI downtick (i.e., when RSI starts to fall after reaching this level) as a trigger to enter a long position.
Oversold Signal: Conversely, when the RSI of the VIX drops below 42, the market is considered oversold. A RSI uptick (i.e., when RSI starts to rise after hitting this level) serves as a signal to enter a short position.
The strategy holds the position for a minimum of 7 days and a maximum of 12 days, after which it exits automatically.
Larry Connors: Background
Larry Connors is a prominent figure in quantitative trading, specializing in short-term market strategies. He is the co-author of several influential books on trading, such as Street Smarts (1995), co-written with Linda Raschke, and How Markets Really Work. Connors' work focuses on developing rules-based systems using volatility indicators like the VIX and oscillators such as RSI to exploit mean-reversion patterns in financial markets.
Risks of the Strategy
While the Larry Connors VIX Reversal II Strategy can capture reversals in volatile market environments, it also carries significant risks:
Over-Optimization: This modified version adjusts RSI levels and holding periods to fit recent market data. If market conditions change, the strategy might no longer be effective, leading to false signals.
Drawdowns in Trending Markets: This is a mean-reversion strategy, designed to profit when markets return to a previous mean. However, in strongly trending markets, especially during extended bull or bear phases, the strategy might generate losses due to early entries or exits.
Volatility Risk: Since this strategy is linked to the VIX, an instrument that reflects market volatility, large spikes in volatility can lead to unexpected, fast-moving market conditions, potentially leading to larger-than-expected losses.
Scientific Literature and Supporting Research
The use of RSI and VIX in trading strategies has been widely discussed in academic research. RSI is one of the most studied momentum oscillators, and numerous studies show that it can capture mean-reversion effects in various markets, including equities and derivatives.
Wong et al. (2003) investigated the effectiveness of technical trading rules such as RSI, finding that it has predictive power in certain market conditions, particularly in mean-reverting markets .
The VIX, often referred to as the “fear index,” reflects market expectations of volatility and has been a focal point in research exploring volatility-based strategies. Whaley (2000) extensively reviewed the predictive power of VIX, noting that extreme VIX readings often correlate with turning points in the stock market .
Modified Version of Original Strategy
This script is a modified version of Larry Connors' original VIX Reversal II strategy. The key differences include:
Adjusted RSI period to 25 (instead of 2 or 4 commonly used in Connors’ other work).
Overbought and oversold levels modified to 61 and 42, respectively.
Specific holding period (7 to 12 days) is predefined to reduce holding risk.
These modifications aim to adapt the strategy to different market environments, potentially enhancing performance under specific volatility conditions. However, as with any system, constant evaluation and testing in live markets are crucial.
References
Wong, W. K., Manzur, M., & Chew, B. K. (2003). How rewarding is technical analysis? Evidence from Singapore stock market. Applied Financial Economics, 13(7), 543-551.
Whaley, R. E. (2000). The investor fear gauge. Journal of Portfolio Management, 26(3), 12-17.
Global Liquidity Index and DEMA1001. Global Liquidity Index:
The code calculates global liquidity from economic data from multiple countries and regions. Specifically, it aggregates money supply data from major economies such as the United States, Europe, China, and Japan, and sums and adjusts them to get a global liquidity index.
This index is calculated by summing data from different sources and subtracting the impact of some financial instruments (such as reverse repurchase agreements, etc.), and then converting the result into a number in trillions. This can help analyze the liquidity conditions in global money markets.
2. ROC SMA (Simple Moving Average of Rate of Change):
The code calculates the rate of change (ROC) of the global liquidity index, which is a way to measure the speed of change of the index.
Then, a simple moving average (SMA) is applied to the rate of change, which helps smooth the data and identify trends.
The ROC SMA curve is displayed in yellow to help users observe the trend of liquidity changes.
3. DEMA (Double Exponential Moving Average):
DEMA is a more complex moving average that attempts to reduce the lag of the moving average and provide a more sensitive trend response.
The calculation method is to first calculate a standard exponential moving average (EMA), then calculate the EMA of this EMA, and use these two results to calculate DEMA.
The code allows users to set the period length of DEMA (default is 100), which can adjust the speed of DEMA's response to price changes.
The DEMA curve is displayed in blue, helping users to more accurately capture the trends and changes of global liquidity indicators.
Korean Exchange Relative Volume BarchartKorean Exchange Relative Volume Barchart
The Korean Exchange Relative Volume Barchart indicator compares the trading volume of a cryptocurrency on any symbol with the combined volumes of major Korean exchanges, Upbit and Bithumb. This tool helps traders understand regional trading activities, offering insights into market sentiment influenced by Korean markets.
For example 0.5 would indicate that the Korean exchanges are doing 50% of the volume of the selected symbol.
Features:
Exchange Selection: Include or exclude Upbit and Bithumb in the comparison.
Automatic Symbol Mapping: Automatically maps the current chart's symbol to equivalent symbols on Upbit and Bithumb.
Stacked Bar Chart Visualization: Plots a stacked bar chart showing the relative volume contributions of Binance, Upbit, and Bithumb.
Usage:
Add the Indicator: Apply it to a cryptocurrency chart on TradingView.
Configure Settings: Toggle inclusion of Upbit and Bithumb in the settings.
Interpret the Chart: The stacked bar chart displays the proportion of trading volumes from each exchange.
Notes:
Symbol Compatibility: Ensure the cryptocurrency is listed on the Korean exchanges for accurate comparison.
Data Accuracy: Volumes are compared in the same base currency (e.g., BTC), so no exchange rate conversion is necessary.
Enhance your trading analysis by understanding the influence of Korean exchanges on cryptocurrency volumes with the Korean Exchange Volume Comparison indicator.
Stationarity Test: Dickey-Fuller & KPSS [Pinescriptlabs]
📊 Kwiatkowski-Phillips-Schmidt-Shin Model Indicator & Dickey-Fuller Test 📈
This algorithm performs two statistical tests on the price spread between two selected instruments: the first from the current chart and the second determined in the settings. The purpose is to determine if their relationship is stationary. It then uses this information to generate **visual signals** based on how far the current relationship deviates from its historical average.
⚙️ Key Components:
• 🧪 ADF Test (Augmented Dickey-Fuller):** Checks if the spread between the two instruments is stationary.
• 🔬 KPSS Test (Kwiatkowski-Phillips-Schmidt-Shin):** Another test for stationarity, complementing the ADF test.
• 📏 Z-Score Calculation:** Measures how many standard deviations the current spread is from its historical mean.
• 📊 Dynamic Threshold:** Adjusts the trading signal threshold based on recent market volatility.
🔍 What the Values Mean:
The indicator displays several key values in a table:
• 📈 ADF Stationarity:** Shows "Stationary" or "Non-Stationary" based on the ADF test result.
• 📉 KPSS Stationarity:** Shows "Stationary" or "Non-Stationary" based on the KPSS test result.
• 📏 Current Z-Score:** The current Z-score of the spread.
• 🔗 Hedge Ratio:** The relationship coefficient between the two instruments.
• 🌐 Market State:** Describes the current market condition based on the Z-score.
📊 How to Interpret the Chart:
• The main chart displays the Z-score of the spread over time.
• The green and red lines represent the upper and lower thresholds for trading signals.
• The area between the **Z-score** and the thresholds is filled when a trading signal is active.
• Additional charts show the **statistics of the ADF and KPSS tests** and their critical values.
**📉 Practical Example: NVIDIA Corporation (NVDA)**
Looking at the chart for **NVIDIA Corporation (NVDA)**, we can see how the indicator applies in a real case:
1. **Main Chart (Top):**
• Shows the **historical price** of NVIDIA on a weekly scale.
• A general **uptrend** is observed with periods of consolidation.
2. **KPSS & ADF Indicator (Bottom):**
• The lower chart shows the KPSS & ADF Model indicator applied to NVIDIA.
• The **green line** represents the Z-score of the spread.
• The **green shaded areas** indicate periods where the Z-score exceeded the thresholds, generating trading signals.
3. **📋 Current Values in the Table:**
• **ADF Stationarity:** Non-Stationary
• **KPSS Stationarity:** Non-Stationary
• **Current Z-Score:** 3.45
• **Hedge Ratio:** -164.8557
• **Market State:** Moderate Volatility
4. **🔍 Interpretation:**
• A Z-score of **3.45** suggests that NVIDIA’s price is significantly above its historical average relative to **EURUSD**.
• Both the **ADF** and **KPSS** tests indicate **non-stationarity**, suggesting **caution** when using mean reversion signals at this moment.
• The market state "Moderate Volatility" indicates noticeable deviation, but not extreme.
---
**💡 Usage:**
• **When Both Tests Show Stationarity:**
• **🔼 If Z-score > Upper Threshold:** Consider **buying the first instrument** and **selling the second**.
• **🔽 If Z-score < Lower Threshold:** Consider **selling the first instrument** and **buying the second**.
• **When Either Test Shows Non-Stationarity:**
• Wait for the relationship to become **stationary** before trading.
• **Market State:**
• Use this information to evaluate **general market conditions** and adjust your trading strategy accordingly.
**Mirror Comparison of the Same as Symbol 2 🔄📊**
**📊 Table Values:**
• **Extreme Volatility Threshold:** This value is displayed when the **Z-score** exceeds **100%**, indicating **extreme deviation**. It signals a potential **trading opportunity**, as the spread has reached unusually high or low levels, suggesting a **reversion or correction** in the market.
• **Mean Reversion Threshold:** Appears when the **Z-score** begins returning towards the mean after a period of **high or extreme volatility**. It indicates that the spread between the assets is returning to normal levels, suggesting a phase of **stabilization**.
• **Neutral Zone:** Displayed when the **Z-score** is near **zero**, signaling that the spread between assets is within expected limits. This indicates a **balanced market** with no significant volatility or clear trading opportunities.
• **Low Volatility Threshold:** Appears when the **Z-score** is below **70%** of the dynamic threshold, reflecting a period of **low volatility** and market stability, indicating fewer trading opportunities.
Español:
📊 Indicador del Modelo Kwiatkowski-Phillips-Schmidt-Shin & Prueba de Dickey-Fuller 📈
Este algoritmo realiza dos pruebas estadísticas sobre la diferencia de precios (spread) entre dos instrumentos seleccionados: el primero en el gráfico actual y el segundo determinado en la configuración. El objetivo es determinar si su relación es estacionaria. Luego utiliza esta información para generar señales visuales basadas en cuánto se desvía la relación actual de su promedio histórico.
⚙️ Componentes Clave:
• 🧪 Prueba ADF (Dickey-Fuller Aumentada): Verifica si el spread entre los dos instrumentos es estacionario.
• 🔬 Prueba KPSS (Kwiatkowski-Phillips-Schmidt-Shin): Otra prueba para la estacionariedad, complementando la prueba ADF.
• 📏 Cálculo del Z-Score: Mide cuántas desviaciones estándar se encuentra el spread actual de su media histórica.
• 📊 Umbral Dinámico: Ajusta el umbral de la señal de trading en función de la volatilidad reciente del mercado.
🔍 Qué Significan los Valores:
El indicador muestra varios valores clave en una tabla:
• 📈 Estacionariedad ADF: Muestra "Estacionario" o "No Estacionario" basado en el resultado de la prueba ADF.
• 📉 Estacionariedad KPSS: Muestra "Estacionario" o "No Estacionario" basado en el resultado de la prueba KPSS.
• 📏 Z-Score Actual: El Z-score actual del spread.
• 🔗 Ratio de Cobertura: El coeficiente de relación entre los dos instrumentos.
• 🌐 Estado del Mercado: Describe la condición actual del mercado basado en el Z-score.
📊 Cómo Interpretar el Gráfico:
• El gráfico principal muestra el Z-score del spread a lo largo del tiempo.
• Las líneas verdes y rojas representan los umbrales superior e inferior para las señales de trading.
• El área entre el Z-score y los umbrales se llena cuando una señal de trading está activa.
• Los gráficos adicionales muestran las estadísticas de las pruebas ADF y KPSS y sus valores críticos.
📉 Ejemplo Práctico: NVIDIA Corporation (NVDA)
Observando el gráfico para NVIDIA Corporation (NVDA), podemos ver cómo se aplica el indicador en un caso real:
Gráfico Principal (Superior): • Muestra el precio histórico de NVIDIA en escala semanal. • Se observa una tendencia alcista general con períodos de consolidación.
Indicador KPSS & ADF (Inferior): • El gráfico inferior muestra el indicador Modelo KPSS & ADF aplicado a NVIDIA. • La línea verde representa el Z-score del spread. • Las áreas sombreadas en verde indican períodos donde el Z-score superó los umbrales, generando señales de trading.
📋 Valores Actuales en la Tabla: • Estacionariedad ADF: No Estacionario • Estacionariedad KPSS: No Estacionario • Z-Score Actual: 3.45 • Ratio de Cobertura: -164.8557 • Estado del Mercado: Volatilidad Moderada
🔍 Interpretación: • Un Z-score de 3.45 sugiere que el precio de NVIDIA está significativamente por encima de su promedio histórico en relación con EURUSD. • Tanto la prueba ADF como la KPSS indican no estacionariedad, lo que sugiere precaución al usar señales de reversión a la media en este momento. • El estado del mercado "Volatilidad Moderada" indica una desviación notable, pero no extrema.
💡 Uso:
• Cuando Ambas Pruebas Muestran Estacionariedad:
• 🔼 Si Z-score > Umbral Superior: Considera comprar el primer instrumento y vender el segundo.
• 🔽 Si Z-score < Umbral Inferior: Considera vender el primer instrumento y comprar el segundo.
• Cuando Alguna Prueba Muestra No Estacionariedad:
• Espera a que la relación se vuelva estacionaria antes de operar.
• Estado del Mercado:
• Usa esta información para evaluar las condiciones generales del mercado y ajustar tu estrategia de trading en consecuencia.
Comparativo en Espejo del Mismo Como Símbolo 2 🔄📊
📊 Valores de la Tabla:
• Umbral de Volatilidad Extrema: Este valor se muestra cuando el Z-score supera el 100%, indicando desviación extrema. Señala una posible oportunidad de trading, ya que el spread entre los activos ha alcanzado niveles inusualmente altos o bajos, lo que podría indicar una reversión o corrección en el mercado.
• Umbral de Reversión a la Media: Aparece cuando el Z-score comienza a volver hacia la media tras un período de alta o extrema volatilidad. Indica que el spread entre los activos está regresando a niveles normales, sugiriendo una fase de estabilización.
• Zona Neutral: Se muestra cuando el Z-score está cerca de cero, señalando que el spread entre activos está dentro de lo esperado. Esto indica un mercado equilibrado con ninguna volatilidad significativa ni oportunidades claras de trading.
• Umbral de Baja Volatilidad: Aparece cuando el Z-score está por debajo del 70% del umbral dinámico, reflejando un período de baja volatilidad y estabilidad del mercado, indicando menos oportunidades de trading.
Correlation with AveragesThe "Correlation with Averages" indicator is designed to visualize and analyze the correlation between a selected asset's price and a base symbol's price, such as the S&P 500 (SPY). This indicator allows users to evaluate how closely an asset’s price movements align with those of the base symbol over various time periods, providing insights into market trends and potential portfolio adjustments.
Key Features:
Base Symbol and Correlation Period:
Users can specify the base symbol (default is SPY) and the period for correlation measurement (default is 252 trading days, approximating one year).
Correlation Calculation:
The indicator computes the correlation between the asset’s closing price and the base symbol’s closing price for the defined period.
Visualization:
The correlation value is plotted on the chart, with conditional background colors indicating the strength and direction of the correlation:
Red for negative correlation (below -0.5)
Green for positive correlation (above 0.5)
Yellow for neutral correlation (between -0.5 and 0.5)
Average Correlation Over Time:
Average correlations are calculated and displayed for various periods: one week, one month, one year, and five years.
A table on the chart provides dynamic updates of these average values with color-coded backgrounds to indicate correlation strength.
The Role of Correlation in Portfolio Management
Correlation is a crucial concept in portfolio management because it measures the degree to which two securities move in relation to each other. Understanding correlation helps investors construct diversified portfolios that balance risk and return. Here's why correlation is important:
Diversification:
By including assets with low or negative correlation in a portfolio, investors can reduce overall portfolio volatility and risk. For instance, if one asset is negatively correlated with another, when one performs poorly, the other may perform well, thus smoothing the overall returns.
Risk Management:
Correlation analysis helps in identifying the potential impact of one asset’s performance on the entire portfolio. Assets with high correlation can lead to concentrated risk, while those with low correlation offer better risk management.
Performance Analysis:
Correlation measures the degree to which asset returns move together. This can inform strategic decisions, such as whether to adjust positions based on expected market conditions.
Scientific References
Markowitz, H. M. (1952). "Portfolio Selection." Journal of Finance, 7(1), 77-91.
This foundational paper introduced Modern Portfolio Theory, highlighting the importance of diversification and correlation in reducing portfolio risk.
Jorion, P. (2007). Financial Risk Manager Handbook. Wiley.
This handbook provides an in-depth exploration of risk management techniques, including the use of correlation in portfolio management.
Elton, E. J., Gruber, M. J., Brown, S. J., & Goetzmann, W. N. (2014). Modern Portfolio Theory and Investment Analysis. Wiley.
This book elaborates on the concepts of correlation and diversification, offering practical insights into portfolio construction and risk management.
By utilizing the "Correlation with Averages" indicator, traders and portfolio managers can make informed decisions based on the relationship between asset prices and the base symbol, ultimately enhancing their investment strategies.
Bull/Bear Ratio By Month Table [MsF]Japanese below / 日本語説明は英文の後にあります。
-------------------------
This is an indicator that shows monthly bull-bear ratio in a table.
By specifying the start year and end year, the ratio will be calculated and showed based on the number of bullish and bearish lines in the monthly bar. It allows you to analyze the trend of each symbol and month (bullish / bearish). Up to 10 symbols can be specified.
You can take monthly bull-bear ratio for the past 10 or 20 years on the web, but with this indicator, you can narrow it down to the period in which you want to see the symbols you want to see. It is very convenient because you can take statistics at will.
Furthermore, if the specified ratio is exceeded, the font color can be changed to any color, making it very easy to read.
=== Parameter description ===
- From … Year of start of aggregation
- To … Year of end of aggregation
- Row Background Color … Row title background color
- Col Background Color … Column title background color
- Base Text Color … Text color
- Background Color … Background Color
- Border Color … Border Color
- Location … Location
- Text Size … Text Size
- Highlight Threshold … Ratio threshold, and color
- Display in counter? … Check if you want to show the number of times instead of the ratio
-------------------------
月別陰陽確率をテーブル表示するインジケータです。
開始年から終了年を指定することで、月足における陽線数および陰線数を元に確率を計算して表示します。
この機能により各シンボルおよび各月の特徴(買われやすい/売られやすい)を認識することができアノマリー分析が可能です。
シンボルは10個まで指定可能です。
過去10年、20年の月別陰陽確率は、Web上でよく見かけますが、このインジケータでは見たいシンボルを見たい期間に絞って、
自由自在に統計を取ることができるため大変便利です。
なお、指定した確率を上回った場合、文字色を任意の色に変更することができるため、大変見やすくなっています。
=== パラメータの説明 ===
- From … 集計開始年
- To … 集計終了年
- Row Background Color … 行タイトルの背景色
- Col Background Color … 列タイトルの背景色
- Base Text Color … テキストカラー
- Background Color … 背景色
- Border Color … 区切り線の色
- Location … 配置
- Text Size … テキストサイズ
- Highlight Threshold … 色変更する確率の閾値、および色
- Display in counter? … 確率ではなく回数表示する場合はチェックする
Solar System in 3D [Astro Tool w/ Zodiac]Hello Traders and Developers,
I am excited to announce my latest Open Source indicator. At the core, this is a demonstration of PineScript’s capabilities in Rendering 3D Animations, while at the same time being a practical tool for Financial Astrologists.
This 3D Engine dynamically renders all the major celestial bodies with their individual orbits, rotation speeds, polar inclinations and astrological aspects, all while maintaining accurate spatial relationships and perspective.
This is a Geocentric model of the solar system (viewed from the perspective of Earth), since that is what most Astrologists use. Thanks to the AstroLib Library created by @BarefootJoey, this model uses the real coordinates of cosmic bodies for every timestamp.
This script truly comes to life when using the “Bar Replay” mode in TradingView, as you can observe the relationships between planets and price action as time progresses, with the full animation capabilities as mentioned above.
In addition to what I have described, this indicator also displays the orbital trajectories for each cosmic body, and has labels for everything. I have also added the ability to hover on all the labels, and see a short description of what they imply in Astrology.
Optional Planetary Aspect Computation
This indicator supports all the Major Planetary Aspects, with an accuracy defined by the user (1° by default).
Conjunction: 0° Alignment. This draws a RED line starting from the center, and going through both planets.
Sextile: 60° Alignment. This draws three YELLOW lines, connecting the planets to each other and to the center.
Square: 90° Alignment. This draws three BLUE lines, connecting the planets to each other and to the center.
Trine: 120° Alignment. This draws three PURPLE lines, connecting the planets to each other and to the center.
Opposition: 180° Alignment. This draws a GREEN line starting from one planet, passing through the center and ending on the second planet.
The below image depicts a Top-Down view of the system, with the Moon in Opposition to Venus and with Mars in Square with Neptune .
Retrograde Computation
This indicator also displays when a planet enters Retrograde (Apparent Backward Motion) by making its orbital trajectory dashed and the planet name getting a red background.
The image below displays an example of Jupiter, Saturn, Neptune and Pluto in Retrograde Motion, from the camera perspective of a 65 degree inclination.
Optional Zodiac Computation (Tropical and Sidereal)
Zodiac represents the relatively stationary star formations that rest along the ecliptic plane, with planets transitioning from one to the next, each with a 30° separation (making 12 in total). I have implemented the option to switch between Tropical mode (where these stars were 2,000 years ago) and Sidereal (where these stars are today).
The image below displays the Zodiac labels with clear lines denoting where each planet falls into.
While this indicator is deployed in a separate pane, it is trivial to transfer it onto your price chart, just by clicking and dragging the graphics. After that, you can adjust the visuals by dragging the scale on the side, or optimizing model settings. You can also drag the model above or below the price, as shown in the following image:
Of course, there are a lot of options to customize this planetary model to your tastes and analytical needs. Aside from visual changes for the labels, colors or resolution you can also disable certain planets that don’t meet your needs as shown below:
Once can also infer the current lunar phases using the Aspects between the Sun and Moon. When the Moon is Opposite the Sun that is a Full Moon, while when they are Conjunct that is a New Moon (and sometimes Eclipse).
—---------------------------------------------------------------------------
I have made this indicator open source to help PineScript programmers understand how to approach 3D graphics rendering, enabling them to develop ever more capable scripts and continuously push the boundaries of what's possible on TradingView.
The code is well documented with comments and has a clear naming convention for functions and variables, to aid developers understand how everything operates.
For financial astrologists, this indicator offers a new way to visualize and correlate planetary movements, adding depth and ease to astrological market analysis.
Regards,
Hawk
[ALGOA+] Markov Chains Library by @metacamaleoLibrary "MarkovChains"
Markov Chains library by @metacamaleo. Created in 09/08/2024.
This library provides tools to calculate and visualize Markov Chain-based transition matrices and probabilities. This library supports two primary algorithms: a rolling window Markov Chain and a conditional Markov Chain (which operates based on specified conditions). The key concepts used include Markov Chain states, transition matrices, and future state probabilities based on past market conditions or indicators.
Key functions:
- `mc_rw()`: Builds a transition matrix using a rolling window Markov Chain, calculating probabilities based on a fixed length of historical data.
- `mc_cond()`: Builds a conditional Markov Chain transition matrix, calculating probabilities based on the current market condition or indicator state.
Basically, you will just need to use the above functions on your script to default outputs and displays.
Exported UDTs include:
- s_map: An UDT variable used to store a map with dummy states, i.e., if possible states are bullish, bearish, and neutral, and current is bullish, it will be stored
in a map with following keys and values: "bullish", 1; "bearish", 0; and "neutral", 0. You will only use it to customize your own script, otherwise, it´s only for internal use.
- mc_states: This UDT variable stores user inputs, calculations and MC outputs. As the above, you don´t need to use it, but you may get features to customize your own script.
For example, you may use mc.tm to get the transition matrix, or the prob map to customize the display. As you see, functions are all based on mc_states UDT. The s_map UDT is used within mc_states´s s array.
Optional exported functions include:
- `mc_table()`: Displays the transition matrix in a table format on the chart for easy visualization of the probabilities.
- `display_list()`: Displays a map (or array) of string and float/int values in a table format, used for showing transition counts or probabilities.
- `mc_prob()`: Calculates and displays probabilities for a given number of future bars based on the current state in the Markov Chain.
- `mc_all_states_prob()`: Calculates probabilities for all states for future bars, considering all possible transitions.
The above functions may be used to customize your outputs. Use the returned variable mc_states from mc_rw() and mc_cond() to display each of its matrix, maps or arrays using mc_table() (for matrices) and display_list() (for maps and arrays) if you desire to debug or track the calculation process.
See the examples in the end of this script.
Have good trading days!
Best regards,
@metacamaleo
-----------------------------
KEY FUNCTIONS
mc_rw(state, length, states, pred_length, show_table, show_prob, table_position, prob_position, font_size)
Builds the transition matrix for a rolling window Markov Chain.
Parameters:
state (string) : The current state of the market or system.
length (int) : The rolling window size.
states (array) : Array of strings representing the possible states in the Markov Chain.
pred_length (int) : The number of bars to predict into the future.
show_table (bool) : Boolean to show or hide the transition matrix table.
show_prob (bool) : Boolean to show or hide the probability table.
table_position (string) : Position of the transition matrix table on the chart.
prob_position (string) : Position of the probability list on the chart.
font_size (string) : Size of the table font.
Returns: The transition matrix and probabilities for future states.
mc_cond(state, condition, states, pred_length, show_table, show_prob, table_position, prob_position, font_size)
Builds the transition matrix for conditional Markov Chains.
Parameters:
state (string) : The current state of the market or system.
condition (string) : A string representing the condition.
states (array) : Array of strings representing the possible states in the Markov Chain.
pred_length (int) : The number of bars to predict into the future.
show_table (bool) : Boolean to show or hide the transition matrix table.
show_prob (bool) : Boolean to show or hide the probability table.
table_position (string) : Position of the transition matrix table on the chart.
prob_position (string) : Position of the probability list on the chart.
font_size (string) : Size of the table font.
Returns: The transition matrix and probabilities for future states based on the HMM.
Ema Z-score | viResearchEma Z-score | viResearch
Conceptual Foundation and Innovation
The "Ema Z-score" indicator introduces a novel method of analyzing price deviations from the mean by combining the Exponential Moving Average (EMA) with a Z-score calculation. The Z-score is a statistical measure that quantifies how far a value deviates from the mean in terms of standard deviations. By applying the Z-score to an EMA, this indicator provides traders with insights into the strength and momentum of price movements relative to a smoothed average. This enables better detection of overbought and oversold conditions, as well as potential trend reversals.
The use of the Z-score helps filter out noise and provides more robust signals by highlighting extreme deviations from the mean, allowing traders to make more informed decisions in both trending and ranging markets.
Technical Composition and Calculation
The "Ema Z-score" script consists of two main components: the Exponential Moving Average (EMA) and the Z-score calculation. The EMA is calculated over a user-defined length, smoothing price movements to provide a clearer trend line. The Z-score is then derived by measuring the deviation of the current EMA value from the mean of the EMA over a lookback period, divided by the standard deviation of the EMA during that same period.
For the Z-score calculation, the script first computes the mean EMA over the lookback period using the ta.ema function. It then calculates the standard deviation of the EMA over the same period using the ta.stdev function. The Z-score is determined by subtracting the mean EMA from the current EMA value and dividing by the standard deviation, producing a normalized measure of deviation from the average.
Features and User Inputs
The "Ema Z-score" script offers several customizable inputs that allow traders to adjust the indicator according to their strategies. The EMA Length controls the smoothing period of the EMA, while the Lookback Period defines how far back the script looks when calculating the mean and standard deviation for the Z-score. Customizable thresholds allow traders to define when the Z-score signals potential uptrends or downtrends, based on their chosen levels of deviation.
Practical Applications
The "Ema Z-score" indicator is designed for traders who want to better understand price deviations from the mean and use those insights to identify potential trading opportunities. This tool is particularly effective for:
Identifying Overbought and Oversold Conditions: The Z-score provides a quantitative measure of how far the price has deviated from the mean, helping traders spot extreme conditions that could lead to reversals. Detecting Trend Reversals: By monitoring when the Z-score crosses certain thresholds, traders can identify potential trend reversals early and adjust their positions accordingly. Confirming Trend Strength: The Z-score can help confirm whether a price move is backed by momentum or is likely to revert to the mean, providing additional context for trade entries and exits.
Advantages and Strategic Value
The "Ema Z-score" script offers a significant advantage by combining the smoothing effect of the EMA with the precision of Z-score analysis. This approach reduces the impact of market noise while highlighting meaningful deviations from the norm. The ability to quantify deviations in terms of standard deviations gives traders a statistical edge in identifying overbought or oversold conditions and potential trend shifts. This makes the "Ema Z-score" an effective tool for both trend-following and contrarian strategies.
Alerts and Visual Cues
The script includes alert conditions to notify traders of key Z-score threshold crossings. The "Ema Z-score Long" alert is triggered when the Z-score exceeds the upper threshold, signaling a potential upward trend. Conversely, the "Ema Z-score Short" alert signals a possible downward trend when the Z-score falls below the lower threshold. Visual cues such as color changes in the bar chart and Z-score plot help traders easily identify these conditions on the chart.
Summary and Usage Tips
The "Ema Z-score | viResearch" indicator offers a unique combination of EMA smoothing and Z-score analysis, giving traders a statistical measure of price deviations and improving their ability to detect overbought or oversold conditions, trend reversals, and trend confirmations. By incorporating this script into your trading strategy, you can better quantify price extremes and make more informed decisions in both volatile and stable markets. Whether you're focused on spotting early reversals or confirming ongoing trends, the "Ema Z-score" provides a reliable and customizable solution.
Note: Backtests are based on past results and are not indicative of future performance.
Forex Macro Metrics [MacroGlide]"Forex Macro Metrics " is a powerful tool for analyzing macroeconomic metrics, designed to help traders make more informed decisions in the forex market. This indicator displays key economic indicators such as interest rates, money supply (M1 and M2), unemployment rate, and government debt for various currencies and their pairs, allowing users to assess the macroeconomic differences between the base and quote currencies.
Key Features:
• Interest Rates Display: Includes interest rates for major world currencies with the ability to show the differential between the base and quote currencies.
• Money Supply Analysis (M1 and M2): Displays the money supply for both the base and quote currencies, including differential calculations.
• Unemployment Rate: Compares the unemployment rates between currencies, showing the differences on the chart.
• Government Debt: Shows government debt levels for the base and quote currencies with differential calculations.
• Customizable Options: Enable/disable specific metrics and adjust colors for better visual clarity.
How to Use:
• Select a Currency Pair: Apply the indicator to your chart and choose the desired currency pair. The indicator will automatically load the relevant data for the base and quote currencies.
• Adjust Display Settings: Use the indicator settings to enable or disable specific metrics and their differentials.
• Analyze the Data: Compare the economic conditions of the two currencies through the charts and identify potential trading opportunities based on macroeconomic differences.
Methodology:
The indicator uses economic data available through TradingView tickers to calculate the values of the base and quote currencies. Differentials are calculated by subtracting the values of the quote currency from the base currency, allowing for a visual assessment of their differences. The displayed data includes historical changes, helping to identify trends and potential reversal points.
Originality and Usefulness:
"Forex Macro Metrics " is a unique tool that combines several key macroeconomic indicators into one comprehensive indicator. This simplifies the analysis process for traders looking to understand the fundamental differences between currencies. Using this approach provides an advantage in assessing long-term trends and potential shifts in currency pairs driven by changes in macroeconomic conditions.
Charts:
The indicator displays data in the form of lines and areas on the chart, with interest rates shown as lines for the base and quote currencies, accompanied by an area representing the differential. For money supply (M1 and M2), lines are drawn for each currency, with areas highlighting the differences. Similarly, the unemployment rate and government debt are displayed with clear visual separation of the data and their differentials, making it easy to compare and analyze the macroeconomic conditions of the currencies involved.
Enjoy the game!
Kalman PSaR [BackQuant]Kalman PSaR
Overview and Innovation
The Kalman PSaR combines the well-known Parabolic SAR (PSaR) with the advanced smoothing capabilities of the Kalman Filter . This innovative tool aims to enhance the traditional PSaR by integrating Kalman filtering, which reduces noise and improves trend detection. The Kalman PSaR adapts dynamically to price movements, making it a highly effective indicator for spotting trend shifts while minimizing the impact of false signals caused by market volatility.
Please Find the Basic Kalman Here:
Kalman Filter Dynamics
The Kalman Filter is a powerful algorithm for estimating the true value of a system amidst noisy data. In the Kalman PSaR, this filter is applied to the high, low, and closing prices, resulting in a smoother and more accurate representation of price action. The filter’s parameters—process noise and measurement noise—are customizable, allowing traders to fine-tune the sensitivity of the indicator to market conditions. By reducing the impact of noise, the Kalman-filtered PSaR offers clearer signals for identifying trend reversals and continuations.
Enhanced PSaR Calculation
The traditional Parabolic SAR is a popular trend-following indicator that highlights potential entry and exit points based on price acceleration. In the Kalman PSaR, this calculation is enhanced by the Kalman-filtered prices, providing a smoother and more reliable signal. The indicator continuously updates based on the acceleration factor and max step values, while the Kalman filter ensures that sudden price spikes or market noise do not trigger false signals.
Min Step and Max Step: These settings control the sensitivity of the PSaR. The Min Step sets the initial acceleration factor, while the Max Step limits how fast the PSaR adapts to price changes, helping traders fine-tune the indicator’s responsiveness.
Optional Smoothing Techniques To further enhance the signal clarity, the Kalman PSaR includes an optional smoothing feature. Traders can choose from various smoothing methods, such as SMA, Hull, EMA, WMA, TEMA, and more, to reduce short-term fluctuations and emphasize the underlying trend. The smoothing period is customizable, allowing traders to adjust the indicator’s behavior according to their preferred trading style and timeframe.
Color-Coded Candle Painting The Kalman PSaR features color-coded candles that change according to the trend direction. When the price is above the PSaR, candles are painted green to indicate a long trend, and when the price is below the PSaR, candles are painted red to signal a short trend. This visual representation makes it easy to interpret market sentiment at a glance, improving decision-making speed during fast-moving markets.
Key Features and Customization
Kalman Filter Customization: The process noise and measurement noise parameters allow traders to adjust how aggressively the filter adapts to price changes, making it suitable for both volatile and stable markets.
Smoothing Options: A variety of moving average types, such as SMA, Hull, EMA, and more, can be applied to smooth the PSaR values, ensuring that the signal remains clear even in choppy markets.
Dynamic Trend Detection: The Kalman PSaR dynamically updates based on price movements, helping traders spot trend reversals early while filtering out false signals caused by short-term volatility.
Bar Coloring and PSaR Plotting: Traders can choose to color candles based on trend direction or plot the PSaR directly on the chart for additional visual clarity.
Practical Applications
Trend-Following Strategies: The Kalman PSaR excels in trend-following strategies by providing timely signals of trend changes. The dynamic nature of the indicator allows traders to capture significant price movements while avoiding market noise.
Reversal Identification: The indicator’s ability to filter out noise and provide smoother signals makes it ideal for identifying reversals in volatile markets.
Risk Management: By plotting clear stop levels based on the PSaR, traders can use this indicator to effectively manage risk, placing stop-loss orders at key points based on the trend direction.
Conclusion
The Kalman PSaR is a fusion of the classic Parabolic SAR and the Kalman filter, offering enhanced trend detection with reduced noise. Its customizable filtering and smoothing options, combined with dynamic trend-following capabilities, make it a versatile tool for traders seeking to improve their timing and signal accuracy. The adaptive nature of the Kalman filter, combined with the robust PSaR logic, helps traders stay on the right side of the market and manage risk more effectively.