Sync Frame (MTF Charts) [Kioseff Trading]Hello!
This indicator "Sync Frame" displays various lower timeframe charts for the asset on your screen!
5 lower timeframe candle charts shown
Timeframes auto-calculated using the new timeframe.from_seconds() function
Heikin-Ashi candles available
Baseline chart type available
Dynamic Scaling for ease of use
User customizable timeframes
Simple script (:
The image above shows the baseline chart type.
Time image above shows a traditional candlestick chart.
The image above shows a hekin-ashi chart.
The image above shows the indicator when nearly zoomed in as much as possible. The lower timeframe charts adjust to my chart positioning.
The image above shows my screen fully zoomed out; the lower timeframe charts adjust in both height and width to accommodate my chart positioning!
Thank you for checking this out (:
Statistics
Blockchain FundamentalThis indicator is made for traders to harness fundamental blockchain data for better decision-making. Unlike traditional tools, this indicator doesn't depend on standard technical indicators. It offers a novel perspective by focusing on core blockchain metrics like capitalization, miner activity, and other intrinsic data elements. I've designed a distinct scoring logic, exclusive to BF, ensuring it's user-friendly and provides actionable insights for traders at all levels.
Mainly created for Bitcoin , but can be applied to any other crypto assets in cost of losing some metrics in the analysis.
Ethereum chart:
Features:
Customizable Moving Averages:
Choose from an array of moving averages, with the flexibility to adjust the length for a tailored analysis, aiding in pinpointing asset trends.
Blockchain Metrics Integration:
Incorporates a range of blockchain metrics such as Market Cap to Realised Cap ratio, Spent Output Profit Ratio, ATH Drawdown, and more.
Blockchain Metrics Evaluation:
Each metric can be toggled on/off to customize the analysis. Using default settings, traders can use all of the metrics combined.
Every metric is essentially evaluated on a scale from -100 to 100 and then combined with others. If any metric is uncertain about its direction (equals to 0), then the score of it is not accounted in a final calculation.
Kalman Filter:
This indicator offers the option to apply a Kalman filter to the signals, enhancing the smoothness and accuracy of the indicator’s output. This is my approach to mitigate the noise in the final output.
Signal Oscillator:
Displays the aggregated score of all selected blockchain metrics.
Offers visual signals with adjustable upper and lower bounds for easy interpretation based on particular asset observation.
Visual Elements:
Signal Oscillator:
A visual representation of the aggregated blockchain fundamental score.
(White line for a raw calculation, orange line for kalman-filtered one)
Signal Counter:
Displays the count of metrics currently being considered in the fundamental score calculation. (grey line at the middle of an indicator)
Buy/Sell Signal Coloring:
The background color changes to indicate potential buying or selling opportunities based on user-defined bounds.
Usage:
Analysis:
Use the signal oscillator to identify potential market tops and bottoms based on blockchain fundamental data.
Adjust the bounds to customize the sensitivity of buy/sell signals.
Customization:
Enable/disable specific blockchain metrics to tailor the indicator to your analytical needs.
Adjust the moving average type and length for better analysis.
Integration:
Combine with other technical indicators to create a comprehensive trading strategy.
Utilize in conjunction with volume and price action analysis for enhanced decision-making. Every output could be used in traders custom strategies and indicators.
IU Probability CalculatorHow This Script Works:
1. This script calculate the probability of price reaching a user-defined price level within one candle with the help Normal Distribution Probability Table.
2. Normal Distribution Probability Table is use for calculating probability of events, it's very powerful for calculation of probability and this script is fully based on that table.
3. It takes the Average True Range value or Standard Deviation value of past user-defined length bar.
4. After that it take this formula z = ( price_level - close ) / (ATR or Standard Deviation) and return the value for z, for the bearish side it take z = (close - price level) / (ATR or Standard Deviation ) formula.
5. Once we have the z it look into Normal Distribution Probability Table and match the value.
6. Now the value of z is multiple buy 100 in order to make it look in percentage term.
7. After that this script subtract the final value with 100 because probability always comes under 100%
8. finally we plot the probability at the bottom of the chart the red line indicates "The probability of price not reaching that price level", While the green line indicates "Probability of price Reaching that level " .
9. This script will work fine for both of the directions
How This Is Useful For The User:
1. With this script user can know the probability of price reaching the certain level within one candle for both Directions .
2. This is useful while creating options hedging strategies
3. This can be helpful for deciding stop loss level.
4. It's useful for scalpers for managing their traders and it can be use by binary option traders.
IU Average move How The Script Works :
1. This script calculate the average movement of the price in a user defined custom session and plot the data in a table from on top left corner of the chart.
2. The script takes highest and lowest value of that custom session and store their difference into an array.
3. Then the script average the array thus gets the average price.
4. Addition to that the script converter the price pip change into percentage in order to calculate the value in percentage form.
5. This script is pure price action based the script only take price value and doesn't take any indicator for calculation.
6. The script works on every type of market.
7. If the session is invalid it returns nothing
8. The background color, text color and transparency is changeable.
How User Can Benefit From This Script:
1. User can understand the volatility of any session that he/she wish to trade.
2. It can be helpful for understanding the average price moment of any tradeble asset.
3. It will give the average price movement both in percentage and points bases.
4. By understanding the volatility user can adjust his stop loss or take profit with respect his risk management.
Quadratic & Linear Time Series Regression [SS]Hey everyone,
Releasing the Quadratic/Linear Time Series regression indicator.
About the indicator:
Most of you will be familiar with the conventional linear regression trend boxes (see below):
This is an awesome feature in Tradingview and there are quite a few indicators that follow this same principle.
However, because of the exponential and cyclical nature of stocks, linear regression tends to not be the best fit for stock time series data. From my experience, stocks tend to fit better with quadratic (or curvlinear) regression, which there really isn't a lot of resources for.
To put it into perspective, let's take SPX on the 1 month timeframe and plot a linear regression trend from 1930 till now:
You can see that its not really a great fit because of the exponential growth that SPX has endured since the 1930s. However, if we take a quadratic approach to the time series data, this is what we get:
This is a quadratic time series version, extended by up to 3 standard deviations. You can see that it is a bit more fitting.
Quadratic regression can also be helpful for looking at cycle patterns. For example, if we wanted to plot out how the S&P has performed from its COVID crash till now, this is how it would look using a linear regression approach:
But this is how it would look using the quadratic approach:
So which is better?
Both linear regression and quadratic regression are pivotal and important tools for traders. Sometimes, linear regression is more appropriate and others quadratic regression is more appropriate.
In general, if you are long dating your analysis and you want to see the trajectory of a ticker further back (over the course of say, 10 or 15 years), quadratic regression is likely going to be better for most stocks.
If you are looking for short term trades and short term trend assessments, linear regression is going to be the most appropriate.
The indicator will do both and it will fit the linear regression model to the data, which is different from other linreg indicators. Most will only find the start of the strongest trend and draw from there, this will fit the model to whatever period of time you wish, it just may not be that significant.
But, to keep it easy, the indicator will actually tell you which model will work better for the data you are selecting. You can see it in the example in the main chart, and here:
Here we see that the indicator indicates a better fit on the quadratic model.
And SPY during its recent uptrend:
For that, let's take a look at the Quadratic Vs the Linear, to see how they compare:
Quadratic:
Linear:
Functions:
You will see that you have 2 optional tables. The statistics table which shows you:
The R Squared to assess for Variance.
The Correlation to assess for the strength of the trend.
The Confidence interval which is set at a default of 1.96 but can be toggled to adjust for the confidence reading in the settings menu. (The confidence interval gives us a range of values that is likely to contain the true value of the coefficient with a certain level of confidence).
The strongest relationship (quadratic or linear).
Then there is the range table, which shows you the anticipated price ranges based on the distance in standard deviations from the mean.
The range table will also display to you how often a ticker has spent in each corresponding range, whether that be within the anticipated range, within 1 SD, 2 SD or 3 SD.
You can select up to 3 additional standard deviations to plot on the chart and you can manually select the 3 standard deviations you want to plot. Whether that be 1, 2, 3, or 1.5, 2.5 or 3.5, or any combination, you just enter the standard deviations in the settings menu and the indicator will adjust the price targets and plotted bands according to your preferences. It will also count the amount of time the ticker spent in that range based on your own selected standard deviation inputs.
Tips on Use:
This works best on the larger timeframes (1 hour and up), with RTH enabled.
The max lookback is 5,000 candles.
If you want to ascertain a longer term trend (over years to months), its best to adjust your chart timeframe to the weekly and/or monthly perspective.
And that's the indicator! Hopefully you all find it helpful.
Let me know your questions and suggestions below!
Safe trades to all!
[dharmatech] Area Under Yield Curve : USThis indicator displays the area under the U.S. Treasury Securities yield curve.
If you compare this to SP:SPX , you'll see that there are large periods where they are inversely related. Other times, they track together. When the move together, watch out for the expected and eventual divergence.
By default, this indicator will show up in a separate pane. If you move it to an existing pane (e.g. along side SP:SPX ) you'll need to move it to a different price scale.
The area under the yield curve is a quick way to see if the overall yield curve moved up or down. Generally speaking, increasing yields isn't good for markets, unless there is some other stimulus going on simultaneously.
The following treasury securities are used in this calculation:
FRED:DGS1MO (1 month)
FRED:DGS3MO (3 month)
FRED:DGS6MO (6 month)
FRED:DGS1 (1 year)
FRED:DGS2 (2 year)
FRED:DGS3 (3 year)
FRED:DGS5 (5 year)
FRED:DGS7 (7 year)
FRED:DGS10 (10 year)
FRED:DGS20 (20 year)
FRED:DGS30 (30 year)
Tops & Bottoms - Time of Day Report█ OVERVIEW
The indicator tracks and reports the percentage of occurrence of daily tops and bottoms by the time of the day.
█ CONCEPTS
At certain times during the trading day, the market reverses and marks the high or low of the day. Tops and bottoms are vital when entering a trade, as they will decide if you are catching the train or being straight offside. They are equally crucial when exiting a position, as they will determine if you are closing at the optimal price or seeing your unrealized profits vanish.
This indicator is before all for educational purposes. It aims to make the knowledge available to all traders, facilitate understanding of the various markets, and ultimately get to know your trading pairs by heart.
Tops and bottoms percentage of occurrence on EURGBP (London time).
Up days versus down days on EURUSD (London time).
█ FEATURES
Selectable time zones
Present the column chart in your local time zone (or other market participants).
Configurable time range filter
Select the period to report from.
Day type filter
Analyze all days, or filter only up days or down days.
█ HOW TO USE
Plot the indicator and visit the 1-hour or 30-minute timeframe.
█ NOTES
Timeframe choice
The 1-hour timeframe produces a higher number of days sampled. Prefer the usage of the 30-minute timeframe when your market starts at 9:30 AM.
Daylight Saving Time (DST)
The exchange time and geographical time zone options may observe Daylight Saving Time, unlike UTC+0.
Tick Weighted Average Price %BTick Weighted Average Price %B
"TiWAP %B" is an indicator that tracks the NYSE TICK by default and plots price location in relation to the tick weighted average price based only off of extreme TICK movement. NASDAQ TICK is also supported and future updates may add others if they provide value, or if requested.
This utilizes same calculation as TiWAP indicator already published, but removes the need to have it overlaying price to keep things tidy :)
What makes this different?
Quite simply there isn't another indicator that plots weighted average price based on TICK movement as done here, this is showing the correlation between the entire markets volatile price movement and the charted security. It provides a sense of established fair value given the entire NYSE/NASDAQ, given the automated nature of the markets there's a strong correlation between highly liquid ETFs/Indexes and the whole market.
How to use
As price is affected by NYSE the study will reveal location of price as it relates to TiWAP, use location to find reversals from rejections or bounces of standard deviations.
As price is affected by market volatility look to see the weighted price adjust to actual price and combine with other trading strategies to take advantage of the data. Rejections and bounces near standard deviations as well as the weighted average price line can provide excellent trade setups, or they could be utilized in advanced options strategies such as straddles, strangles, iron condors, etc.
Anchor points can be utilized to track how the market is adjusting broad value for the week, month, quarter, etc. The higher timeframe based anchor points will need higher periods for the chart or a max bars lookback error may occur.
Sensitivity should be adjusted as changes in TICK occur, this is commonly correlated with NYSE adjustments but the tooltip provides some guidance on value selection based on current conventional wisdom.
Show Target Level Relation
Turn on "Show Target Level Relation" to observe how current price is moving in relation to previous TiWAP range. For example if %B is configured for session, enabling this feature will reveal price rejecting and reclaim aspects of previous session %B range, works on any anchorage selected so long as resolution permits.
Fill %B As Cloud
By special request, this will render %B as a sentiment cloud which will aid in quick review of price to TiWAP relation being in buy side or sell side ranges, use this to easily spot exhaustion or continuation.
Markets
TICK tracks the entire market and as such whatever the entire market is doing will most likely apply to any individual security charted so give this a shot with anything you trade and let me know your results :)
Usage Conditions
Currently I'm finding the most success with this weighted average price on various intra-day timeframes, but anchored on weekly or higher and utilizing other timeframes may net some interesting swing trading opportunities.
Special thanks to MrChach for the original idea as well as discussions and debugging sessions :)
Monte Carlo Simulation - Your Strategy [Kioseff Trading]Hello!
This script “Monte Carlo Simulation - Your Strategy” uses Monte Carlo simulations for your inputted strategy returns or the asset on your chart!
Features
Monte Carlo Simulation: Performs Monte Carlo simulation to generate multiple future paths.
Asset Price or Strategy: Can simulate either future asset prices based on historical log returns or a specific trading strategy's future performance.
User-Defined Input: Allows you to input your own historical returns for simulation.
Statistical Methods: Offers two simulation methods—Gaussian (Normal) distribution and Bootstrapping.
Graphical Display: Provides options for graphical representation, including line plots and histograms.
Cumulative Probability Target: Enables setting a user-defined cumulative probability target to quantify simulation results.
Adjustable Parameters: Offers numerous user-adjustable settings like number of simulations, forecast length, and more.
Historical Data Points: Option to specify the amount of historical data to be used in the simulation (price).
Custom Binning: Allows you to select the binning method for histograms, with options like Sturges, Rice, and Square Root.
Best/Worst Case: Allows you to show only the best case / worst case outcome (range) for all simulations!
Scatterplot: allows you to show up to 1000 potential outcomes for a specified trade number (or bars forward price endpoint) using a scatter plot.
The image above shows the primary components of the indicator!
The image above shows the best/worst case outcome feature in action!
The image above shows a "fun feature" where 1000 simulated end points for a 15-bar price trajectory are shown as a scatter plot!
How To Perform a Monte Carlo Simulation On Your Strategy
Really, you can input any data into the indicator it will perform a Monte Carlo Simulation on it :D
The following instructions show how to export your strategy results from TradingView to an Excel File, copy the data, and input it into the indicator.
However , you are not limited to following this method!
Wherever your strategy results are stored, simply copy and paste them into the indicator text area in the settings and simulations will begin.
Returns Should Follow This Format
1
3
-3
2
-5
The numbers are presented as a single column. No commas or separators used.
The numbers above are in sequential order. A return of "1" for the first trade and a return of "-5" for the last trade. Your strategy returns will likely be in sequential order already so don't worry too much about this (:
How To Perform a Monte Carlo Simulation On Your TradingView Strategy With Excel Data
Export your strategy returns to an excel file using TradingView
Navigate to your downloads folder to column G "Profit"
Click the column and press CTRL + SPACE to highlight the entire column
Press CTRL + C to copy the entire column
Open this indicator's settings and paste the returns into the text area
The image above illustrates the process!
Notes on Inputting Returns
*Must input your returns without a separate as a vertical list
*The initial text area can only hold so many return values. If your list of trades is large you can input additional returns into two additional text areas at the bottom of the indicator settings.
That should be it; thank you for checking this out!
Xeeder - US Government Bonds AnalysisXeeder - US Government Bonds Analysis (USBA)
The "Xeeder - US Government Bonds Analysis" (USBA) is a comprehensive tool designed to assist traders in analyzing the spread, historical volatility, and correlation between two different U.S. Government Bonds. This indicator is crucial for understanding the relative performance and risk factors between two bond assets.
Details of the Indicator:
Bond Input Settings: This feature allows traders to select two different U.S. Government Bonds from a dropdown list. The bonds range from 1-month to 30-year maturities.
Timeframe Settings: Traders can choose the timeframe for the analysis, such as Daily, Weekly, etc.
Moving Average (MA) Settings: The indicator offers various types of moving averages like SMA, EMA, WMA, etc., for calculating the spread's moving average. Traders can also specify the length of the moving average.
Spread Calculation: The indicator calculates the spread between the selected bonds and plots it on the chart.
Historical Volatility: The indicator calculates and plots the historical volatility of the spread, which is useful for risk assessment.
Correlation Coefficient: This feature calculates the correlation between the two selected bonds over a specified period.
How to Use the Indicator:
Select Bonds: Choose two U.S. Government Bonds from the dropdown list that you are interested in analyzing.
Choose Timeframe: Select the timeframe that aligns with your trading or investment strategy.
Configure MA Settings: Adjust the type and length of the moving average according to your needs.
Analyze Plots: Observe the plotted spread, its moving average, historical volatility, and correlation coefficient to gain insights into the bonds' relative performance and risk factors.
Interpret Data: Use the plotted data to make informed decisions about bond trading or hedging strategies.
Example of Usage:
As a trader focused on swing trading and strategy development, you can use the USBA indicator to:
Select Bonds: Choose bonds that you believe will show significant spread changes based on your macroeconomic and geopolitical analysis.
Adjust Settings: Configure the MA settings to suit your trading strategy.
Analysis and Comparison: Examine the spread, historical volatility, and correlation to identify potential trading opportunities or hedging strategies.
Content Creation: Use the insights gained to write compelling articles on bond market trends, risks, and opportunities, enriching your financial journalism portfolio.
Remember, the USBA indicator is a versatile tool that provides a multi-faceted analysis of U.S. Government Bonds. Always consider your broader trading strategy and market conditions when using this tool.
MeanReversion - LogReturn/Vola ZScoreShows the z-Score of log-return (blue line) and volatility (black line). In statistics, the z-score is the number of standard deviations by which a value of a raw score is above or below the mean value.
This indicator aggregates z-score based on two indicators:
MeanReversion by Logarithmic Returns
MeanReversion by Volatility
Change the time period in bars for longer or shorter time frames. At a daily chart 252 mean on trading year, 21 mean one trading month.
Seasonal Trend by LogReturnSeasonal trend in terms of stocks refers to typical and recurring patterns in stock prices that happen at a specific time of the year. There are many theories and beliefs regarding seasonal trends in the financial markets, and some traders use these patterns to guide their investment decisions.
This indicator calculates the trend by "Daily" logarithmic returns of the past years.
So, you should use this indicator with a "Daily" mainchart.
Note: If you select more years in the past than data is available, the line turns red.
Statistical Package for the Trading Sciences [SS]
This is SPTS.
It stands for Statistical Package for the Trading Sciences.
Its a play on SPSS (Statistical Package for the Social Sciences) by IBM (software that, prior to Pinescript, I would use on a daily basis for trading).
Let's preface this indicator first:
This isn't so much an indicator as it is a project. A passion project really.
This has been in the works for months and I still feel like its incomplete. But the plan here is to continue to add functionality to it and actually have the Pinecoding and Tradingview community contribute to it.
As a math based trader, I relied on Excel, SPSS and R constantly to plan my trades. Since learning a functional amount of Pinescript and coding a lot of what I do and what I relied on SPSS, Excel and R for, I use it perhaps maybe a few times a week.
This indicator, or package, has some of the key things I used Excel and SPSS for on a daily and weekly basis. This also adds a lot of, I would say, fairly complex math functionality to Pinescript. Because this is adding functionality not necessarily native to Pinescript, I have placed most, if not all, of the functionality into actual exportable functions. I have also set it up as a kind of library, with explanations and tips on how other coders can take these functions and implement them into other scripts.
The hope here is that other coders will take it, build upon it, improve it and hopefully share additional functionality that can be added into this package. Hence why I call it a project. Okay, let's get into an overview:
Current Functions of SPTS:
SPTS currently has the following functionality (further explanations will be offered below):
Ability to Perform a One-Tailed, Two-Tailed and Paired Sample T-Test, with corresponding P value.
Standard Pearson Correlation (with functionality to be able to calculate the Pearson Correlation between 2 arrays).
Quadratic (or Curvlinear) correlation assessments.
R squared Assessments.
Standard Linear Regression.
Multiple Regression of 2 independent variables.
Tests of Normality (with Kurtosis and Skewness) and recognition of up to 7 Different Distributions.
ARIMA Modeller (Sort of, more details below)
Okay, so let's go over each of them!
T-Tests
So traditionally, most correlation assessments on Pinescript are done with a generic Pearson Correlation using the "ta.correlation" argument. However, this is not always the best test to be used for correlations and determine effects. One approach to correlation assessments used frequently in economics is the T-Test assessment.
The t-test is a statistical hypothesis test used to determine if there is a significant difference between the means of two groups. It assesses whether the sample means are likely to have come from populations with the same mean. The test produces a t-statistic, which is then compared to a critical value from the t-distribution to determine statistical significance. Lower p-values indicate stronger evidence against the null hypothesis of equal means.
A significant t-test result, indicating the rejection of the null hypothesis, suggests that there is statistical evidence to support that there is a significant difference between the means of the two groups being compared. In practical terms, it means that the observed difference in sample means is unlikely to have occurred by random chance alone. Researchers typically interpret this as evidence that there is a real, meaningful difference between the groups being studied.
Some uses of the T-Test in finance include:
Risk Assessment: The t-test can be used to compare the risk profiles of different financial assets or portfolios. It helps investors assess whether the differences in returns or volatility are statistically significant.
Pairs Trading: Traders often apply the t-test when engaging in pairs trading, a strategy that involves trading two correlated securities. It helps determine when the price spread between the two assets is statistically significant and may revert to the mean.
Volatility Analysis: Traders and risk managers use t-tests to compare the volatility of different assets or portfolios, assessing whether one is significantly more or less volatile than another.
Market Efficiency Tests: Financial researchers use t-tests to test the Efficient Market Hypothesis by assessing whether stock price movements follow a random walk or if there are statistically significant deviations from it.
Value at Risk (VaR) Calculation: Risk managers use t-tests to calculate VaR, a measure of potential losses in a portfolio. It helps assess whether a portfolio's value is likely to fall below a certain threshold.
There are many other applications, but these are a few of the highlights. SPTS permits 3 different types of T-Test analyses, these being the One Tailed T-Test (if you want to test a single direction), two tailed T-Test (if you are unsure of which direction is significant) and a paired sample t-test.
Which T is the Right T?
Generally, a one-tailed t-test is used to determine if a sample mean is significantly greater than or less than a specified population mean, whereas a two-tailed t-test assesses if the sample mean is significantly different (either greater or less) from the population mean. In contrast, a paired sample t-test compares two sets of paired observations (e.g., before and after treatment) to assess if there's a significant difference in their means, typically used when the data points in each pair are related or dependent.
So which do you use? Well, it depends on what you want to know. As a general rule a one tailed t-test is sufficient and will help you pinpoint directionality of the relationship (that one ticker or economic indicator has a significant affect on another in a linear way).
A two tailed is more broad and looks for significance in either direction.
A paired sample t-test usually looks at identical groups to see if one group has a statistically different outcome. This is usually used in clinical trials to compare treatment interventions in identical groups. It's use in finance is somewhat limited, but it is invaluable when you want to compare equities that track the same thing (for example SPX vs SPY vs ES1!) or you want to test a hypothesis about an index and a leveraged share (for example, the relationship between FNGU and, say, MSFT or NVDA).
Statistical Significance
In general, with a t-test you would need to reference a T-Table to determine the statistical significance of the degree of Freedom and the T-Statistic.
However, because I wanted Pinescript to full fledge replace SPSS and Excel, I went ahead and threw the T-Table into an array, so that Pinescript can make the determination itself of the actual P value for a t-test, no cross referencing required :-).
Left tail (Significant):
Both tails (Significant):
Distributed throughout (insignificant):
As you can see in the images above, the t-test will also display a bell-curve analysis of where the significance falls (left tail, both tails or insignificant, distributed throughout).
That said, I have not included this function for the paired sample t-test because that is a bit more nuanced. But for the one and two tailed assessments, the indicator will provide you the P value.
Pearson Correlation Assessment
I don't think I need to go into too much detail on this one.
I have put in functionality to quickly calculate the Pearson Correlation of two array's, which is not currently possible with the "ta.correlation" function.
Quadratic (Curvlinear) Correlation
Not everything in life is linear, sometimes things are curved!
The Pearson Correlation is great for linear assessments, but tends to under-estimate the degree of the relationship in curved relationships. There currently is no native function to t-test for quadratic/curvlinear relationships, so I went ahead and created one.
You can see an example of how Quadratic and Pearson Correlations vary when you look at CME_MINI:ES1! against AMEX:DIA for the past 10 ish months:
Pearson Correlation:
Quadratic Correlation:
One or the other is not always the best, so it is important to check both!
R-Squared Assessments:
The R-squared value, or the square of the Pearson correlation coefficient (r), is used to measure the proportion of variance in one variable that can be explained by the linear relationship with another variable. It represents the goodness-of-fit of a linear regression model with a single predictor variable.
R-Squared is offered in 3 separate forms within this indicator. First, there is the generic R squared which is taking the square root of a Pearson Correlation assessment to assess the variance.
The next is the R-Squared which is calculated from an actual linear regression model done within the indicator.
The first is the R-Squared which is calculated from a multiple regression model done within the indicator.
Regardless of which R-Squared value you are using, the meaning is the same. R-Square assesses the variance between the variables under assessment and can offer an insight into the goodness of fit and the ability of the model to account for the degree of variance.
Here is the R Squared assessment of the SPX against the US Money Supply:
Standard Linear Regression
The indicator contains the ability to do a standard linear regression model. You can convert one ticker or economic indicator into a stock, ticker or other economic indicator. The indicator will provide you with all of the expected information from a linear regression model, including the coefficients, intercept, error assessments, correlation and R2 value.
Here is AAPL and MSFT as an example:
Multiple Regression
Oh man, this was something I really wanted in Pinescript, and now we have it!
I have created a function for multiple regression, which, if you export the function, will permit you to perform multiple regression on any variables available in Pinescript!
Using this functionality in the indicator, you will need to select 2, dependent variables and a single independent variable.
Here is an example of multiple regression for NASDAQ:AAPL using NASDAQ:MSFT and NASDAQ:NVDA :
And an example of SPX using the US Money Supply (M2) and AMEX:GLD :
Tests of Normality:
Many indicators perform a lot of functions on the assumption of normality, yet there are no indicators that actually test that assumption!
So, I have inputted a function to assess for normality. It uses the Kurtosis and Skewness to determine up to 7 different distribution types and it will explain the implication of the distribution. Here is an example of SP:SPX on the Monthly Perspective since 2010:
And NYSE:BA since the 60s:
And NVDA since 2015:
ARIMA Modeller
Okay, so let me disclose, this isn't a full fledge ARIMA modeller. I took some shortcuts.
True ARIMA modelling would involve decomposing the seasonality from the trend. I omitted this step for simplicity sake. Instead, you can select between using an EMA or SMA based approach, and it will perform an autogressive type analysis on the EMA or SMA.
I have tested it on lookback with results provided by SPSS and this actually works better than SPSS' ARIMA function. So I am actually kind of impressed.
You will need to input your parameters for the ARIMA model, I usually would do a 14, 21 and 50 day EMA of the close price, and it will forecast out that range over the length of the EMA.
So for example, if you select the EMA 50 on the daily, it will plot out the forecast for the next 50 days based on an autoregressive model created on the EMA 50. Here is how it looks on AMEX:SPY :
You can also elect to plot the upper and lower confidence bands:
Closing Remarks
So that is the indicator/package.
I do hope to continue expanding its functionality, but as of now, it does already have quite a lot of functionality.
I really hope you enjoy it and find it helpful. This. Has. Taken. AGES! No joke. Between referencing my old statistics textbooks, trying to remember how to calculate some of these things, and wanting to throw my computer against the wall because of errors in the code, this was a task, that's for sure. So I really hope you find some usefulness in it all and enjoy the ability to be able to do functions that previously could really only be done in external software.
As always, leave your comments, suggestions and feedback below!
Take care!
Correlation Coefficient based on Log ReturnsMeasuring correlations based on log returns, rather than raw prices or simple returns, offers several advantages:
- stationarity: Log returns are more stationary, resulting in more meaningful and reliable results
- volatility: Log returns give a consistent measure of relative changes of assets with different volatility
Log returns are time-additive and often more stationary than simple returns, making them statistically more reliable for analyses in financial contexts. Additionally, they provide a consistent measure of relative price changes and align more closely with the assumptions of many statistical models, including normal distribution.
K's Reversal Indicator IIIK's Reversal Indicator III is based on the concept of autocorrelation of returns. The main theory is that extreme autocorrelation (trending) that coincide with a technical signals such as one from the RSI, may result in a powerful short-term signal that can be exploited.
The indicator is calculated as follows:
1. Calculate the price differential (returns) as the current price minus the previous price.
2. the correlation between the current return and the return from 14 periods ago using a lookback of 14 periods.
3. Calculate a 14-period RSI on the close prices.
To generate the signals, use the following rules:
* A bullish signal is generated whenever the correlation is above 0.60 while the RSI is below 40.
* A bearish signal is generated whenever the correlation is above 0.60 while the RSI is above 60.
Position Cost DistributionThe Position Cost Distribution indicator (also known as the Market Position Overview, Chip Distribution, or CYQ Algorithm) provides an estimate of how shares are distributed across different price levels. Visually, it resembles the Volume Profile indicator, though they rely on distinct computational approaches.
🟠 Principle
The Position Cost Distribution algorithm is based on the principle that a security's total shares outstanding usually remains constant, except under conditions like stock splits, reverse splits, or new share issuance. It views all trading activity as simply exchanging share positions between holders at different price points.
By analyzing daily trade volume and the prior day's distribution, the algorithm infers the resulting share distribution after each day. By tracking these inferred transpositions over time, the indicator builds up an aggregate view of the estimated share concentration at each price level. This provides insights into potential buying and selling pressure zones that could form support or resistance areas.
Together with the Volume Profile, the Position Cost Distribution gives traders multiple lenses for examining market structure from both a volume and positional standpoint. Both can help identify meaningful technical price levels.
🟠 Algorithm
The algorithm initializes by allocating all shares to the price range encompassed by the first bar displayed on the chart. Preferably, the chart window should include the stock's IPO date, allowing the model to distribute shares specifically to the IPO price.
For subsequent trading sessions, the indicator performs the following calculations:
1. The daily turnover ratio is calculated by dividing the bar's trading volume by total outstanding shares.
2. For each price level (bucket), the number of shares is reduced by the turnover amount to represent shares transferring from existing holders.
3. The bar's total volume is then added to buckets corresponding to that period's price range.
Currently, the model assumes each share has an equal probability of being exchanged, regardless of how long ago it was acquired or at what price. Potential optimizations could incorporate factors like making shares held longer face a smaller chance of transfer compared to more recently purchased shares.
────────────────────────────────────────────
中文介绍:该指标为“筹码分布”的一个 TradingView 实现 :)
SFC Valuation Model - US SectorSector analysis is an assessment of the economic and financial condition and prospects of a given sector of the economy. Sector analysis serves to provide an investor with a judgment about how well companies in the sector are expected to perform. Sector analysis is typically employed by investors who specialize in a particular sector, or who use a top-down or sector rotation approach to investing.
Sector analysis is based on the premise that certain sectors perform better during different stages of the business cycle. The business cycle refers to the up and down changes in economic activity that occur in an economy over time. The business cycle consists of expansions, which are periods of economic growth, and contractions, which are periods of economic decline.
Investors who employ a top-down approach to sector analysis focus first on macroeconomic conditions in their search for companies that have the potential to outperform. They start by looking at those macroeconomic factors that have the biggest impact on the largest part of the population and the economy, such as unemployment rates, economic outputs, and inflation.
Every sector shows the average return from three ETFs - SPDR, Vanguard, iShares. There is a possibility to see the returns from every ETF by just holding the cursor on the sector name.
There are few valuation methods/steps
- Macroeconomics - analyse the current economic;
- Define how the sector is performing;
- Relative valuation method - compare few stocks and find the Outlier;
- Absolute valuation method historically- define how the stock performed in the past;
- Absolute valuation method - define how the stock is performed now and find the fair value;
- Technical analysis
How to use:
1. Once you have completed the initial evaluation step, simply load the indicator.
2. Analyse which sector is outperforming.
SFC Valuation Model - AbsoluteFinancial statement analysis is the process of analyzing a company’s financial statements for decision-making purposes. External stakeholders use it to understand the overall health of an organization and to evaluate financial performance and business value. Internal constituents use it as a monitoring tool for managing the finances.
Most often, analysts will use three main techniques for analyzing a company’s financial statements.
First, horizontal analysis involves comparing historical data. Usually, the purpose of horizontal analysis is to detect growth trends across different time periods.
Second, vertical analysis compares items on a financial statement in relation to each other. For instance, an expense item could be expressed as a percentage of company sales.
Finally, ratio analysis, a central part of fundamental equity analysis, compares line-item data. Price-to-earnings (P/E) ratios, earnings per share, or dividend yield are examples of ratio analysis.
The indicator shows the most important metrics to help investors evaluate a stock. It saves a lot of time searching for metrics on different websites and writing them into different platforms for further analysis.
There are few valuation methods/steps
- Macroeconomics - analyse the current economic;
- Define how the sector is performing;
- Relative valuation method - compare few stocks and find the Outlier;
- Absolute valuation method historically- define how the stock performed in the past;
- Absolute valuation method - define how the stock is performed now and find the fair value;
- Technical analysis
How to use:
1. Once you have completed the initial evaluation steps, simply load the indicator.
2. Make your analysis.
3. Complete the checklist by writing down your thoughts.
SFC Valuation Model - RelativeComparable company analysis, or “Comps” for short, is commonly used to value firms by comparing them to publicly traded companies with similar business operations. An analyst will compare the current share price a public company relative to some metric such as its earnings to derive a P/E ratio. It will then use that ratio to value the company it is trying to determine the worth of.
One of the most popular relative valuation multiples is the price-to-earnings (P/E) ratio. It is calculated by dividing stock price by earnings per share (EPS), and is expressed as a company's share price as a multiple of its earnings. A company with a high P/E ratio is trading at a higher price per dollar of earnings than its peers and is considered overvalued. Likewise, a company with a low P/E ratio is trading at a lower price per dollar of EPS and is considered undervalued. This framework can be carried out with any multiple of price to gauge relative market value. Therefore, if the average P/E for an industry is 10x and a particular company in that industry is trading at 5x earnings, it is relatively undervalued to its peers.
Limitations
Like any valuation tool, relative valuation has its limitations. The biggest limitation is the assumption that the market has valued the business correctly.
Second, all valuation metrics are based on past performance. Investors' perceptions of future performance heavily influence stock prices and most relative valuation metrics don’t account for growth.
Finally and most importantly, relative valuation is no assurance that the "cheaper" company will outperform its peer.
With this indicator, investors can easily compare a few companies and find the outlier. It calculates the average for the sector and highlights the stock that is above the average.
Due to some limitations, the indicator can only compare 5 tickers, but users can always load it twice for more stocks.
Save hours of data entry into Excel spreadsheets to compare stocks !
There are few valuation methods/steps
- Macroeconomics - analyse the current economic;
- Define how the sector is performing;
- Relative valuation method - compare few stocks and find the Outlier;
- Absolute valuation method historically- define how the stock performed in the past;
- Absolute valuation method - define how the stock is performed now and find the fair value;
- Technical analysis
How to use:
1. Once you have completed the initial evaluation steps, simply load the indicator.
2. Add the forwarded EPS.
3. The indicator will do the rest of the calculations for you.
SFC Valuation Model - Fair ValueValuation is the analytical process of determining the current (or projected) worth of an asset or a company. There are many techniques used for doing a valuation. An analyst placing a value on a company looks at the business's management, the composition of its capital structure, the prospect of future earnings, and the market value of its assets, among other metrics.
Fundamental analysis is often employed in valuation, although several other methods may be employed such as the capital asset pricing model (CAPM) or the dividend discount model (DDM), Discounted Cash Flow (DCF) and many others.
A valuation can be useful when trying to determine the fair value of a security, which is determined by what a buyer is willing to pay a seller, assuming both parties enter the transaction willingly. When a security trades on an exchange, buyers and sellers determine the market value of a stock or bond.
There is no universal standard for calculating the intrinsic value of a company or stock. Financial analysts attempt to determine an asset's intrinsic value by using fundamental and technical analyses to gauge its actual financial performance.
Intrinsic value is useful because it can help an investor understand whether a potential investment is overvalued or undervalued.
This indicator allows investors to simulate different scenarios depending on their view of the stock's value. It calculates different models automatically, but users can define the fair value manually by changing the settings.
For example: change the weight of the model; choose how conservatively want to evaluate the stock; use different growth rate or discount rate and so on.
The indicator shows other useful metrics in order to help investors to evaluate the stock.
This indicator can save users hours of searching financial data and calculating fair value.
There are few valuation methods/steps
- Macroeconomics - analyse the current economic;
- Define how the sector is performing;
- Relative valuation method - compare few stocks and find the Outlier;
- Absolute valuation method historically- define how the stock performed in the past;
- Absolute valuation method - define how the stock is performed now and find the fair value;
- Technical analysis
How to use:
1. Once you have completed the initial evaluation steps, simply load the indicator.
2. Check the default settings and see if they suit you.
3. Find the fair value and wait for the stock to reach it.
Median of Means Estimator Median of Means (MoM) is a measure of central tendency like mean (average) and median. However, it could be a better and robust estimator of central tendency when the data is not normal, asymmetric, have fat tails (like stock price data) and have outliers. The MoM can be used as a robust trend following tool and in other derived indicators.
Median of means (MoM) is calculated as follows, the MoM estimator shuffles the "n" data points and then splits them into k groups of m data points (n= k*m). It then computes the Arithmetic Mean of each group (k). Finally, it calculate the median over the resulting k Arithmetic Means. This technique diminishes the effect that outliers have on the final estimation by splitting the data and only considering the median of the resulting sub-estimations. This preserves the overall trend despite the data shuffle.
Below is an example to illustrate the advantages of MoM
Set A Set B Set C
3 4 4
3 4 4
3 5 5
3 5 5
4 5 5
4 5 5
5 5 5
5 5 5
6 6 8
6 6 8
7 7 10
7 7 15
8 8 40
9 9 50
10 100 100
Median 5 5 5
Mean 5.5 12.1 17.9
MoM 5.7 6.0 17.3
For all three sets the median is the same, though set A and B are the same except for one outlier in set B (100) it skews the mean but the median is resilient. However, in set C the group has several high values despite that the median is not responsive and still give 5 as the central tendency of the group, but the median of means is a value of 17.3 which is very close to the group mean 17.9. In all three cases (set A, B and C) the MoM provides a better snapshot of the central tendency of the group. Note: The MoM is dependent on the way we split the data initially and the value might slightly vary when the randomization is done sevral time and the resulting value can give the confidence interval of the MoM estimator.
Cumulative Distribution of a Dataset [SS]This is the Cumulative Distribution of a Dataset indicator that also calculates the Kurtosis and Skewness for a selected dataset and determines the normality and distribution type.
What it does, in pragmatic terms?
In the most simplest terms, it calculates the cumulative distribution function (or CDF) of user-defined dataset.
The cumulative distribution function (CDF) is a concept used in statistics and probability to describe how the probability of a random variable taking on a certain value or less is distributed across the entire range of possible values. In simpler terms, you can conceptualize the CDF as this:
Imagine you have a list of data, such as test scores of students in a class. The CDF helps you answer questions like, "What's the probability that a randomly chosen student scored 80 or less on the test?"
Or in our case, say we are in a strong up or downtrend on a stock. The CDF can help us answer questions like "Based on this current xyz trend, what is the probability that a ticker will fall above X price or below Y price".
Within the indicator, you can manually assess a price of interest. Let's say, for NVDA, we want to know the probability NVDA goes above or below $450. We can enter $450 into the indicator and get this result:
Other functions:
Kurtosis and Skewness Functions:
In addition to calculating and plotting the CDF, we can also plot the kurtosis & Skewness.
This can help you look for outlier periods where the distribution of your dataset changed. It can potentially alert you to when a stock is behaving abnormally and when it is more stable and evenly distributed.
Tests of normality
The indicator will use the kurtosis and skewness to determine the normality of the dataset. The indicator is programmed to recognize up to 7 different distribution types and alert you to them and the implications they have in your overall assessment.
e.g. #1 AMC during short squeeze:
e.g. #2: BA during the COVID crash:
Plotting the standardized Z-Score of the Distribution Dataset
You can also standardize the dataset by converting it into Z-Score format:
Plot the raw, CDF results
Two values are plotting, the green and the red. The green represents the probability of a ticker going higher than the current value. The red represents the probability of a ticker going lower than the current value.
Limitations
There are some limitations of the indicator which I think are important to point out. They are:
The indicator cannot tell you timelines, it can only tell you the general probability that data within the dataset will fall above or below a certain value.
The indicator cannot take into account projected periods of consolidation. It is possible a ticker can remain in a consolidation phase for a very long time. This would have the effect of stabilizing the probability in one direction (if there was a lot of downside room, it can normalize the data out so that the extent of the downside probability is mitigated). Thus, its important to use judgement and other methods to assess the likelihood that a stock will pullback or continue up, based on the overall probability.
The indicator is only looking at an individual dataset.
Using this indicator, you have to omit a large amount of data and look at solely a confined dataset. In a way, this actually improves the accuracy, but can also be misleading, depending on the size and strength of the dataset being chosen. It is important to balance your choice of dataset time with such things as:
a) The strength of the uptrend or downtrend.
b) The length of the uptrend or downtrend.
c) The overall performance of the stock leading into the dataset time period
And that is the indicator in a nutshell.
Hopefully you find it helpful and interesting. Feel free to leave questions, comments and suggestions below.
Safe trades everyone and take care!
Returns Model by TenozenHey there! I've been diving into the book "Paul Wilmott on Quantitative Finance," and I stumbled upon this cool model for calculating and modeling returns. Basically, it helps us figure out how much a price has changed over a set number of periods—I like to use 20 periods as a default. Once we get that rate of change value, we crunch some numbers to find the standard deviation and mean using all the historical data we have. That's the foundation of this model.
Now, let's talk about how to use it. This model shows us how returns and price behavior are connected. When returns hang out in the +1 to +2 standard deviation range, it usually means returns are about to drop, and vice versa. Often, this leads to corresponding price moves. But here's the thing: sometimes prices don't do what we expect. Why? It's because there's another hidden factor at play—I like to call it "power."
This "power" isn't something we can see directly, but it's there. Basically, when returns are within that standard deviation range, the market faces resistance when trying to move in its preferred direction, whether bullish or bearish. The strength of this "power" determines if the market will snap back to the average or go for a wild ride. It can show up as small price wiggles, big price jumps, or lightning-fast moves. By understanding this "power," we can get a better handle on what the market might do next and avoid getting blindsided. In the meantime, I couldn't explain "power" yet, but In the future, when I've learned enough, I'd love to share the model with you guys!
So... I'm planning to explore and share more models from this book as I learn, even if those pesky math formulas can be tough to crack. I hope you find this indicator as helpful as I do, and if you've got any suggestions or feedback, please feel free to share! Ciao!