Daily Ratio OCHL Averager by Munif ShaikhThe "Daily Ratio OCHL Averager" indicator, is designed for use in financial charts. It calculates an average value based on the daily open, close, high, and low prices, and visualizes this average on the chart.
Ratio Calculation:
The script calculates a ratio representing the normalized difference as a percentage. This ratio helps determine if the current price is above or below the calculated average.
Plotting the Average Line:
The average value (dDaily) is plotted on the chart with a dynamic color indicating whether the current price is above (green) or below (red) the average.
Traders can use this indicator to visually analyze how the current price compares to the daily average. The color-coded average line helps quickly identify bullish or bearish conditions. The ratio percentage provides an additional quantitative measure of this relationship.
This indicator can be particularly useful in identifying trends and potential reversal points by showing how prices behave relative to their daily average, aiding in making informed trading decisions.
Ratio
RiskMetrics█ OVERVIEW
This library is a tool for Pine programmers that provides functions for calculating risk-adjusted performance metrics on periodic price returns. The calculations used by this library's functions closely mirror those the Broker Emulator uses to calculate strategy performance metrics (e.g., Sharpe and Sortino ratios) without depending on strategy-specific functionality.
█ CONCEPTS
Returns, risk, and volatility
The return on an investment is the relative gain or loss over a period, often expressed as a percentage. Investment returns can originate from several sources, including capital gains, dividends, and interest income. Many investors seek the highest returns possible in the quest for profit. However, prudent investing and trading entails evaluating such returns against the associated risks (i.e., the uncertainty of returns and the potential for financial losses) for a clearer perspective on overall performance and sustainability.
One way investors and analysts assess the risk of an investment is by analyzing its volatility , i.e., the statistical dispersion of historical returns. Investors often use volatility in risk estimation because it provides a quantifiable way to gauge the expected extent of fluctuation in returns. Elevated volatility implies heightened uncertainty in the market, which suggests higher expected risk. Conversely, low volatility implies relatively stable returns with relatively minimal fluctuations, thus suggesting lower expected risk. Several risk-adjusted performance metrics utilize volatility in their calculations for this reason.
Risk-free rate
The risk-free rate represents the rate of return on a hypothetical investment carrying no risk of financial loss. This theoretical rate provides a benchmark for comparing the returns on a risky investment and evaluating whether its excess returns justify the risks. If an investment's returns are at or below the theoretical risk-free rate or the risk premium is below a desired amount, it may suggest that the returns do not compensate for the extra risk, which might be a call to reassess the investment.
Since the risk-free rate is a theoretical concept, investors often utilize proxies for the rate in practice, such as Treasury bills and other government bonds. Conventionally, analysts consider such instruments "risk-free" for a domestic holder, as they are a form of government obligation with a low perceived likelihood of default.
The average yield on short-term Treasury bills, influenced by economic conditions, monetary policies, and inflation expectations, has historically hovered around 2-3% over the long term. This range also aligns with central banks' inflation targets. As such, one may interpret a value within this range as a minimum proxy for the risk-free rate, as it may correspond to the minimum rate required to maintain purchasing power over time.
The built-in Sharpe and Sortino ratios that strategies calculate and display in the Performance Summary tab use a default risk-free rate of 2%, and the metrics in this library's example code use the same default rate. Users can adjust this value to fit their analysis needs.
Risk-adjusted performance
Risk-adjusted performance metrics gauge the effectiveness of an investment by considering its returns relative to the perceived risk. They aim to provide a more well-rounded picture of performance by factoring in the level of risk taken to achieve returns. Investors can utilize such metrics to help determine whether the returns from an investment justify the risks and make informed decisions.
The two most commonly used risk-adjusted performance metrics are the Sharpe ratio and the Sortino ratio.
1. Sharpe ratio
The Sharpe ratio , developed by Nobel laureate William F. Sharpe, measures the performance of an investment compared to a theoretically risk-free asset, adjusted for the investment risk. The ratio uses the following formula:
Sharpe Ratio = (𝑅𝑎 − 𝑅𝑓) / 𝜎𝑎
Where:
• 𝑅𝑎 = Average return of the investment
• 𝑅𝑓 = Theoretical risk-free rate of return
• 𝜎𝑎 = Standard deviation of the investment's returns (volatility)
A higher Sharpe ratio indicates a more favorable risk-adjusted return, as it signifies that the investment produced higher excess returns per unit of increase in total perceived risk.
2. Sortino ratio
The Sortino ratio is a modified form of the Sharpe ratio that only considers downside volatility , i.e., the volatility of returns below the theoretical risk-free benchmark. Although it shares close similarities with the Sharpe ratio, it can produce very different values, especially when the returns do not have a symmetrical distribution, since it does not penalize upside and downside volatility equally. The ratio uses the following formula:
Sortino Ratio = (𝑅𝑎 − 𝑅𝑓) / 𝜎𝑑
Where:
• 𝑅𝑎 = Average return of the investment
• 𝑅𝑓 = Theoretical risk-free rate of return
• 𝜎𝑑 = Downside deviation (standard deviation of negative excess returns, or downside volatility)
The Sortino ratio offers an alternative perspective on an investment's return-generating efficiency since it does not consider upside volatility in its calculation. A higher Sortino ratio signifies that the investment produced higher excess returns per unit of increase in perceived downside risk.
█ CALCULATIONS
Return period detection
Calculating risk-adjusted performance metrics requires collecting returns across several periods of a given size. Analysts may use different period sizes based on the context and their preferences. However, two widely used standards are monthly or daily periods, depending on the available data and the investment's duration. The built-in ratios displayed in the Strategy Tester utilize returns from either monthly or daily periods in their calculations based on the following logic:
• Use monthly returns if the history of closed trades spans at least two months.
• Use daily returns if the trades span at least two days but less than two months.
• Do not calculate the ratios if the trade data spans fewer than two days.
This library's `detectPeriod()` function applies related logic to available chart data rather than trade data to determine which period is appropriate:
• It returns true if the chart's data spans at least two months, indicating that it's sufficient to use monthly periods.
• It returns false if the chart's data spans at least two days but not two months, suggesting the use of daily periods.
• It returns na if the length of the chart's data covers less than two days, signifying that the data is insufficient for meaningful ratio calculations.
It's important to note that programmers should only call `detectPeriod()` from a script's global scope or within the outermost scope of a function called from the global scope, as it requires the time value from the first bar to accurately measure the amount of time covered by the chart's data.
Collecting periodic returns
This library's `getPeriodicReturns()` function tracks price return data within monthly or daily periods and stores the periodic values in an array . It uses a `detectPeriod()` call as the condition to determine whether each element in the array represents the return over a monthly or daily period.
The `getPeriodicReturns()` function has two overloads. The first overload requires two arguments and outputs an array of monthly or daily returns for use in the `sharpe()` and `sortino()` methods. To calculate these returns:
1. The `percentChange` argument should be a series that represents percentage gains or losses. The values can be bar-to-bar return percentages on the chart timeframe or percentages requested from a higher timeframe.
2. The function compounds all non-na `percentChange` values within each monthly or daily period to calculate the period's total return percentage. When the `percentChange` represents returns from a higher timeframe, ensure the requested data includes gaps to avoid compounding redundant values.
3. After a period ends, the function queues the compounded return into the array , removing the oldest element from the array when its size exceeds the `maxPeriods` argument.
The resulting array represents the sequence of closed returns over up to `maxPeriods` months or days, depending on the available data.
The second overload of the function includes an additional `benchmark` parameter. Unlike the first overload, this version tracks and collects differences between the `percentChange` and the specified `benchmark` values. The resulting array represents the sequence of excess returns over up to `maxPeriods` months or days. Passing this array to the `sharpe()` and `sortino()` methods calculates generalized Information ratios , which represent the risk-adjustment performance of a sequence of returns compared to a risky benchmark instead of a risk-free rate. For consistency, ensure the non-na times of the `benchmark` values align with the times of the `percentChange` values.
Ratio methods
This library's `sharpe()` and `sortino()` methods respectively calculate the Sharpe and Sortino ratios based on an array of returns compared to a specified annual benchmark. Both methods adjust the annual benchmark based on the number of periods per year to suit the frequency of the returns:
• If the method call does not include a `periodsPerYear` argument, it uses `detectPeriod()` to determine whether the returns represent monthly or daily values based on the chart's history. If monthly, the method divides the `annualBenchmark` value by 12. If daily, it divides the value by 365.
• If the method call does specify a `periodsPerYear` argument, the argument's value supersedes the automatic calculation, facilitating custom benchmark adjustments, such as dividing by 252 when analyzing collected daily stock returns.
When the array passed to these methods represents a sequence of excess returns , such as the result from the second overload of `getPeriodicReturns()`, use an `annualBenchmark` value of 0 to avoid comparing those excess returns to a separate rate.
By default, these methods only calculate the ratios on the last available bar to minimize their resource usage. Users can override this behavior with the `forceCalc` parameter. When the value is true , the method calculates the ratio on each call if sufficient data is available, regardless of the bar index.
Look first. Then leap.
█ FUNCTIONS & METHODS
This library contains the following functions:
detectPeriod()
Determines whether the chart data has sufficient coverage to use monthly or daily returns
for risk metric calculations.
Returns: (bool) `true` if the period spans more than two months, `false` if it otherwise spans more
than two days, and `na` if the data is insufficient.
getPeriodicReturns(percentChange, maxPeriods)
(Overload 1 of 2) Tracks periodic return percentages and queues them into an array for ratio
calculations. The span of the chart's historical data determines whether the function uses
daily or monthly periods in its calculations. If the chart spans more than two months,
it uses "1M" periods. Otherwise, if the chart spans more than two days, it uses "1D"
periods. If the chart covers less than two days, it does not store changes.
Parameters:
percentChange (float) : (series float) The change percentage. The function compounds non-na values from each
chart bar within monthly or daily periods to calculate the periodic changes.
maxPeriods (simple int) : (simple int) The maximum number of periodic returns to store in the returned array.
Returns: (array) An array containing the overall percentage changes for each period, limited
to the maximum specified by `maxPeriods`.
getPeriodicReturns(percentChange, benchmark, maxPeriods)
(Overload 2 of 2) Tracks periodic excess return percentages and queues the values into an
array. The span of the chart's historical data determines whether the function uses
daily or monthly periods in its calculations. If the chart spans more than two months,
it uses "1M" periods. Otherwise, if the chart spans more than two days, it uses "1D"
periods. If the chart covers less than two days, it does not store changes.
Parameters:
percentChange (float) : (series float) The change percentage. The function compounds non-na values from each
chart bar within monthly or daily periods to calculate the periodic changes.
benchmark (float) : (series float) The benchmark percentage to compare against `percentChange` values.
The function compounds non-na values from each bar within monthly or
daily periods and subtracts the results from the compounded `percentChange` values to
calculate the excess returns. For consistency, ensure this series has a similar history
length to the `percentChange` with aligned non-na value times.
maxPeriods (simple int) : (simple int) The maximum number of periodic excess returns to store in the returned array.
Returns: (array) An array containing monthly or daily excess returns, limited
to the maximum specified by `maxPeriods`.
method sharpeRatio(returnsArray, annualBenchmark, forceCalc, periodsPerYear)
Calculates the Sharpe ratio for an array of periodic returns.
Callable as a method or a function.
Namespace types: array
Parameters:
returnsArray (array) : (array) An array of periodic return percentages, e.g., returns over monthly or
daily periods.
annualBenchmark (float) : (series float) The annual rate of return to compare against `returnsArray` values. When
`periodsPerYear` is `na`, the function divides this value by 12 to calculate a
monthly benchmark if the chart's data spans at least two months or 365 for a daily
benchmark if the data otherwise spans at least two days. If `periodsPerYear`
has a specified value, the function divides the rate by that value instead.
forceCalc (bool) : (series bool) If `true`, calculates the ratio on every call. Otherwise, ratio calculation
only occurs on the last available bar. Optional. The default is `false`.
periodsPerYear (simple int) : (simple int) If specified, divides the annual rate by this value instead of the value
determined by the time span of the chart's data.
Returns: (float) The Sharpe ratio, which estimates the excess return per unit of total volatility.
method sortinoRatio(returnsArray, annualBenchmark, forceCalc, periodsPerYear)
Calculates the Sortino ratio for an array of periodic returns.
Callable as a method or a function.
Namespace types: array
Parameters:
returnsArray (array) : (array) An array of periodic return percentages, e.g., returns over monthly or
daily periods.
annualBenchmark (float) : (series float) The annual rate of return to compare against `returnsArray` values. When
`periodsPerYear` is `na`, the function divides this value by 12 to calculate a
monthly benchmark if the chart's data spans at least two months or 365 for a daily
benchmark if the data otherwise spans at least two days. If `periodsPerYear`
has a specified value, the function divides the rate by that value instead.
forceCalc (bool) : (series bool) If `true`, calculates the ratio on every call. Otherwise, ratio calculation
only occurs on the last available bar. Optional. The default is `false`.
periodsPerYear (simple int) : (simple int) If specified, divides the annual rate by this value instead of the value
determined by the time span of the chart's data.
Returns: (float) The Sortino ratio, which estimates the excess return per unit of downside
volatility.
Ratio Chart with GMMA■About this indicator
This indicator divides the selected stocks by any stocks you specify and plots the result in a new pane.
At the same time, it plots the GMMA against the result of the division.
This allows you to see the relative chart and trend of the selected stock and the arbitrary stock.
Quote Symbol: Specify the denominator of the division. The default is TOPIX. Feel free to change it.
EMA Days: 5 to 30 days are indicated in green, and 75 to 200 days in red. Change the number of days and color freely.
Explanation of Effective Usage
It is recommended to enter an index for stocks specified in the Quote Symbol.
By entering the index, you can check the superiority of the selected issue and the index at a glance.
Example: By dividing AAPL by SP500, you can see on the chart whether AAPL is stronger or weaker relative to SP500.
(Similar concept to the Relative Strength Comparison RSC.)
At the same time, by plotting GMMA, you can confirm the trend of strength or weakness of the selected issue divided by the index. This is useful for swing trading and mid- to long-term trading.
The greater the distance between the short-term and long-term EMAs of the GMMA, the more the selected stocks outperform the index, and when the short-term and long-term EMAs cross, the trend ends and the stock underperforms the index.
■About the Chart
The screen below shows a chart plotted using this indicator.
For comparison with the regular chart, the upper screen shows only the GMMA plotted for the selected stocks.
From the red circle in the lower screen, a trend begins where the selected stocks outperform the index, and the trend ends at the blue circle.
When the trend ends, the selected stocks will underperform the index and it can be determined that it is more efficient to invest in another stock.
■このインジケーターについて
このインジケーターは選択している銘柄を、指定した任意の銘柄で割り算し、その結果を新規ペインにプロットします。
同時に、割り算の結果に対してGMMAをプロットします。
これにより選択した銘柄と、任意の銘柄の相対チャートとトレンドを把握することが出来ます。
Quote Symbol:割り算の分母を指定します。デフォルトはTOPIXです。自由に変更して下さい。
EMA日数:5~30日が緑、75~200日を赤で表記しています。日数と色は自由に変更して下さい。
■有効な使い方の説明
Quote Symbolで指定する銘柄は、指数を入力することを推奨します。
指数を入力することによって、選択した銘柄と指数の優位性を一目で確認出来ます。
例)AAPLをSP500で割ることで、SP500に比べてAAPLが相対的に強いのか、弱いのかをチャートで把握できます。
(相対力比較RSCと似たような考え方です。)
同時にGMMAをプロットすることで、選択した銘柄÷指数の強弱のトレンドを確認できます。これはスイングトレードや中長期トレードに役立ちます。
GMMAの短期EMAと長期EMAの距離が開いていくほど、指数より選択した銘柄がアウトパフォームしていると考えられ、短期EMAと長期EMAが交わるとトレンドは終了し、指数をアンダーパフォームします。
■チャートについて
下の画面がこのインジケーターを使用してプロットしたチャートです。
通常のチャートとの比較のため、上画面には選択した銘柄にGMMAだけをプロットしたものを表示しています。
下の画面の赤い丸から、選択した銘柄が指数をアウトパフォームするトレンドが始まり、青い〇でトレンドは終了します。
トレンドが終了した場合、選択した銘柄は指数をアンダーパフォームするので、別の銘柄に投資する方が効率的と判断できます。
Price Ratio Indicator [ChartPrime]The Price Ratio Indicator is a versatile tool designed to analyze the relationship between the price of an asset and its moving average. It helps traders identify overbought and oversold conditions in the market, as well as potential trend reversals.
◈ User Inputs:
MA Length: Specifies the length of the moving average used in the calculation.
MA Type Fast: Allows users to choose from various types of moving averages such as Exponential Moving Average (EMA), Simple Moving Average (SMA), Weighted Moving Average (WMA), Volume Weighted Moving Average (VWMA), Relative Moving Average (RMA), Double Exponential Moving Average (DEMA), Triple Exponential Moving Average (TEMA), Zero-Lag Exponential Moving Average (ZLEMA), and Hull Moving Average (HMA).
Upper Level and Lower Level: Define the threshold levels for identifying overbought and oversold conditions.
Signal Line Length: Determines the length of the signal line used for smoothing the indicator's values.
◈ Indicator Calculation:
The indicator calculates the ratio between the price of the asset and the selected moving average, subtracts 1 from the ratio, and then smooths the result using the chosen signal line length.
// 𝙄𝙉𝘿𝙄𝘾𝘼𝙏𝙊𝙍 𝘾𝘼𝙇𝘾𝙐𝙇𝘼𝙏𝙄𝙊𝙉𝙎
//@ Moving Average's Function
ma(src, ma_period, ma_type) =>
ma =
ma_type == 'EMA' ? ta.ema(src, ma_period) :
ma_type == 'SMA' ? ta.sma(src, ma_period) :
ma_type == 'WMA' ? ta.wma(src, ma_period) :
ma_type == 'VWMA' ? ta.vwma(src, ma_period) :
ma_type == 'RMA' ? ta.rma(src, ma_period) :
ma_type == 'DEMA' ? ta.ema(ta.ema(src, ma_period), ma_period) :
ma_type == 'TEMA' ? ta.ema(ta.ema(ta.ema(src, ma_period), ma_period), ma_period) :
ma_type == 'ZLEMA' ? ta.ema(src + src - src , ma_period) :
ma_type == 'HMA' ? ta.hma(src, ma_period)
: na
ma
//@ Smooth of Source
src = math.sum(source, 5)/5
//@ Ratio Price / MA's
p_ratio = src / ma(src, ma_period, ma_type) - 1
◈ Visualization:
The main plot displays the price ratio, with color gradients indicating the strength and direction of the ratio.
The bar color changes dynamically based on the ratio, providing a visual representation of market conditions.
Invisible Horizontal lines indicate the upper and lower threshold levels for overbought and oversold conditions.
A signal line, smoothed using the specified length, helps identify trends and potential reversal points.
High and low value regions are filled with color gradients, enhancing visualization of extreme price movements.
MA type HMA gives faster changes of the indicator (Each MA has its own specifics):
MA type TEMA:
◈ Additional Features:
A symbol displayed at the bottom right corner of the chart provides a quick visual reference to the current state of the indicator, with color intensity indicating the strength of the ratio.
Overall, the Price Ratio Indicator offers traders valuable insights into price dynamics and helps them make informed trading decisions based on the relationship between price and moving averages. Adjusting the input parameters allows for customization according to individual trading preferences and market conditions.
Dividend-to-ROE RatioDividend-to-ROE Ratio Indicator
The Dividend-to-ROE Ratio indicator offers valuable insights into a company's dividend distribution relative to its profitability, specifically comparing the Dividend Payout Ratio (proportion of earnings as dividends) to the Return on Equity (ROE), a measure of profitability from shareholder equity.
Interpretation:
1. Higher Ratio: A higher Dividend-to-ROE Ratio suggests a stable dividend policy, where a significant portion of earnings is returned to shareholders. This can indicate consistent dividend payments, often appealing to income-seeking investors.
2. Lower Ratio: Conversely, a lower ratio implies that the company retains more earnings for growth, potentially signaling a focus on reinvestment for future expansion rather than immediate dividend payouts.
3. Excessively High Ratio: An exceptionally high ratio may raise concerns. While it could reflect a generous dividend policy, excessively high ratios might indicate that a company is distributing more earnings than it can sustainably afford. This could potentially hinder the company's ability to reinvest in its operations, research, or navigate economic downturns effectively.
Utility and Applications:
The Dividend-to-ROE Ratio can be particularly useful in the following scenarios:
1. Income-Oriented Investors: For investors seeking consistent dividend income, a higher ratio signifies a company's commitment to distributing profits to shareholders, potentially aligning with income-oriented investment strategies.
2. Financial Health Assessment: Analysts and stakeholders can use this ratio to gauge a company's financial health and dividend sustainability. It provides insights into management's capital allocation decisions and strategic focus.
3. Comparative Analysis: When comparing companies within the same industry, this ratio helps in benchmarking dividend policies and identifying outliers with unusually high or low ratios.
Considerations:
1. Contextual Analysis: Interpretation should be contextualized within industry standards and the company's financial history. Comparing the ratio with peers in the same sector can provide meaningful insights.
2. Financial Health: It's crucial to evaluate this indicator alongside other financial metrics (like cash flow, debt levels, and profit margins) to grasp the company's overall financial health and sustainability of its dividend policy.
Disclaimer: This indicator is for informational purposes only and does not constitute financial advice. Investors should conduct thorough research and consult with financial professionals before making investment decisions based on this ratio.
CAPEX RatioUnderstanding the CAPEX Ratio: An Essential Financial Metric
Introduction
In the world of finance, understanding how companies allocate their resources and reinvest their earnings is crucial for investors and analysts. One fundamental metric used to assess a company's investment behavior is the CAPEX Ratio. This article delves into what the CAPEX Ratio signifies, its advantages, and how to interpret its implications.
What is the CAPEX Ratio?
The CAPEX Ratio, short for Capital Expenditure Ratio, is a financial indicator that measures the proportion of a company's capital expenditures (CAPEX) relative to various financial metrics such as revenue, free cash flow, net income, or total assets. CAPEX represents investments made by a company to acquire or maintain its physical assets.
Interpreting the Results
Each variant of the CAPEX Ratio provides unique insights into a company's financial strategy:
• CAPEX to Revenue Ratio: This ratio shows what portion of a company's revenue is being reinvested into capital investments. A higher ratio might indicate aggressive expansion plans or a need for infrastructure upgrades.
• CAPEX to Free Cash Flow Ratio: By comparing CAPEX with free cash flow, this ratio reveals how much of a company's available cash is dedicated to capital investments. It helps assess financial health and sustainability.
• CAPEX to Net Income Ratio: This ratio measures how much of a company's net income is being channeled back into capital expenditures. A high ratio relative to net income could signal a company's commitment to growth and development.
• CAPEX to Total Assets Ratio: This metric assesses the proportion of total assets being allocated towards capital expenditures. It provides a perspective on the company's investment intensity relative to its overall asset base.
Advantages of Using CAPEX Ratios
• Insight into Investment Strategy: Helps investors understand where a company is directing its resources.
• Evaluation of Financial Health: Indicates how efficiently a company is reinvesting profits or available cash.
• Comparative Analysis: Enables comparisons across companies or industries to gauge investment priorities.
How to Use the CAPEX Ratio
• Comparative Analysis: Compare the CAPEX Ratios over time or against industry peers to spot trends or outliers.
• Investment Decision-Making: Consider CAPEX Ratios alongside other financial metrics when making investment decisions.
Conclusion
In conclusion, the CAPEX Ratio is a valuable financial metric that offers deep insights into a company's investment behavior and financial health. By analyzing different variants of this ratio, investors and analysts can make informed decisions about a company's growth prospects and financial stability.
Support and Resistance: Triangles [YinYangAlgorithms]Overview:
Triangles have always been known to be the strongest shape. Well, why wouldn’t that likewise apply to trading? This Indicator will create Upwards and Downwards Triangles which in turn create Support and Resistance locations. For example, we find 2 highs that meet the criteria (within deviation %, Minimum Distance and Lookback Distance). We calculate the distance between these two and create an Equilateral Triangle Downwards (You can adjust the % if you want more of an Isosceles Triangle). The midpoint (tip) of this triangle is the Support and the bottom (base) of it is the Resistance. The exact opposite applies for an Upwards Triangle.
The reason why Triangles may make for good Support and Resistance locations is the % 's used, much like the fibonacci, use ratios relevant in nature and everywhere in the world around us, so why not for trading too?
Tutorial:
If you look at the locations we’ve circled above, all of them exhibit strong rejections are predictive Support and Resistance locations plotted by the triangles created. There can only ever be 1 Upward and 1 Downward Triangle at a time, so when a new one is created, the Support and Resistance locations are moved.
If you scroll back far enough you’ll notice the Triangles disappear but their Support and Resistance locations are still plotted. This has to do with the fact you are allowed only so many Lines plotted and when a new Triangle is created, an old one will be removed. The Support and Resistance locations however will stay.
If we look at the example above, you can see the Support and Resistance locations the Triangles made here may have helped predict where the price would struggle to surpass.
By default the Look Back Distance is set to 50 and the Min Distance is 10 (settings used in all previous examples). However, you can modify these to make Triangles more ‘Rare’ and therefore the Support and Resistance locations change less. In the example above for Instance we left Look Back Distance to 50 but changed Min Distance from 10 to 25. This results in Support and Resistance locations that may hold better in the long term.
If we scroll back a bit, we can see the settings ‘Look Back Distance’ 50 and ‘Minimum Distance’ 25 had done a decent job at predicting the ATH resistance and many Support and Resistance locations around it. Keep in mind, previous results don’t mean future results, but Triangles may create ratios which apply well to trading.
We will conclude our Tutorial here. Hopefully you can see the benefit to the ratio Triangles make when predicting Support and Resistance locations.
Settings:
Show Triangles: If all you want to know is the Support and Resistance locations, there’s no need to draw the Triangles.
Triangle Zones: What types of triangles should we create our zones for? Options are Upward, Downward, Both, None.
Max Deviation Allowed: Maximum Deviation up or down from the last bars High/Low for potential to create a Triangle.
Lookback Distance: How far back we look to see for potential of a High/Low within Deviation range.
Min Distance: This is so triangles are spaced properly and not from 2 bars beside each other. Min distance allocated between 2 points to create a Triangle.
Bar Percent Increase: How much % multiplier do we apply for each bar spacing of the triangle. 0.005 creates a close to Equilateral Triangle, but other values like 0.004 and 0.006 seem to work well too.
If you have any questions, comments, ideas or concerns please don't hesitate to contact us.
HAPPY TRADING!
Realized Profit & Loss [BigBeluga]The Realized Loss & Profit indicator aims to find potential dips and tops in price by utilizing the security function syminfo.basecurrency + "_LOSSESADDRESSES".
The primary objective of this indicator is to present an average, favorable buying/selling opportunity based on the number of people currently in profit or loss.
The script takes into consideration the syminfo.basecurrency, so it should automatically adapt to the current coin.
🔶 USAGE
Users have the option to enable the display of either Loss or Profit, depending on their preferred visualization.
Examples of displaying Losses:
Example of displaying Profits:
🔶 CONCEPTS
The concept aims to assign a score to the data in the ticker representing the realized losses. This score will provide users with an average of buying/selling points that are better to the typical investor.
🔶 SETTINGS
Users have complete control over the script settings.
🔹 Calculation
• Profit: Display people in profit on an average of the selected length.
• Loss: Display people in loss on an average of the selected length.
🔹 Candle coloring
• True: Color the candle when data is above the threshold.
• False: Do not color the candle.
🔹 Levels
- Set the level of a specific threshold.
• Low: Low losses (green).
• Normal: Low normal (yellow).
• Medium: Low medium (orange).
• High: Low high (red).
🔹 Z-score Length: Length of the z-score moving window.
🔹 Threshold: Filter out non-significant values.
🔹 Histogram width: Width of the histogram.
🔹 Colors: Modify the colors of the displayed data.
🔶 LIMITATIONS
• Since the ticker from which we obtain data works only on the daily timeframe, we are
restricted to displaying data solely from the 1D timeframe.
• If the coin does not have any realized loss data, we can't use this script.
The Strat with Continuity [starlord_xrp]This indicator shows entry and exit points for The Strat as well as potential setups. It also has full time frame continuity detection.
Ratio To Average - The Quant ScienceRatio To Average - The Quant Science is a quantitative indicator that calculates the percentage ratio of the market price in relation to a reference average. The indicator allows the calculation of the ratio using four different types of averages: SMA, EMA, WMA, and HMA. The ratio is represented by a series of histograms that highlight periods when the ratio is positive (in green) and periods when the ratio is negative (in red).
What is the Ratio to Average?
The Ratio to Average is a measure that tracks the price movements with one of its averages, calculating how much the price is above or below its own average, in percentage terms.
USER INTERFACE
Lenght: it adjusts the number of bars to include in the calculation of the average.
Moving Average: it allows you to choose the type of average to use.
Color Up/Color Down : it allows you to choose the color of the indicator for positive and negative ratios.
TTP OI + LS signal filterThis oscillator helps filtering specific conditions in the market based on open interest (OI) and the ratio of longs and shorts (LS) for crypto assets.
Currently it works with BINANCE:BTCUSDT.P but soon I'll be adding support for more assets.
It flags areas of interest like:
- Too many longs, too many shorts in the market
- Open interest too high or too low
It accepts an external signal as a source in which case filters can be applied to the original signal. For example the external signal might trigger and plot a 1 when RSI break below 70. By connecting such signal with this oscillator you'll be able to only pass-through the ones that occur when any of the areas of interest mentioned above are also valid.
If both filter are applied it acts as an OR. For example, if too many longs and too many shorts are active, it will pass through the signal in either condition.
The results of the original signal filtered is printed to be able to later use it in any external backtester strategy that accepts external sources too.
If external source signal is disabled it will trigger any time the combined filters are returning true.
Open interest and the ratio of longs/shorts is considered too high whenever the stochastic RSI calculation of the OI or ratio LS reaches a level above 80 and too low when below 20
The ratio of long/shorts is calculated by dividing the ratio of longs vs shorts from BITFINEX:BTCUSDLONGS and BITFINEX:BTCUSDSHORTS
Put to Call Ratio CorrelationHello!
Excited to share this with the community!
This is actually a very simple indicator but actually usurpingly helpful, especially for those who trade indices such as SPX, IWM, QQQ, etc.
Before I get into the indicator itself, let me explain to you its development.
I have been interested in the use of option data to detect sentiment and potential reversals in the market. However, I found option data on its own is full of noise. Its very difficult if not impossible for a trader to make their own subjective assessment about how option data is reflecting market sentiment.
Generally speaking, put to call ratios generally range between 0.8 to 1.1 on average. Unless there is a dramatic pump in calls or puts causing an aggressive spike up to over this range, or fall below this range, its really difficult to make the subjective assessment about what is happening.
So what I thought about trying to do was, instead of looking directly at put to call ratio, why not see what happens when you perform a correlation analysis of the PTC ratio to the underlying stock.
So I tried this in pinescript, pulling for Tradingview's ticker PCC (Total Equity Put to Call Ratio) and using the ta.correlation function against whichever ticker I was looking at.
I played around with this idea a bit, pulled the data into excel and from this I found something interesting. When there is a very significant negative or positive correlation between PTC ratio and price movement, we see a reversal impending. In fact, a significant negative or positive correlation (defined as a R value of 0.8 or higher or -0.8 or lower) corresponded to a stock reversal about 92% of the time when data was pulled on a 5 minute timeframe on SPY.
But wait, what is a correlation?
If you are not already familiar, a correlation is simply a statistical relationship. It is defined with a Pearson R correlation value which ranges from 0 (no correlation) to 1 (significant positive correlation) and 0 to -1 (significant negative correlation).
So what does positive vs negative mean?
A significant positive correlation means the correlation is moving the same as the underlying. In the case of this indicator, if there is a significant positive correlation could mean the stock price is climbing at the same time as the PTC ratio.
Inversely, it could mean the stock price is falling as well as the PTC ratio.
A significant negative correlation means the correlation is moving in the opposite direction. So in this case, if the stock price is climbing and the PTC ratio is falling proportionately, we would see a significant negative correlation.
So how does this work in real life?
To answer this, let's get into the actual indicator!
In the image above, you will see the arrow pointing to an area of significant POSITIVE correlation.
The indicator will paint the bars on the actual chart purple (customizable of course) to signify this is an area of significant correlation.
So, in the above example this means that the PTC ratio is increase proportionately to the increase in the stock price in the SAME direction (Puts are going up proportionately to the stock price). Thus, we can make the assumption that the underlying sentiment is overwhelmingly BEARISH. Why? Because option trading activity is significantly proportionate to stock movement, meaning that there is consensus among the options being traded and the movement of the market itself.
And in the above example we will see, the stock does indeed end up selling:
In this case, IWM fell roughly 1 point from where there was bearish consensus in the market.
Let's use this same trading day and same example to show the inverse:
You will see a little bit later, a significant NEGATIVE correlation developed.
In this case identified, the stock wise RISING and the PTC ratio was FALLING.
This means that Puts were not being bought up as much as calls and the sentiment had shifted to bullish .
And from that point, IWM ended up going up an additional 0.75 points from where there was a significant INVERSE correlation.
So you can see that it is helpful for identifying reversals. But what is also can be used for is identifying areas of LOW conviction. Meaning, areas where there really is no relationship between option activity and stock movement. Let's take spy on the 1 hour timeframe for this example:
You can see in the above example there really is no consensus in the option trading activity with the overarching sentiment. The price action is choppy and so too is option trading activity. Option traders are not pushing too far in one direction or the other. We can also see the lack of conviction in the option trading activity by looking at the correlation SMA (the white line).
When a ticker is experiencing volatile and good movement up and down, the SMA will generally trade to the top of the correlation range (roughly + 1.0) and then make a move down to the bottom (roughly - 1.0), see the example below:
When the SMA is not moving much and accumulating around the centerline, it generally means a lot of indecision.
Additional Indicator Information:
As I have said, the indicator is very simple. It pulls the data from the ticker PCC and runs a correlation assessment against whichever ticker you are on.
PCC pulls averaged data from all equities within the market and is not limited to a single equity. As such, its helpful to use this with indices such as SPY, IWM and QQQ, but I have had success with using it on individual tickers such as NVDA and AMD.
The correlation length is defaulted to 14. You can modify it if you wish, but I do recommend leaving it at this as the default and the testing I have done with this have all been on the 14 correlation length.
You can chose to smooth the SMA over whichever length of period you wish as well.
When the indicator is approaching a significant negative or positive relationship, you will see the indicator flash red in the upper or lower band to signify the relationship. As well, the chart will change the bar colour to purple:
Everything else is pretty straight forward.
Let me know your questions/comments or suggestions around the indicator and its applications.
As always, no indicator is meant to provide a single, reliable strategy to your trading regimen and no indicator or group of indicators should be relied on solely. Be sure to do your own analysis and assessments of the stock prior to taking any trades.
Safe trades everyone!
Momentum Ratio Oscillator [Loxx]What is Momentum Ratio Oscillator?
The theory behind this indicator involves utilizing a sequence of exponential moving average (EMA) calculations to achieve a smoother value of momentum ratio, which compares the current value to the previous one. Although this results in an outcome similar to that of some pre-existing indicators (such as volume zone or price zone oscillators), the use of EMA for smoothing is what sets it apart. EMA produces a smooth step-like output when values undergo sudden changes, whereas the mathematics used for those other indicators are completely distinct. This is a concept by the beloved Mladen of FX forums.
To utilize this version of the indicator, you have the option of using either levels, middle, or signal crosses for signals. The indicator is range bound from 0 to 1.
What is an EMA?
EMA stands for Exponential Moving Average, which is a type of moving average that is commonly used in technical analysis to smooth out price data and identify trends.
In a simple moving average (SMA), each data point is given equal weight when calculating the average. For example, if you are calculating the 10-day SMA, you would add up the prices for the past 10 days and divide by 10 to get the average. In contrast, in an EMA, more weight is given to recent prices, while older prices are given less weight.
The formula for calculating an EMA involves using a smoothing factor that is multiplied by the difference between the current price and the previous EMA value, and then adding this to the previous EMA value. The smoothing factor is typically calculated based on the length of the EMA being used. For example, a 10-day EMA might use a smoothing factor of 2/(10+1) or 0.1818.
The result of using an EMA is that the line produced is more responsive to recent price changes than a simple moving average. This makes it useful for identifying short-term trends and potential trend reversals. However, it can also be more volatile and prone to whipsaws, so it is often used in combination with other indicators to confirm signals.
Overall, the EMA is a widely used and versatile tool in technical analysis, and its effectiveness depends on the specific context in which it is applied.
What is Momentum?
In technical analysis, momentum refers to the rate of change of an asset's price over a certain period of time. It is often used to identify trends and potential trend reversals in financial markets.
Momentum is calculated by subtracting the closing price of an asset X days ago from its current closing price, where X is the number of days being used for the calculation. The result is the momentum value for that particular day. A positive momentum value suggests that prices are increasing, while a negative value indicates that prices are decreasing.
Traders use momentum in a variety of ways. One common approach is to look for divergences between the momentum indicator and the price of the asset being traded. For example, if an asset's price is trending upwards but its momentum is trending downwards, this could be a sign of a potential trend reversal.
Another popular strategy is to use momentum to identify overbought and oversold conditions in the market. When an asset's price has been rising rapidly and its momentum is high, it may be considered overbought and due for a correction. Conversely, when an asset's price has been falling rapidly and its momentum is low, it may be considered oversold and due for a bounce back up.
Momentum is also often used in conjunction with other technical indicators, such as moving averages or Bollinger Bands, to confirm signals and improve the accuracy of trading decisions.
Overall, momentum is a useful tool for traders and investors to analyze price movements and identify potential trading opportunities. However, like all technical indicators, it should be used in conjunction with other forms of analysis and with consideration of the broader market context.
Extras
Alerts
Signals
Loxx's Expanded Source Types, see here for details
IOFin F-Score by zdmre🗣The IOFin F-Score is a discrete score between zero and ten that reflects ten criteria used to determine the strength of a firm's financial position.
🗣It is used to determine the best value stocks, with ten being the best and zero being the worst.
The IOFin F-Score broken down into the following categories:
Profitability
Equity, cash flow, liquidity, and source of funds
Operating efficiency
Criteria Include:
Price to book (P/B) lower than 3 (1 point)
Debt to Equity (D/E) lower than 0.5 (1 point)
Price to FreeCashFlow (P/FCF) equal to or lower than 20 (1 point)
Peg Ratio lower than 1 (1 point)
Sustainable Growth Rate higher than 0.3 (1 point)
Return on Assets (ROIC) higher than 0.07 (1 point)
Return on Equity (ROE) higher than 0.3 (1 point)
EnterpriseValue/Ebitda lower than 10 (1 point)
Quick Ratio equal to or higher than 1 (1 point)
Operating Margin higher than 0.15 (1 point)
Futures/Spot Ratiowhat is Futures /Spot Ratio?
Although futures and spot markets are separate markets, they are correlated. arbitrage bots allow this gap to be closed. But arbitrage bots also have their limits. so there are always slight differences between futures and spot markets. By analyzing these differences, the movements of the players in the market can be interpreted and important information about the price can be obtained. Futures /Spot Ratio is a tool that facilitates this analysis.
what it does?
it compresses the ratio between two selected spot and futures trading pairs between 0 and 100. its purpose is to facilitate use and interpretation. it also passes a regression (Colorful Regression) through the middle of the data for the same purpose.
about Colorful Regression:
how it does it?
it uses this formula:
how to use it?
use it to understand whether the market is priced with spot trades or leveraged positions. A value of 50 is the breakeven point where the ratio of the spot and leveraged markets are equal. Values above 50 indicate excess of long positions in the market, values below 50 indicate excess of short positions. I have explained how to interpret these ratios with examples below.
Body / Range %Body / Range is a volatility indicator that shows how many percentages the body candle occupies the range.
The ratio tells us about the health and confidence of the current candlestick.
Since overall candle Range is always bigger than the body range, Body/Range indicator will always fluctuate inside a range of 0 and 100%.
I didn't use True Range because it considers gaps and the ratio won't be considering individual candles. Therefore, I used high - low and identified it as Range.
In this function, the wicks play obviously role in determining the ratio too without its variable separately in the formula. I wouldn't use wicks here because Range = body + total wicks anyway. It already covers the variable. If I made the ratio with Body / Total Wicks, we wouldn't have stable 0 - 100% range of the indicator by the way. So it's fully justified dividing Body by Range to get some summarized Candle Metrics.
Logically we assume that if wicks are relatively bigger than body then the ratio will be relatively smaller and vice versa.
Change TF of the indicator is possible. For example, 3 months per bar would look like this:
Accumulated Put/Call Ratio V2This is an updated version of the Accumulated P/C Ratio. Some changes include:
- Pinescript privacy changed from protected to open.
- Utilizes the "request.security_lower_tf" function for weekly and monthly charts.
- Now acquires and sums raw put volume (ticker: PVOL) and call volume (ticker: CVOL) separately, then divides the aggregate put to aggregate call to get the P/C ratio, as opposed to the original version which directly sums the put call ratio (ticker: PCC). Mathematically this calculation makes more sense, but the major drawback of this change seems to be that PVOL and CVOL don't have as much historical data as PCC.
The way to interpret the indicator is the same as the original version - higher values are bullish while lower values are bearish. A solid (0 transparency) bar means that the value is beyond 3 standard deviations within a particular period.
Buyer to Seller Volume (BSV) Indicator As promised, here is the buyer to seller volume indicator!
About it/How it works:
The indicator tracks buying and selling volume. It does it simplistically but effectively simply by looking at red vs green candles and averaging out the volume of each respective candle.
It uses the SMA of buying/selling and overall volume to track buyers to sellers and also display the average volume traded over a designated period of time.
Legend:
Green lines = buying volume
Red lines = selling volume
Yellow lines = SMA over designated period of time (user input defined, default is 14 candles).
Buyers are shown in green and sellers are shown in red:
How to Use it:
Default, the indicator goes to 1 Day, 14 candle period.
My preference personally is to use to have it go to "chart" but you can view any time period on the chart that you want and designate the time period of volume you want to view independently.
This can be used for:
1. Identify trends: When buying or selling volume is above selling volume and above the SMA, you know that this persuasively supports a bullish trend. Inverse for the opposite (see below):
2. To identify fakeouts and whether there is volume backing a move:
3. To identify potential changes in trends via a cross:
Its also a great reference when you are unsure of a move. This indicator literally just saved me from wrongfully shorting the FOMC bear flag today:
Probably many other uses you can find, but these are the things I like to use it for!
As always, I have posted a tutorial video for your reference:
As always though, if you have any questions, comments or suggestions for the indicator, please share them below!
Safe trades and best of luck to all!
Fixed Quantum VectorSelect a zone to analyse the vectors.
This screener show the ratio of the bullish and bearish candle vector and on volume.
Slide the white bar to choose your sample size or you can enter the date.
Click label to hide start calculation and end calculation.
- Happy trading
Financial MetricsGives a sneak peak into some of the important financial ratios described below:
1. P/E : price to earnings ratio (Green when P/E<15)
2. PEG: Price to earnings growth ratio (Green when PEG<1)
3. P/S: Price to sales ratio (Green when P/S<2)
4. EV/FCF: Enterprise Value to Free Cashflow ratio
5. OPM: Operating Profit Margin % (Green when OPM>15%)
6. D/E: Debt to equity ratio (Green when D/E<1)
7. ROE: Return on equity % (Green when ROE>15%)
8. Div_Yield: Dividend yield
Disclaimer: All the limits defined are based on the widely accepted general values, but are subjective to particular sector or group of stocks. For example IT stocks command higher valuation than cyclical stocks like metal. So Compare with other stocks of the same sector to reach any conclusion.
KERPD Noise Filter - Kaufman Efficiency Ratio and Price DensityThis indicator combines Kaufman Efficiency Ratio (KER) and Price Density theories to create a unique market noise filter that is 'right on time' compared to using KER or Price Density alone. All data is normalized and merged into a single output. Additionally, this indicator provides the ability to consider background noise and background noise buoyancy to allow dynamic observation of noise level and asset specific calibration of the indicator (if desired).
The basic theory surrounding usage is that: higher values = lower noise, while lower values = higher noise in market.
Notes: NON-DIRECTIONAL Kaufman Efficiency Ratio used. Threshold period of 30 to 40 applies to Kaufman Efficiency Ratio systems if standard length of 20 is applied; maintained despite incorporation of Price Density normalized data.
TRADING USES:
-Trend strategies, mean reversion/reversal/contrarian strategies, and identification/avoidance of ranging market conditions.
-Trend strategy where KERPD is above a certain value; generally a trend is forming/continuing as noise levels fall in the market.
-Mean reversion/reversal/contrarian strategies when KERPD exits a trending condition and falls below a certain value (additional signal confluence confirming for a strong reversal in price required); generally a reversal is forming as noise levels increase in the market.
-A filter to screen out ranging/choppy conditions where breakouts are frequently fake-outs and or price fails to move significantly; noise level is high, in addition to the background buoyancy level.
-In an adaptive trading systems to assist in determining whether to apply a trend following algorithm or a mean reversion algorithm.
THEORY / THOUGHT SPACE:
The market is a jungle. When apex predators are present it often goes quiet (institutions moving price), when absent the jungle is loud.
There is always background noise that scales with the anticipation of the silence, which has features of buoyancy that act to calibrate the beginning of the silence and return to background noise conditions.
Trend traders hunt in low noise conditions. Reversion traders hunt in the onset of low noise into static conditions. Ranges can be avoided during high noise and buoyant background noise conditions.
Distance between the noise line and background noise can help inform decision making.
CALIBRATION:
- Set the Noise Threshold % color change line so that the color cut off is where your trend/reversion should begin.
- Set the Background Noise Buoyancy Calibration Decimal % to match the beginning/end of the color change Noise Threshold % line. Match the Background Noise Baseline Decimal %' to the number set for buoyancy.
- Additionally, create your own custom settings; 33/34 and 50 length also provides interesting results.
- A color change tape option can be enabled by un-commenting the lines at the bottom of this script.
Market Usage:
Stock, Crypto, Forex, and Others
Excellent for: NDQ, J225, US30, SPX
Market Conditions:
Trend, Reversal, Ranging
ABC 123 Harmonic Ratio Custom Range Interactive█ OVERVIEW
This indicator was designed based on Harmonic Trading : Volume One written by Scott Carney.
This is about harmonic ratios which expanded through retracement and projection.
Derivation is pretty much explained here such as Primary, Primary Derivation, Secondary Derivation and Secondary Derivation Extreme.
Derivation value depends on minimum retracement or maximum projection.
This derivation value utilize Fibonacci value which later expand to Harmonic Ratio.
█ INSPIRATION
Inspired by design, code and usage of CAGR . Basic usage of custom range / interactive, pretty much explained here . Credits to TradingView.
This build is based and visualized upon Harmonic Trading Ratios.
This build also was stripped down from XABCD Harmonic Pattern Custom Range Interactive .
█ CREDITS
Scott Carney, Harmonic Trading : Volume One (Page 18)
█ FEATURES
Table can positioned by any position and font size can be resized.
Labels can be either changed to alphabets or numbers.
█ HOW TO USE
Draw points from Point A to Point C.
Dont worry about magnet, point will attached depends on High or Low of the candle.
█ USAGE / TIPS EXAMPLES (Description explained in each image)
Bitcoin Golden Pi CyclesTops are signaled by the fast top MA crossing above the slow top MA, and bottoms are signaled by the slow bottom MA crossing above the fast bottom MA. Alerts can be set on top and bottom prints. Does not repaint.
Similar to the work of Philip Swift regarding the Bitcoin Pi Cycle Top, I’ve recently come across a similar mathematically curious ratio that corresponds to Bitcoin cycle bottoms. This ratio was extracted from skirmantas’ Bitcoin Super Cycle indicator . Cycle bottoms are signaled when the 700D SMA crosses above the 137D SMA (because this indicator is closed source, these moving averages were reverse-engineered). Such crossings have historically coincided with the January 2015 and December 2018 bottoms. Also, although yet to be confirmed as a bottom, a cross occurred June 19, 2022 (two days prior to this article)
The original pi cycle uses the doubled 350D SMA and the 111D SMA . As pointed out this gives the original pi cycle top ratio:
350/111 = 3.1532 ≈ π
Also, as noted by Swift, 111 is the best integer for dividing 350 to approximate π. What is mathematically interesting about skirmanta’s ratio?
700/138 = 5.1095
After playing around with this for a while I realized that 5.11 is very close to the product of the two most numerologically significant geometrical constants, π and the golden ratio, ϕ:
πϕ = 5.0832
However, 138 turns out to be the best integer denominator to approximate πϕ:
700/138 = 5.0725 ≈ πϕ
This is what I’ve dubbed the Bitcoin Golden Pi Bottom Ratio.
In the spirit of numerology I must mention that 137 does have some things going for it: it’s a prime number and is very famously almost exactly the reciprocal of the fine structure constant (α is within 0.03% of 1/137).
Now why 350 and 700 and not say 360 and 720? After all, 360 is obviously much more numerologically significant than 350, which is proven by the fact that 360 has its own wikipedia page, and 350 does not! Using 360/115 and 720/142, which are also approximations of π and πϕ respectively, this also calls cycle tops and bottoms.
There are infinitely many such ratios that could work to approximate π and πϕ (although there are a finite number whose daily moving averages are defined). Further analysis is needed to find the range(s) of numerators (the numerator determines the denominator when maintaining the ratio) that correctly produce bottom and top signals.