Volume StatsDescription:
Volume Stats displays volume data and statistics for every day of the year, and is designed to work on "1D" timeframe. The data is displayed in a table with columns being months of the year, and rows being days of each month. By default, latest data is displayed, but you have an option to switch to data of the previous year as well.
The statistics displayed for each day is:
- volume
- % of total yearly volume
- % of total monthly volume
The statistics displayed for each column (month) is:
- monthly volume
- % of total yearly volume
- sentiment (was there more bullish or bearish volume?)
- min volume (on which day of the month was the min volume)
- max volume (on which day of the month was the max volume)
The cells change their colors depending on whether the volume is bullish or bearish, and what % of total volume the current cell has (either yearly or monthly). The header cells also change their color (based either on sentiment or what % of yearly volume the current month has).
This is the first (and free) version of the indicator, and I'm planning to create a "PRO" version of this indicator in future.
Parameters:
- Timezone
- Cell data -> which data to display in the cells (no data, volume or percentage)
- Highlight min and max volume -> if checked, cells with min and max volume (either monthly or yearly) will be highlighted with a dot or letter (depending on the "Cell data" input)
- Cell stats mode -> which data to use for color and % calculation (All data = yearly, Column = monthly)
- Display data from previous year -> if checked, the data from previous year will be used
- Header color is calculated from -> either sentiment or % of the yearly volume
- Reverse theme -> the table colors are automatically changed based on the "Dark mode" of Tradingview, this checkbox reverses the logic (so that darker colors will be used when "Dark mode" is off, and lighter colors when it's on)
- Hide logo -> hides the cat logo (PLEASE DO NOT HIDE THE CAT)
Conclusion:
Let me know what you think of the indicator. As I said, I'm planning to make a PRO version with more features, for which I already have some ideas, but if you have any suggestions, please let me know.
Statistic
analytics_tablesLibrary "analytics_tables"
📝 Description
This library provides the implementation of several performance-related statistics and metrics, presented in the form of tables.
The metrics shown in the afforementioned tables where developed during the past years of my in-depth analalysis of various strategies in an atempt to reason about the performance of each strategy.
The visualization and some statistics where inspired by the existing implementations of the "Seasonality" script, and the performance matrix implementations of @QuantNomad and @ZenAndTheArtOfTrading scripts.
While this library is meant to be used by my strategy framework "Template Trailing Strategy (Backtester)" script, I wrapped it in a library hoping this can be usefull for other community strategy scripts that will be released in the future.
🤔 How to Guide
To use the functionality this library provides in your script you have to import it first!
Copy the import statement of the latest release by pressing the copy button below and then paste it into your script. Give a short name to this library so you can refer to it later on. The import statement should look like this:
import jason5480/analytics_tables/1 as ant
There are three types of tables provided by this library in the initial release. The stats table the metrics table and the seasonality table.
Each one shows different kinds of performance statistics.
The table UDT shall be initialized once using the `init()` method.
They can be updated using the `update()` method where the updated data UDT object shall be passed.
The data UDT can also initialized and get updated on demend depending on the use case
A code example for the StatsTable is the following:
var ant.StatsData statsData = ant.StatsData.new()
statsData.update(SideStats.new(), SideStats.new(), 0)
if (barstate.islastconfirmedhistory or (barstate.isrealtime and barstate.isconfirmed))
var statsTable = ant.StatsTable.new().init(ant.getTablePos('TOP', 'RIGHT'))
statsTable.update(statsData)
A code example for the MetricsTable is the following:
var ant.StatsData statsData = ant.StatsData.new()
statsData.update(ant.SideStats.new(), ant.SideStats.new(), 0)
if (barstate.islastconfirmedhistory or (barstate.isrealtime and barstate.isconfirmed))
var metricsTable = ant.MetricsTable.new().init(ant.getTablePos('BOTTOM', 'RIGHT'))
metricsTable.update(statsData, 10)
A code example for the SeasonalityTable is the following:
var ant.SeasonalData seasonalData = ant.SeasonalData.new().init(Seasonality.monthOfYear)
seasonalData.update()
if (barstate.islastconfirmedhistory or (barstate.isrealtime and barstate.isconfirmed))
var seasonalTable = ant.SeasonalTable.new().init(seasonalData, ant.getTablePos('BOTTOM', 'LEFT'))
seasonalTable.update(seasonalData)
🏋️♂️ Please refer to the "EXAMPLE" regions of the script for more advanced and up to date code examples!
Special thanks to @Mrcrbw for the proposal to develop this library and @DCNeu for the constructive feedback 🏆.
getTablePos(ypos, xpos)
Get table position compatible string
Parameters:
ypos (simple string) : The position on y axise
xpos (simple string) : The position on x axise
Returns: The position to be passed to the table
method init(this, pos, height, width, positiveTxtColor, negativeTxtColor, neutralTxtColor, positiveBgColor, negativeBgColor, neutralBgColor)
Initialize the stats table object with the given colors in the given position
Namespace types: StatsTable
Parameters:
this (StatsTable) : The stats table object
pos (simple string) : The table position string
height (simple float) : The height of the table as a percentage of the charts height. By default, 0 auto-adjusts the height based on the text inside the cells
width (simple float) : The width of the table as a percentage of the charts height. By default, 0 auto-adjusts the width based on the text inside the cells
positiveTxtColor (simple color) : The text color when positive
negativeTxtColor (simple color) : The text color when negative
neutralTxtColor (simple color) : The text color when neutral
positiveBgColor (simple color) : The background color with transparency when positive
negativeBgColor (simple color) : The background color with transparency when negative
neutralBgColor (simple color) : The background color with transparency when neutral
method init(this, pos, height, width, neutralBgColor)
Initialize the metrics table object with the given colors in the given position
Namespace types: MetricsTable
Parameters:
this (MetricsTable) : The metrics table object
pos (simple string) : The table position string
height (simple float) : The height of the table as a percentage of the charts height. By default, 0 auto-adjusts the height based on the text inside the cells
width (simple float) : The width of the table as a percentage of the charts width. By default, 0 auto-adjusts the width based on the text inside the cells
neutralBgColor (simple color) : The background color with transparency when neutral
method init(this, seas)
Initialize the seasonal data
Namespace types: SeasonalData
Parameters:
this (SeasonalData) : The seasonal data object
seas (simple Seasonality) : The seasonality of the matrix data
method init(this, data, pos, maxNumOfYears, height, width, extended, neutralTxtColor, neutralBgColor)
Initialize the seasonal table object with the given colors in the given position
Namespace types: SeasonalTable
Parameters:
this (SeasonalTable) : The seasonal table object
data (SeasonalData) : The seasonality data of the table
pos (simple string) : The table position string
maxNumOfYears (simple int) : The maximum number of years that fit into the table
height (simple float) : The height of the table as a percentage of the charts height. By default, 0 auto-adjusts the height based on the text inside the cells
width (simple float) : The width of the table as a percentage of the charts width. By default, 0 auto-adjusts the width based on the text inside the cells
extended (simple bool) : The seasonal table with extended columns for performance
neutralTxtColor (simple color) : The text color when neutral
neutralBgColor (simple color) : The background color with transparency when neutral
method update(this, wins, losses, numOfInconclusiveExits)
Update the strategy info data of the strategy
Namespace types: StatsData
Parameters:
this (StatsData) : The strategy statistics object
wins (SideStats)
losses (SideStats)
numOfInconclusiveExits (int) : The number of inconclusive trades
method update(this, stats, positiveTxtColor, negativeTxtColor, negativeBgColor, neutralBgColor)
Update the stats table object with the given data
Namespace types: StatsTable
Parameters:
this (StatsTable) : The stats table object
stats (StatsData) : The stats data to update the table
positiveTxtColor (simple color) : The text color when positive
negativeTxtColor (simple color) : The text color when negative
negativeBgColor (simple color) : The background color with transparency when negative
neutralBgColor (simple color) : The background color with transparency when neutral
method update(this, stats, buyAndHoldPerc, positiveTxtColor, negativeTxtColor, positiveBgColor, negativeBgColor)
Update the metrics table object with the given data
Namespace types: MetricsTable
Parameters:
this (MetricsTable) : The metrics table object
stats (StatsData) : The stats data to update the table
buyAndHoldPerc (float) : The buy and hold percetage
positiveTxtColor (simple color) : The text color when positive
negativeTxtColor (simple color) : The text color when negative
positiveBgColor (simple color) : The background color with transparency when positive
negativeBgColor (simple color) : The background color with transparency when negative
method update(this)
Update the seasonal data based on the season and eon timeframe
Namespace types: SeasonalData
Parameters:
this (SeasonalData) : The seasonal data object
method update(this, data, positiveTxtColor, negativeTxtColor, neutralTxtColor, positiveBgColor, negativeBgColor, neutralBgColor, timeBgColor)
Update the seasonal table object with the given data
Namespace types: SeasonalTable
Parameters:
this (SeasonalTable) : The seasonal table object
data (SeasonalData) : The seasonal cell data to update the table
positiveTxtColor (simple color) : The text color when positive
negativeTxtColor (simple color) : The text color when negative
neutralTxtColor (simple color) : The text color when neutral
positiveBgColor (simple color) : The background color with transparency when positive
negativeBgColor (simple color) : The background color with transparency when negative
neutralBgColor (simple color) : The background color with transparency when neutral
timeBgColor (simple color) : The background color of the time gradient
SideStats
Object that represents the strategy statistics data of one side win or lose
Fields:
numOf (series int)
sumFreeProfit (series float)
freeProfitStDev (series float)
sumProfit (series float)
profitStDev (series float)
sumGain (series float)
gainStDev (series float)
avgQuantityPerc (series float)
avgCapitalRiskPerc (series float)
avgTPExecutedCount (series float)
avgRiskRewardRatio (series float)
maxStreak (series int)
StatsTable
Object that represents the stats table
Fields:
table (series table) : The actual table
rows (series int) : The number of rows of the table
columns (series int) : The number of columns of the table
StatsData
Object that represents the statistics data of the strategy
Fields:
wins (SideStats)
losses (SideStats)
numOfInconclusiveExits (series int)
avgFreeProfitStr (series string)
freeProfitStDevStr (series string)
lossFreeProfitStDevStr (series string)
avgProfitStr (series string)
profitStDevStr (series string)
lossProfitStDevStr (series string)
avgQuantityStr (series string)
MetricsTable
Object that represents the metrics table
Fields:
table (series table) : The actual table
rows (series int) : The number of rows of the table
columns (series int) : The number of columns of the table
SeasonalData
Object that represents the seasonal table dynamic data
Fields:
seasonality (series Seasonality)
eonToMatrixRow (map)
numOfEons (series int)
mostRecentMatrixRow (series int)
balances (matrix)
returnPercs (matrix)
maxDDs (matrix)
eonReturnPercs (array)
eonCAGRs (array)
eonMaxDDs (array)
SeasonalTable
Object that represents the seasonal table
Fields:
table (series table) : The actual table
headRows (series int) : The number of head rows of the table
headColumns (series int) : The number of head columns of the table
eonRows (series int) : The number of eon rows of the table
seasonColumns (series int) : The number of season columns of the table
statsRows (series int)
statsColumns (series int) : The number of stats columns of the table
rows (series int) : The number of rows of the table
columns (series int) : The number of columns of the table
extended (series bool) : Whether the table has additional performance statistics
Portfolio Index Generator [By MUQWISHI]▋ INTRODUCTION:
The “Portfolio Index Generator” simplifies the process of building a custom portfolio management index, allowing investors to input a list of preferred holdings from global securities and customize the initial investment weight of each security. Furthermore, it includes an option for rebalancing by adjusting the weights of assets to maintain a desired level of asset allocation. The tool serves as a comprehensive approach for tracking portfolio performance, conducting research, and analyzing specific aspects of portfolio investment. The output includes an index value, a table of holdings, and chart plotting, providing a deeper understanding of the portfolio's historical movement.
_______________________
▋ OVERVIEW:
The image can be taken as an example of building a custom portfolio index. I created this index and named it “My Portfolio Performance”, which comprises several global companies and crypto assets.
_______________________
▋ OUTPUTS:
The output can be divided into 4 sections:
1. Portfolio Index Title (Name & Value).
2. Portfolio Specifications.
3. Portfolio Holdings.
4. Portfolio Index Chart.
1. Portfolio Index Title, displays the index name at the top, and at the bottom, it shows the index value, along with the chart timeframe, e.g., daily change in points and percentage.
2. Portfolio Specifications, displays the essential information on portfolio performance, including the investment date range, initial capital, returns, assets, and equity.
3. Portfolio Holdings, a list of the holding securities inside a table that contains the ticker, average entry price, last price, return percentage of the portfolio's initial capital, and customized weighted percentage of the portfolio. Additionally, a tooltip appears when the user passes the cursor over a ticker's cell, showing brief information about the company, such as the company's name, exchange market, country, sector, and industry.
4. Index Chart, display a plot of the historical movement of the index in the form of a bar, candle, or line chart.
_______________________
▋ INDICATOR SETTINGS:
Section(1): Style Settings
(1) Naming the index.
(2) Table location on the chart and cell size.
(3) Sorting Holdings Table. By securities’ {Return(%) Portfolio, Weight(%) Portfolio, or Ticker Alphabetical} order.
(4) Choose the type of index: {Equity or Return (%)}, and the plot type for the index: {Candle, Bar, or Line}.
(5) Positive/Negative colors.
(6) Table Colors (Title, Cell, and Text).
(7) To show/hide any indicator’s components.
Section(2): Performance Settings
(1) Calculation window period: from DateTime to DateTime.
(2) Initial Capital and specifying currency.
(3) Option to enable portfolio rebalancing in {Monthly, Quarterly, or Yearly} intervals.
Section(3): Portfolio Holdings
(1) Enable and count security in the investment portfolio.
(2) Initial weight of security. For example, if the initial capital is $100,000 and the weight of XYZ stock is 4%, the initial value of the shares would be $4,000.
(3) Select and add up to 30 symbols that interested in.
Please let me know if you have any questions.
Volatility and Volume by Hour EXT(Extended republication, use this instead of the old one)
The goal of this indicator is to show a “characteristic” of the instrument, regarding the price change and trading volume. You can see how the instrument “behaved” throughout the day in the lookback period. I've found this useful for timing in day trading.
The indicator creates a table on the chart to display various statistics for each hour of the day.
Important: ONLY SHOWS THE TABLE IF THE CHART’S TIMEFRAME IS 1H!
Explanation of the columns:
1. Volatility Percentage (Volat): This column shows the volatility of the price as a percentage. For example, a value of "15%" means the price movement was 15% of the total daily price movement within the hour.
2. Hourly Point Change (PointCh): This column shows the change in price points for each hour in the lookback period. For example, a value of "5" means the price has increased by 5 points in the hour, while "-3" means it has decreased by 3 points.
3. Hourly Point Change Percentage (PrCh% (LeverageX)): This column shows the percentage change in price points for each hour, adjusted with leverage multiplier. Displayed green (+) or red (-) accordingly. For example, a value of "10%" with a leverage of 2X means the price has effectively changed by 5% due to the leverage.
4. Trading Volume Percentage (TrVol): This column shows the percentage of the daily total volume that was traded in a specific hour. For example, a value of "10%" would mean that 10% of the day's total trading volume occurred in that hour.
5. Added New! - Relevancy Check: The indicator checks the last 24 candle. If the direction of the price movement was the same in the last 24 hour as the statistical direction in that hour, the background of the relevant hour in the second column goes green.
For example: if today at 9 o'clock the price went lower, so as at 9 o'clock in the loopback period, the instrument "behaves" according to statistics . So the statistics is probably more relevant for today. The more green background row the more relevancy.
Settings:
1. Lookback period: The lookback period is the number of previous bars from which data is taken to perform calculations. In this script, it's used in a loop that iterates over a certain number of past bars to calculate the statistics. TIP: Select a period the contains a trend in one direction, because an upward and a downward trend compensate the price movement in opposite directions.
2. Timezone: This is a string input that represents the user's timezone. The default value is "UTC+2". Adjust it to your timezone in order to view the hours properly.
3. Leverage: The default value is 10(!). This input is used to adjust the hourly point change percentage. For FOREX traders (for example) the statistics can show the leveraged percentage of price change. Set that according the leverage you trade the instrument with.
Use at your own risk, provided “as is” basis!
Hope you find it useful! Cheers!
trend_switch
█ Description
Asset price data was time series data, commonly consisting of trends, seasonality, and noise. Many applicable indicators help traders to determine between trend or momentum to make a better trading decision based on their preferences. In some cases, there is little to no clear market direction, and price range. It feels much more appropriate to use a shorter trend identifier, until clearly defined market trend. The indicator/strategy developed with the notion aims to automatically switch between shorter and longer trend following indicator. There were many methods that can be applied and switched between, however in this indicator/strategy will be limited to the use of predictive moving average and MESA adaptive moving average (Ehlers), by first determining if there is a strong trend identified by calculating the slope, if slope value is between upper and lower threshold assumed there is not much price direction.
█ Formula
// predictive moving average
predict = (2*wma1-wma2)
trigger = (4*predict+3*predict +2*predict *predict)
// MESA adaptive moving average
mama = alpha*src+(1-alpha)*mama
fama = .5*alpha*mama+(1-.5-alpha)*fama
█ Feature
The indicator will have a specified default parameter of:
source = ohlc4
lookback period = 10
threshold = 10
fast limit = 0.5
slow limit = 0.05
Strategy type can be switched between Long/Short only and Long-Short strategy
Strategy backtest period
█ How it works
If slope between the upper (red) and lower (green) threshold line, assume there is little to no clear market direction, thus signal predictive moving average indicator
If slope is above the upper (red) or below the lower (green) threshold line, assume there is a clear trend forming, the signal generated from the MESA adaptive moving average indicator
█ Example 1 - Slope fall between the Threshold - activate shorter trend
█ Example 2 - Slope fall above/below Threshold - activate longer trend
Inflation CorrelationHeyo fellas,
In today’s dynamic economic landscape, understanding the relationship of market prices to other economical factors like inflation rate is crucial. The Inflation Correlation Indicator is designed to provide traders with a clear visualization of this relationship. By correlating average inflation rates from selected countries with market closing prices, this indicator offers a unique perspective on potential market movements influenced by inflationary trends.
Features:
Country Selection: Choose from the European Union (EU), Germany (DE), or the United States (US) to tailor the correlation analysis to your specific market interest.
Correlation Length Customization: Adjust the correlation length to refine the sensitivity of the indicator to recent inflation data.
Visual Clarity: The correlation histogram changes color based on the direction of the correlation, providing an intuitive understanding of the inflation correlation.
Whether you’re a fundamental analyst seeking to incorporate macroeconomic indicators into your strategy or a trader looking for an edge in inflation-sensitive markets, the Inflation Correlation Indicator is an indispensable tool in your TradingView arsenal.
Thanks for checking this out!
Best regards,
simwai
Statistics • Chi Square • P-value • SignificanceThe Statistics • Chi Square • P-value • Significance publication aims to provide a tool for combining different conditions and checking whether the outcome is significant using the Chi-Square Test and P-value.
🔶 USAGE
The basic principle is to compare two or more groups and check the results of a query test, such as asking men and women whether they want to see a romantic or non-romantic movie.
–––––––––––––––––––––––––––––––––––––––––––––
| | ROMANTIC | NON-ROMANTIC | ⬅︎ MOVIE |
–––––––––––––––––––––––––––––––––––––––––––––
| MEN | 2 | 8 | 10 |
–––––––––––––––––––––––––––––––––––––––––––––
| WOMEN | 7 | 3 | 10 |
–––––––––––––––––––––––––––––––––––––––––––––
|⬆︎ SEX | 10 | 10 | 20 |
–––––––––––––––––––––––––––––––––––––––––––––
We calculate the Chi-Square Formula, which is:
Χ² = Σ ( (Observed Value − Expected Value)² / Expected Value )
In this publication, this is:
chiSquare = 0.
for i = 0 to rows -1
for j = 0 to colums -1
observedValue = aBin.get(i).aFloat.get(j)
expectedValue = math.max(1e-12, aBin.get(i).aFloat.get(colums) * aBin.get(rows).aFloat.get(j) / sumT) //Division by 0 protection
chiSquare += math.pow(observedValue - expectedValue, 2) / expectedValue
Together with the 'Degree of Freedom', which is (rows − 1) × (columns − 1) , the P-value can be calculated.
In this case it is P-value: 0.02462
A P-value lower than 0.05 is considered to be significant. Statistically, women tend to choose a romantic movie more, while men prefer a non-romantic one.
Users have the option to choose a P-value, calculated from a standard table or through a math.ucla.edu - Javascript-based function (see references below).
Note that the population (10 men + 10 women = 20) is small, something to consider.
Either way, this principle is applied in the script, where conditions can be chosen like rsi, close, high, ...
🔹 CONDITION
Conditions are added to the left column ('CONDITION')
For example, previous rsi values (rsi ) between 0-100, divided in separate groups
🔹 CLOSE
Then, the movement of the last close is evaluated
UP when close is higher then previous close (close )
DOWN when close is lower then previous close
EQUAL when close is equal then previous close
It is also possible to use only 2 columns by adding EQUAL to UP or DOWN
UP
DOWN/EQUAL
or
UP/EQUAL
DOWN
In other words, when previous rsi value was between 80 and 90, this resulted in:
19 times a current close higher than previous close
14 times a current close lower than previous close
0 times a current close equal than previous close
However, the P-value tells us it is not statistical significant.
NOTE: Always keep in mind that past behaviour gives no certainty about future behaviour.
A vertical line is drawn at the beginning of the chosen population (max 4990)
Here, the results seem significant.
🔹 GROUPS
It is important to ensure that the groups are formed correctly. All possibilities should be present, and conditions should only be part of 1 group.
In the example above, the two top situations are acceptable; close against close can only be higher, lower or equal.
The two examples at the bottom, however, are very poorly constructed.
Several conditions can be placed in more than 1 group, and some conditions are not integrated into a group. Even if the results are significant, they are useless because of the group formation.
A population count is added as an aid to spot errors in group formation.
In this example, there is a discrepancy between the population and total count due to the absence of a condition.
The results when rsi was between 5-25 are not included, resulting in unreliable results.
🔹 PRACTICAL EXAMPLES
In this example, we have specific groups where the condition only applies to that group.
For example, the condition rsi > 55 and rsi <= 65 isn't true in another group.
Also, every possible rsi value (0 - 100) is present in 1 of the groups.
rsi > 15 and rsi <= 25 28 times UP, 19 times DOWN and 2 times EQUAL. P-value: 0.01171
When looking in detail and examining the area 15-25 RSI, we see this:
The population is now not representative (only checking for RSI between 15-25; all other RSI values are not included), so we can ignore the P-value in this case. It is merely to check in detail. In this case, the RSI values 23 and 24 seem promising.
NOTE: We should check what the close price did without any condition.
If, for example, the close price had risen 100 times out of 100, this would make things very relative.
In this case (at least two conditions need to be present), we set 1 condition at 'always true' and another at 'always false' so we'll get only the close values without any condition:
Changing the population or the conditions will change the P-value.
In the following example, the outcome is evaluated when:
close value from 1 bar back is higher than the close value from 2 bars back
close value from 1 bar back is lower/equal than the close value from 2 bars back
Or:
close value from 1 bar back is higher than the close value from 2 bars back
close value from 1 bar back is equal than the close value from 2 bars back
close value from 1 bar back is lower than the close value from 2 bars back
In both examples, all possibilities of close against close are included in the calculations. close can only by higher, equal or lower than close
Both examples have the results without a condition included (5 = 5 and 5 < 5) so one can compare the direction of current close.
🔶 NOTES
• Always keep in mind that:
Past behaviour gives no certainty about future behaviour.
Everything depends on time, cycles, events, fundamentals, technicals, ...
• This test only works for categorical data (data in categories), such as Gender {Men, Women} or color {Red, Yellow, Green, Blue} etc., but not numerical data such as height or weight. One might argue that such tests shouldn't use rsi, close, ... values.
• Consider what you're measuring
For example rsi of the current bar will always lead to a close higher than the previous close, since this is inherent to the rsi calculations.
• Be careful; often, there are na -values at the beginning of the series, which are not included in the calculations!
• Always keep in mind considering what the close price did without any condition
• The numbers must be large enough. Each entry must be five or more. In other words, it is vital to make the 'population' large enough.
• The code can be developed further, for example, by splitting UP, DOWN in close UP 1-2%, close UP 2-3%, close UP 3-4%, ...
• rsi can be supplemented with stochRSI, MFI, sma, ema, ...
🔶 SETTINGS
🔹 Population
• Choose the population size; in other words, how many bars you want to go back to. If fewer bars are available than set, this will be automatically adjusted.
🔹 Inputs
At least two conditions need to be chosen.
• Users can add up to 11 conditions, where each condition can contain two different conditions.
🔹 RSI
• Length
🔹 Levels
• Set the used levels as desired.
🔹 Levels
• P-value: P-value retrieved using a standard table method or a function.
• Used function, derived from Chi-Square Distribution Function; JavaScript
LogGamma(Z) =>
S = 1
+ 76.18009173 / Z
- 86.50532033 / (Z+1)
+ 24.01409822 / (Z+2)
- 1.231739516 / (Z+3)
+ 0.00120858003 / (Z+4)
- 0.00000536382 / (Z+5)
(Z-.5) * math.log(Z+4.5) - (Z+4.5) + math.log(S * 2.50662827465)
Gcf(float X, A) => // Good for X > A +1
A0=0., B0=1., A1=1., B1=X, AOLD=0., N=0
while (math.abs((A1-AOLD)/A1) > .00001)
AOLD := A1
N += 1
A0 := A1+(N-A)*A0
B0 := B1+(N-A)*B0
A1 := X*A0+N*A1
B1 := X*B0+N*B1
A0 := A0/B1
B0 := B0/B1
A1 := A1/B1
B1 := 1
Prob = math.exp(A * math.log(X) - X - LogGamma(A)) * A1
1 - Prob
Gser(X, A) => // Good for X < A +1
T9 = 1. / A
G = T9
I = 1
while (T9 > G* 0.00001)
T9 := T9 * X / (A + I)
G := G + T9
I += 1
G *= math.exp(A * math.log(X) - X - LogGamma(A))
Gammacdf(x, a) =>
GI = 0.
if (x<=0)
GI := 0
else if (x
Chisqcdf = Gammacdf(Z/2, DF/2)
Chisqcdf := math.round(Chisqcdf * 100000) / 100000
pValue = 1 - Chisqcdf
🔶 REFERENCES
mathsisfun.com, Chi-Square Test
Chi-Square Distribution Function
Wick %Heyo Fellas,
thanks for checking out my new indicator.
Introduction
Wick % is a simple indicator to compare wick size with body size (mode 1) and to compare wick size with candle size (mode 2).
Upper wicks are bullish when close is higher than open pricen.
Lower wicks are bearish when close is lower than open price.
Wick Theory
In general, big wick and small bodie on a bar means that bull and bears are fighting heavily.
A big wick below the body means the bulls are leading in that fight,
and a big wick above the body means the bears are leading in that fight.
Calculation Formula
Mode 1 – Percentual Increase Wick/Body:
upperWickPercentage = (upperWick / body) * 100 - 100
lowerWickPercentage = (lowerWick / body) * 100 - 100
Mode 2 – Percent Wick/Candlestick:
upperWickPercentage = (upperWick / (high - low)) * 100
lowerWickPercentage = (lowerWick / (high - low)) * 100
Usage
You can use it on every symbol and every timeframe.
The indicator repaints by default, but you can disable it in the settings.
When you disable repaint, it moves the label one bar to the right.
If you want to use the indicator for signals, you must disable repainting.
Best regards,
simwai
Likelihood of Winning - Probability Density FunctionIn developing the "Likelihood of Winning - Probability Density Function (PDF)" indicator, my aim was to offer traders a statistical tool to quantify the probability of reaching target prices. This indicator, grounded in risk assessment principles, enables users to analyze potential outcomes based on the normal distribution, providing insights into market dynamics.
The tool's flexibility allows for customization of the data series, lookback periods, and target settings for both long and short scenarios. It features a color-coded visualization to easily distinguish between probabilities of hitting specified targets, enhancing decision-making in trading strategies.
I'm excited to share this indicator with the trading community, hoping it will enhance data-driven decision-making and offer a deeper understanding of market risks and opportunities. My goal is to continuously improve this tool based on user feedback and market evolution, contributing to more informed trading practices.
This indicator leverages the "NormalDistributionFunctions" library, enabling easy integration into other indicators or strategies. Users can readily embed advanced statistical analysis into their trading tools, fostering innovation within the Pine Script community.
Day/Week/Month Metrics (Zeiierman)█ Overview
The Day/Week/Month Metrics (Zeiierman) indicator is a powerful tool for traders looking to incorporate historical performance into their trading strategy. It computes statistical metrics related to the performance of a trading instrument on different time scales: daily, weekly, and monthly. Breaking down the performance into daily, weekly, and monthly metrics provides a granular view of the instrument's behavior.
The indicator requires the chart to be set on a daily timeframe.
█ Key Statistics
⚪ Day in month
The performance of financial markets can show variability across different days within a month. This phenomenon, often referred to as the "monthly effect" or "turn-of-the-month effect," suggests that certain days of the month, especially the first and last days, tend to exhibit higher than average returns in many stock markets around the world. This effect is attributed to various factors including payroll contributions, investment of monthly dividends, and psychological factors among traders and investors.
⚪ Edge
The Edge calculation identifies days within a month that consistently outperform the average monthly trading performance. It provides a statistical advantage by quantifying how often trading on these specific days yields better returns than the overall monthly average. This insight helps traders understand not just when returns might be higher, but also how reliable these patterns are over time. By focusing on days with a higher "Edge," traders can potentially increase their chances of success by aligning their strategies with historically more profitable days.
⚪ Month
Historically, the stock market has exhibited seasonal trends, with certain months showing distinct patterns of performance. One of the most well-documented patterns is the "Sell in May and go away" phenomenon, suggesting that the period from November to April has historically brought significantly stronger gains in many major stock indices compared to the period from May to October. This pattern highlights the potential impact of seasonal investor sentiment and activities on market performance.
⚪ Day in week
Various studies have identified the "day-of-the-week effect," where certain days of the week, particularly Monday and Friday, show different average returns compared to other weekdays. Historically, Mondays have been associated with lower or negative average returns in many markets, a phenomenon often linked to the settlement of trades from the previous week and negative news accumulation over the weekend. Fridays, on the other hand, might exhibit positive bias as investors adjust positions ahead of the weekend.
⚪ Week in month
The performance of markets can also vary within different weeks of the month, with some studies suggesting a "week of the month effect." Typically, the first and the last week of the month may show stronger performance compared to the middle weeks. This pattern can be influenced by factors such as the timing of economic reports, monthly investment flows, and options and futures expiration dates which tend to cluster around these periods, affecting investor behavior and market liquidity.
█ How It Works
⚪ Day in Month
For each day of the month (1-31), the script calculates the average percentage change between the opening and closing prices of a trading instrument. This metric helps identify which days have historically been more volatile or profitable.
It uses arrays to store the sum of percentage changes for each day and the total occurrences of each day to calculate the average percentage change.
⚪ Month
The script calculates the overall gain for each month (January-December) by comparing the closing price at the start of a month to the closing price at the end, expressed as a percentage. This metric offers insights into which months might offer better trading opportunities based on historical performance.
Monthly gains are tracked using arrays that store the sum of these gains for each month and the count of occurrences to calculate the average monthly gain.
⚪ Day in Week
Similar to the day in the month analysis, the script evaluates the average percentage change between the opening and closing prices for each day of the week (Monday-Sunday). This information can be used to assess which days of the week are typically more favorable for trading.
The script uses arrays to accumulate percentage changes and occurrences for each weekday, allowing for the calculation of average changes per day of the week.
⚪ Week in Month
The script assesses the performance of each week within a month, identifying the gain from the start to the end of each week, expressed as a percentage. This can help traders understand which weeks within a month may have historically presented better trading conditions.
It employs arrays to track the weekly gains and the number of weeks, using a counter to identify which week of the month it is (1-4), allowing for the calculation of average weekly gains.
█ How to Use
Traders can use this indicator to identify patterns or trends in the instrument's performance. For example, if a particular day of the week consistently shows a higher percentage of bullish closes, a trader might consider this in their strategy. Similarly, if certain months show stronger performance historically, this information could influence trading decisions.
Identifying High-Performance Days and Periods
Day in Month & Day in Week Analysis: By examining the average percentage change for each day of the month and week, traders can identify specific days that historically have shown higher volatility or profitability. This allows for targeted trading strategies, focusing on these high-performance days to maximize potential gains.
Month Analysis: Understanding which months have historically provided better returns enables traders to adjust their trading intensity or capital allocation in anticipation of seasonally stronger or weaker periods.
Week in Month Analysis: Identifying which weeks within a month have historically been more profitable can help traders plan their trades around these periods, potentially increasing their chances of success.
█ Settings
Enable or disable the types of statistics you want to display in the table.
Table Size: Users can select the size of the table displayed on the chart, ranging from "Tiny" to "Auto," which adjusts based on screen size.
Table Position: Users can choose the location of the table on the chart
-----------------
Disclaimer
The information contained in my Scripts/Indicators/Ideas/Algos/Systems does not constitute financial advice or a solicitation to buy or sell any securities of any type. I will not accept liability for any loss or damage, including without limitation any loss of profit, which may arise directly or indirectly from the use of or reliance on such information.
All investments involve risk, and the past performance of a security, industry, sector, market, financial product, trading strategy, backtest, or individual's trading does not guarantee future results or returns. Investors are fully responsible for any investment decisions they make. Such decisions should be based solely on an evaluation of their financial circumstances, investment objectives, risk tolerance, and liquidity needs.
My Scripts/Indicators/Ideas/Algos/Systems are only for educational purposes!
ATH Drawdown Indicator by Atilla YurtsevenThe ATH (All-Time High) Drawdown Indicator, developed by Atilla Yurtseven, is an essential tool for traders and investors who seek to understand the current price position in relation to historical peaks. This indicator is especially useful in volatile markets like cryptocurrencies and stocks, offering insights into potential buy or sell opportunities based on historical price action.
This indicator is suitable for long-term investors. It shows the average value loss of a price. However, it's important to remember that this indicator only displays statistics based on past price movements. The price of a stock can remain cheap for many years.
1. Utility of the Indicator:
The ATH Drawdown Indicator provides a clear view of how far the current price is from its all-time high. This is particularly beneficial in assessing the magnitude of a pullback or retracement from peak levels. By understanding these levels, traders can gauge market sentiment and make informed decisions about entry and exit points.
2. Risk Management:
This indicator aids in risk management by highlighting significant drawdowns from the ATH. Traders can use this information to adjust their position sizes or set stop-loss orders more effectively. For instance, entering trades when the price is significantly below the ATH could indicate a higher potential for recovery, while a minimal drawdown from the ATH may suggest caution due to potential overvaluation.
3. Indicator Functionality:
The indicator calculates the percentage drawdown from the ATH for each trading period. It can display this data either as a line graph or overlaid on candles, based on user preference. Horizontal lines at -25%, -50%, -75%, and -100% drawdown levels offer quick visual cues for significant price levels. The color-coding of candles further aids in visualizing bullish or bearish trends in the context of ATH drawdowns.
4. ATH Level Indicator (0 Level):
A unique feature of this indicator is the 0 level, which signifies that the price is currently at its all-time high. This level is a critical reference point for understanding the market's peak performance.
5. Mean Line Indicator:
Additionally, this indicator includes a 'Mean Line', representing the average percentage drawdown from the ATH. This average is calculated over more than a thousand past bars, leveraging the law of large numbers to provide a reliable mean value. This mean line is instrumental in understanding the typical market behavior in relation to the ATH.
Disclaimer:
Please note that this ATH Drawdown Indicator by Atilla Yurtseven is provided as an open-source tool for educational purposes only. It should not be construed as investment advice. Users should conduct their own research and consult a financial advisor before making any investment decisions. The creator of this indicator bears no responsibility for any trading losses incurred using this tool.
Please remember to follow and comment!
Trade smart, stay safe
Atilla Yurtseven
StrategyDashboardLibrary ”StrategyDashboard”
Hey, everybody!
I haven’t done anything here for a long time, I need to get better ^^.
In my strategies, so far private, but not about that, I constantly use dashboards, which clearly show how my strategy is working out.
Of course, you can also find a number of these parameters in the standard strategy window, but I prefer to display everything on the screen, rather than digging through a bunch of boxes and dropdowns.
At the moment I am using 2 dashboards, which I would like to share with you.
1. monthly(isShow)
this is a dashboard with the breakdown of profit by month in per cent. That is, it displays how much percentage you made or lost in a particular month, as well as for the year as a whole.
Parameters:
isShow (bool) - determine allowance to display or not.
2. total(isShow)
The second dashboard displays more of the standard strategy information, but in a table format. Information from the series “number of consecutive losers, number of consecutive wins, amount of earnings per day, etc.”.
Parameters:
isShow (bool) - determine allowance to display or not.
Since I prefer the dark theme of the interface, now they are adapted to it, but in the near future for general convenience I will add the ability to adapt to light.
The same goes for the colour scheme, now it is adapted to the one I use in my strategies (because the library with more is made by cutting these dashboards from my strategies), but will also make customisable part.
If you have any wishes, feel free to write in the comments, maybe I can implement and add them in the next versions.
Supertrend Forecast - vanAmsenHello everyone!
I am thrilled to present the "vanAmsen - Supertrend Forecast", an advanced tool that marries the simplicity of the Supertrend with comprehensive statistical insights.
Before we dive into the functionalities of this indicator, it's essential to understand its foundation and theory.
The Theory:
What exactly is the Supertrend?
The Supertrend, at its core, is a momentum oscillator. It's a tool that provides buy and sell signals based on the prevailing market trend. The underlying principle is straightforward: by analyzing average price data and volatility over a period, the Supertrend gives us a line that represents the trend direction.
However, trading isn't just about identifying trends; it's about understanding their strength, potential profitability, and historical accuracy. This is where statistics come into play. By incorporating statistical analysis into the Supertrend, we can gain deeper insights into the market's behavior.
Description:
The "vanAmsen - Supertrend Forecast" isn't just another Supertrend indicator. It's a comprehensive tool designed to offer traders a holistic view of market trends, backed by robust statistical analysis.
Key Features:
- Supertrend Line: A visual representation of the current market direction.
- Win Rate & Expected Return: Delve into the historical accuracy and profitability of the prevailing trend.
- Average Percentage Change: Understand the average price fluctuation for both winning and losing trends.
- Forecast Lines: Project future price movements based on historical data, providing a roadmap for potential scenarios.
- Interactive Table: A concise table in the top right, offering a snapshot of all vital metrics at a glance.
Usage:
- The bullish Supertrend line adopts an Aqua hue, indicating potential upward momentum.
- In contrast, the bearish line is painted in Orange, suggesting potential downtrends.
- Customize your chart by toggling labels, tables, and lines according to preference.
Recommendation:
The "vanAmsen - Supertrend Forecast" is undoubtedly a powerful tool in a trader's arsenal. However, it's imperative to combine it with other technical analysis tools and sound risk management practices. It's always prudent to backtest strategies with historical data before embarking on live trading.
Machine Learning: Trend Pulse⚠️❗ Important Limitations: Due to the way this script is designed, it operates specifically under certain conditions:
Stocks & Forex : Only compatible with timeframes of 8 hours and above ⏰
Crypto : Only works with timeframes starting from 4 hours and higher ⏰
❗Please note that the script will not work on lower timeframes.❗
Feature Extraction : It begins by identifying a window of past price changes. Think of this as capturing the "mood" of the market over a certain period.
Distance Calculation : For each historical data point, it computes a distance to the current window. This distance measures how similar past and present market conditions are. The smaller the distance, the more similar they are.
Neighbor Selection : From these, it selects 'k' closest neighbors. The variable 'k' is a user-defined parameter indicating how many of the closest historical points to consider.
Price Estimation : It then takes the average price of these 'k' neighbors to generate a forecast for the next stock price.
Z-Score Scaling: Lastly, this forecast is normalized using the Z-score to make it more robust and comparable over time.
Inputs:
histCap (Historical Cap) : histCap limits the number of past bars the script will consider. Think of it as setting the "memory" of model—how far back in time it should look.
sampleSpeed (Sampling Rate) : sampleSpeed is like a time-saving shortcut, allowing the script to skip bars and only sample data points at certain intervals. This makes the process faster but could potentially miss some nuances in the data.
winSpan (Window Size) : This is the size of the "snapshot" of market data the script will look at each time. The window size sets how many bars the algorithm will include when it's measuring how "similar" the current market conditions are to past conditions.
All these variables help to simplify and streamline the k-NN model, making it workable within limitations. You could see them as tuning knobs, letting you balance between computational efficiency and predictive accuracy.
Normal Distribution CurveThis Normal Distribution Curve is designed to overlay a simple normal distribution curve on top of any TradingView indicator. This curve represents a probability distribution for a given dataset and can be used to gain insights into the likelihood of various data levels occurring within a specified range, providing traders and investors with a clear visualization of the distribution of values within a specific dataset. With the only inputs being the variable source and plot colour, I think this is by far the simplest and most intuitive iteration of any statistical analysis based indicator I've seen here!
Traders can quickly assess how data clusters around the mean in a bell curve and easily see the percentile frequency of the data; or perhaps with both and upper and lower peaks identify likely periods of upcoming volatility or mean reversion. Facilitating the identification of outliers was my main purpose when creating this tool, I believed fixed values for upper/lower bounds within most indicators are too static and do not dynamically fit the vastly different movements of all assets and timeframes - and being able to easily understand the spread of information simplifies the process of identifying key regions to take action.
The curve's tails, representing the extreme percentiles, can help identify outliers and potential areas of price reversal or trend acceleration. For example using the RSI which typically has static levels of 70 and 30, which will be breached considerably more on a less liquid or more volatile asset and therefore reduce the actionable effectiveness of the indicator, likewise for an asset with little to no directional volatility failing to ever reach this overbought/oversold areas. It makes considerably more sense to look for the top/bottom 5% or 10% levels of outlying data which are automatically calculated with this indicator, and may be a noticeable distance from the 70 and 30 values, as regions to be observing for your investing.
This normal distribution curve employs percentile linear interpolation to calculate the distribution. This interpolation technique considers the nearest data points and calculates the price values between them. This process ensures a smooth curve that accurately represents the probability distribution, even for percentiles not directly present in the original dataset; and applicable to any asset regardless of timeframe. The lookback period is set to a value of 5000 which should ensure ample data is taken into calculation and consideration without surpassing any TradingView constraints and limitations, for datasets smaller than this the indicator will adjust the length to just include all data. The labels providing the percentile and average levels can also be removed in the style tab if preferred.
Additionally, as an unplanned benefit is its applicability to the underlying price data as well as any derived indicators. Turning it into something comparable to a volume profile indicator but based on the time an assets price was within a specific range as opposed to the volume. This can therefore be used as a tool for identifying potential support and resistance zones, as well as areas that mark market inefficiencies as price rapidly accelerated through. This may then give a cleaner outlook as it eliminates the potential drawbacks of volume based profiles that maybe don't collate all exchange data or are misrepresented due to large unforeseen increases/decreases underlying capital inflows/outflows.
Thanks to @ALifeToMake, @Bjorgum, vgladkov on stackoverflow (and possibly some chatGPT!) for all the assistance in bringing this indicator to life. I really hope every user can find some use from this and help bring a unique and data driven perspective to their decision making. And make sure to please share any original implementaions of this tool too! If you've managed to apply this to the average price change once you've entered your position to better manage your trade management, or maybe overlaying on an implied volatility indicator to identify potential options arbitrage opportunities; let me know! And of course if anyone has any issues, questions, queries or requests please feel free to reach out! Thanks and enjoy.
Linear Correlation Coefficient W/ MAs and Significance TestsThis Linear CC takes into account the log-normal distribution of stock prices and performs Pearson correlation on that data set. It also smoothens the results into an easy to read oscillator, and performs a two-tail t-test on the correlation coefficient data (with a = 0.05) to determine the significance of the coefficients. Significant results are shown in a solid yellow color while insignificant results are shown in a dark yellow color (you can eyeball this with a normal LCC by looking at results around -0.5 to +0.5).
Two MAs are provided as well for a quick trend analysis. You can reduce the lookback period, but it defaults to 31 for the sake of statistical standards.
Autocorrelation - The Quant ScienceAutocorrelation - The Quant Science it is an indicator developed to quickly calculate the autocorrelation of a historical series. The objective of this indicator is to plot the autocorrelation values and highlight market moments where the value is positive and exceeds the attention threshold.
This indicator can be used for manual analysis when a trader needs to search for new price patterns within the historical series or to create complex formulas in estimating future prices.
What is autocorrelation?
Autocorrelation in trading is a statistical measure used to determine the presence of a relationship or pattern of dependence between values in a financial time series over time. It represents the correlation of past values in a series with its future values. In other words, autocorrelation in trading aims to identify if there are systematic relationships between the past prices or returns of a security or market and its future prices or returns. This analysis can be helpful in identifying patterns or trends that can be leveraged for informed trading decisions. The presence of autocorrelation may suggest that market prices or returns follow a certain pattern or trend over time.
Limitations of the model
It is important to note that autocorrelation does not necessarily imply a causal relationship between past and future values. Other variables or market factors may influence the dynamics of prices or returns, and therefore autocorrelation could be merely a random coincidence. Therefore, it is essential to carefully evaluate the results of autocorrelation analysis along with other information and trading strategies to make informed decisions.
How to use
The usage is very simple, you just need to add it to the current chart to activate the indicator.
From the user interface, you can manage two important features:
1. Lenght: the delay period applied to the historical series during the autocorrelation calculation can be managed from the user interface. By default, it is set to 20, which means that the autocorrelation ratio within the historical series is calculated with a delay of 20 bars.
2. Threshold: the threshold value that the autocorrelation level must meet can be managed from the user interface. By default, it is set to 0.50, which means that the autocorrelation value must be higher than this threshold to be considered valid and displayed on the chart.
3. Bar color: the color used to display the autocorrelation data and highlight the bars when autocorrelation is valid can be managed from the user interface.
To set up the chart
We recommend disabling the 'wick' and 'border' of the candlesticks from the chart settings for a high-quality user experience.
Recessions & crises shading (custom dates & stats)Shades your chart background to flag events such as crises or recessions, in similar fashion to what you see on FRED charts. The advantage of this indicator over others is that you can quickly input custom event dates as text in the menu to analyse their impact for your specific symbol. The script automatically labels, calculates and displays the peak to through percentage corrections on your current chart.
By default the indicator is configured to show the last 6 US recessions. If you have custom events which will benefit others, just paste the input string in the comments below so one can simply copy/paste in their indicator.
Example event input (No spaces allowed except for the label name. Enter dates as YYYY-MM-DD.)
2020-02-01,2020-03-31,COVID-19
2007-12-01,2009-05-31,Subprime mortgages
2001-03-01,2001-10-30,Dot-com bubble
1990-07-01,1991-03-01,Oil shock
1981-07-01,1982-11-01,US unemployment
1980-01-01,1980-07-01,Volker
1973-11-01,1975-03-01,OPEC
Days in rangeThis script is a little widget that I made to do some homework on the VIX.
As you can see in the chart I was analyzing the 2008 market crash and the stats that followed it after until the market started to recover.
You can see that theory in my "Ideas" tab.
This is an interactive set of lines that you can use to count the the bars inside and outside of your chosen range, and the percentage outside that range.
You should initially enter the price range of your product in the menu and set some arbitrary dates that you can easily see on your chart.
Drag and drop the lines around to suit what price and the dates you are analyzing.
The table will display the bar count inside and outside of the range, the total bars, and the percentage outside that range.
I personally used this as a tool to study the overall average of the product, compared with the behavior during major market events.
It is currently my opinion that post 2020 analysis needs to take into account the behavior of any given product prior to 2020 when the
VIX was in its comfort zone. Not to say that a price valuation hasn't been set, but that the movement to that price was outside of "Normal Market Conditions,"
and the time factor to return to that value might be skewed. Other factors would need to be considered at that point pertaining to your specific product or corelating indicator.
I could see this tool being useful to Forex and commodities traders. But that isn't my field so that that for what it is. I do think it would perform best on something that is more
pegged to a price range. I personally would use it on product's, like the VIX, that I use as an indicator product. That is what it was designed for.
But I suppose it could be used for Mean price and time related analysis, maybe with a Vwap, SMA or other breakout style indicators.
Volume analysis might be pretty sporty. Possibly time patterns... the possibilities could be endless. Or... limited.
I am publishing this for my trade group so that it can be tinkered with to find other helpful ways to use it.
If anyone finds something interesting with other indicators, please drop a comment below and I could consider creating a script to integrate with this tool.
Oscillator: Which follows Normal Distribution?When doing machine learning using oscillators, it would be better if the oscillators were normally distributed.
So I analyzed the distribution of oscillators.
The value of the oscillator was divided into 50 groups each from 0 to 100.
ex) if rsi value is 45.43 -> group_44, 58.23 -> group_58
Ocscillators : RSI, Stoch, MFI, WT, RVI, etc....
Caution: The normal distribution was verified through an empirical formula.
Smoothing R-Squared ComparisonIntroduction
Heyo guys, here I made a comparison between my favorised smoothing algorithms.
I chose the R-Squared value as rating factor to accomplish the comparison.
The indicator is non-repainting.
Description
In technical analysis, traders often use moving averages to smooth out the noise in price data and identify trends. While moving averages are a useful tool, they can also obscure important information about the underlying relationship between the price and the smoothed price.
One way to evaluate this relationship is by calculating the R-squared value, which represents the proportion of the variance in the price that can be explained by the smoothed price in a linear regression model.
This PineScript code implements a smoothing R-squared comparison indicator.
It provides a comparison of different smoothing techniques such as Kalman filter, T3, JMA, EMA, SMA, Super Smoother and some special combinations of them.
The Kalman filter is a mathematical algorithm that uses a series of measurements observed over time, containing statistical noise and other inaccuracies, and produces estimates of unknown variables that tend to be more accurate than those based on a single measurement.
The input parameters for the Kalman filter include the process noise covariance and the measurement noise covariance, which help to adjust the sensitivity of the filter to changes in the input data.
The T3 smoothing technique is a popular method used in technical analysis to remove noise from a signal.
The input parameters for the T3 smoothing method include the length of the window used for smoothing, the type of smoothing used (Normal or New), and the smoothing factor used to adjust the sensitivity to changes in the input data.
The JMA smoothing technique is another popular method used in technical analysis to remove noise from a signal.
The input parameters for the JMA smoothing method include the length of the window used for smoothing, the phase used to shift the input data before applying the smoothing algorithm, and the power used to adjust the sensitivity of the JMA to changes in the input data.
The EMA and SMA techniques are also popular methods used in technical analysis to remove noise from a signal.
The input parameters for the EMA and SMA techniques include the length of the window used for smoothing.
The indicator displays a comparison of the R-squared values for each smoothing technique, which provides an indication of how well the technique is fitting the data.
Higher R-squared values indicate a better fit. By adjusting the input parameters for each smoothing technique, the user can compare the effectiveness of different techniques in removing noise from the input data.
Usage
You can use it to find the best fitting smoothing method for the timeframe you usually use.
Just apply it on your preferred timeframe and look for the highlighted table cell.
Conclusion
It seems like the T3 works best on timeframes under 4H.
There's where I am active, so I will use this one more in the future.
Thank you for checking this out. Enjoy your day and leave me a like or comment. 🧙♂️
---
Credits to:
▪@loxx – T3
▪@balipour – Super Smoother
▪ChatGPT – Wrote 80 % of this article and helped with the research
Premium Linear Regression - The Quant ScienceThis script calculates the average deviation of the source data from the linear regression. When used with the indicator, it can plot the data line and display various pieces of information, including the maximum average dispersion around the linear regression.
The code includes various user configurations, allowing for the specification of the start and end dates of the period for which to calculate linear regression, the length of the period to use for the calculation, and the data source to use.
The indicator is designed for multi-timeframe use and to facilitate analysis for traders who use regression models in their analysis. It displays a green linear regression line when the price is above the line and a red line when the price is below. The indicator also highlights areas of dispersion around the regression using circles, with bullish areas shown in green and bearish areas shown in red.
Financial Data Spreadsheet [By MUQWISHI]The Financial Data Spreadsheet indicator displays tables in the form of a spreadsheet containing a set of selected financial performances of a company within the most recent reported period. Analyzing Financial data is one of the classic methods to evaluate whether the company’s stock price is overvalued or undervalued based on its income statement, balance sheet, and cash flow statement. This indicator might be practical to investors to collect needed data of a company to analyze and compare it with other companies on a TradingView chart or print it in spreadsheet form.
█ OVERVIEW
█ BEST PRACTICES
Due to strict limitations on calling request.financial() function, I tried to develop the table with the best ways to be more dynamic to move and the ability to join multiple tables into a spreadsheet. Users can add up to 20 instruments and 2 financial metrics per table. However, it’s possible to add many tables with other financial metrics, then connect them to the main table.
Credits: The idea of joining multiple tables inspired by @QuantNomad Screener for 40+ instruments
█ INDICATOR SETTINGS
1- Moving Table toward right-left up-down from its origin.
2- Hiding Column Title checkmark. Useful for adding a joined table underneath with additional instruments.
3- Hiding Instruments Title checkmark. Useful for adding a joined table on the right with other financial metrics.
4- Shade Alternate Rows checkmark. I believe it’ll make the table easier to read.
5- Selecting Financial Period. (Year, Quarter).
6- Entering a currency.
7- Choosing a financial ID for each column. There’re over 200 financial IDs. Source: What financial data is available in Pine? — TradingView
8- Optional to highlight values in between.
9- Entering the ticker’s symbol with the ability to activate/deactivate.
█ TIP
For best technical performance, use the indicator in a 1D timeframe.
Please let me know if you have any questions.
Thank you.