[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)
Statistics
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.
WIPFunctionLyaponovLibrary "WIPFunctionLyaponov"
Lyapunov exponents are mathematical measures used to describe the behavior of a system over
time. They are named after Russian mathematician Alexei Lyapunov, who first introduced the concept in the
late 19th century. The exponent is defined as the rate at which a particular function or variable changes
over time, and can be positive, negative, or zero.
Positive exponents indicate that a system tends to grow or expand over time, while negative exponents
indicate that a system tends to shrink or decay. Zero exponents indicate that the system does not change
significantly over time. Lyapunov exponents are used in various fields of science and engineering, including
physics, economics, and biology, to study the long-term behavior of complex systems.
~ generated description from vicuna13b
---
To calculate the Lyapunov Exponent (LE) of a given Time Series, we need to follow these steps:
1. Firstly, you should have access to your data in some format like CSV or Excel file. If not, then you can collect it manually using tools such as stopwatches and measuring tapes.
2. Once the data is collected, clean it up by removing any outliers that may skew results. This step involves checking for inconsistencies within your dataset (e.g., extremely large or small values) and either discarding them entirely or replacing with more reasonable estimates based on surrounding values.
3. Next, you need to determine the dimension of your time series data. In most cases, this will be equal to the number of variables being measured in each observation period (e.g., temperature, humidity, wind speed).
4. Now that we have a clean dataset with known dimensions, we can calculate the LE for our Time Series using the following formula:
λ = log(||M^T * M - I||)/log(||v||)
where:
λ (Lyapunov Exponent) is the quantity that will be calculated.
||...|| denotes an Euclidean norm of a vector or matrix, which essentially means taking the square root of the sum of squares for each element in the vector/matrix.
M represents our Jacobian Matrix whose elements are given by:
J_ij = (∂fj / ∂xj) where fj is the jth variable and xj is the ith component of the initial condition vector x(t). In other words, each element in this matrix represents how much a small change in one variable affects another.
I denotes an identity matrix whose elements are all equal to 1 (or any constant value if you prefer). This term essentially acts as a baseline for comparison purposes since we want our Jacobian Matrix M^T * M to be close to it when the system is stable and far away from it when the system is unstable.
v represents an arbitrary vector whose Euclidean norm ||v|| will serve as a scaling factor in our calculation. The choice of this particular vector does not matter since we are only interested in its magnitude (i.e., length) for purposes of normalization. However, if you want to ensure that your results are accurate and consistent across different datasets or scenarios, it is recommended to use the same initial condition vector x(t) as used earlier when calculating our Jacobian Matrix M.
5. Finally, once we have calculated λ using the formula above, we can interpret its value in terms of stability/instability for our Time Series data:
- If λ < 0, then this indicates that the system is stable (i.e., nearby trajectories will converge towards each other over time).
- On the other hand, if λ > 0, then this implies that the system is unstable (i.e., nearby trajectories will diverge away from one another over time).
~ generated description from airoboros33b
---
Reference:
en.wikipedia.org
www.collimator.ai
blog.abhranil.net
www.researchgate.net
physics.stackexchange.com
---
This is a work in progress, it may contain errors so use with caution.
If you find flaws or suggest something new, please leave a comment bellow.
_measure_function(i)
helper function to get the name of distance function by a index (0 -> 13).\
Functions: SSD, Euclidean, Manhattan, Minkowski, Chebyshev, Correlation, Cosine, Camberra, MAE, MSE, Lorentzian, Intersection, Penrose Shape, Meehl.
Parameters:
i (int)
_test(L)
Helper function to test the output exponents state system and outputs description into a string.
Parameters:
L (float )
estimate(X, initial_distance, distance_function)
Estimate the Lyaponov Exponents for multiple series in a row matrix.
Parameters:
X (map)
initial_distance (float) : Initial distance limit.
distance_function (string) : Name of the distance function to be used, default:`ssd`.
Returns: List of Lyaponov exponents.
max(L)
Maximal Lyaponov Exponent.
Parameters:
L (float ) : List of Lyapunov exponents.
Returns: Highest exponent.
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!
TTP PNR filterPNR filter uses the "percentile nearest rank" method to produce signals from any source including oscillator indicators and price bars.
Features:
* Length - how many candles back in time to use for calculating PNR
* % low and high - what range of the spread of values captured will form the PNR band. Use 99&100 to create a band on the 1% highest percentile or 0&1 to create a band in the lowest percentile. It accepts float numbers so you can find very rare occurrences.
* src - by default it will use the close price but PNR filter can be used with any source. It's particularly useful when working with oscillators like RSI, MACD, ADX, etc.
* Signal direction - The indicator will print 1 when the selected conditions are met. Once the PNR band is plotted you can chose from cross over, cross under, above and below conditions to trigger a signal.
* Signal source - the band consists in a % low and % high, this option allows you to pick which band will be used with the "signal direction" parameter.
Example configuration:
1) Select 200 as the length
2) Select % low 0 and % high 1
3) Add RSI to the chart and select it as the source parameter
4) Select signal direction cross over
5) Select signal source % high which corresponds to the 1% band
In this setup you are finding values of RSI that in the past 200 candles have been that low only 1% of the time. With each new candle the calculation window will move as well leaving the oldest candle out.
Signal to Noise TrendSignal to Noise Ratio
The Signal to Noise Ratio or SNR is used to assess the quality of information or data by comparing the strength of a useful signal to the presence of background noise or random variations.
In Finance the SNR refers to the ratio of strength of a trading signal to the background noise. A high SNR suggest a clear and reliable signal, meanwhile a low SNR indicates more noise (random fluctuations, volatility, or randomness).
Signal To Noise Trend
This indicator basically calculates the signal to noise of returns and then gets the Z-Score of the signal to noise ratio to find extremes levels of signal and noise. The Lines basically are standard deviations from the mean. 1,2,3 Are standard deviations same with the -1,-2,-3 Lines.
The signal is expressed as the positive Z-Score value, and the Noise is the negative Z-Score Value.
The moving average enhances the indicator ability to display the trend of returns and the trend strength. It provides a smooth representation of the Signal to Nose Ratio values.
There are more trending conditions when there is a higher signal, and there is more "ranging" conditions when there is more noise present in the markets.
The Standard deviations help find extreme levels of signal and noise. If the noise reaches the standard deviation of -3 then that means that there is a extreme negative deviation from the mean, and this would be a rare occurrence, with a lot of noise. This could indicate a potential reversion in market states, and could be followed by a trending move.
Another example is that if the Z-Score value reaches a Standard deviation of 3, this could mean that there is extremely strong and rare signal, and could potentially mean a change to a more noisy environment soon.
lib_profileLibrary "lib_profile"
a library with functions to calculate a volume profile for either a set of candles within the current chart, or a single candle from its lower timeframe security data. All you need is to feed the
method delete(this)
deletes this bucket's plot from the chart
Namespace types: Bucket
Parameters:
this (Bucket)
method delete(this)
Namespace types: Profile
Parameters:
this (Profile)
method delete(this)
Namespace types: Bucket
Parameters:
this (Bucket )
method delete(this)
Namespace types: Profile
Parameters:
this (Profile )
method update(this, top, bottom, value, fraction)
updates this bucket's data
Namespace types: Bucket
Parameters:
this (Bucket)
top (float)
bottom (float)
value (float)
fraction (float)
method update(this, tops, bottoms, values)
update this Profile's data (recalculates the whole profile and applies the result to this object) TODO optimisation to calculate this incremental to improve performance in realtime on high resolution
Namespace types: Profile
Parameters:
this (Profile)
tops (float ) : array of range top/high values (either from ltf or chart candles using history() function
bottoms (float ) : array of range bottom/low values (either from ltf or chart candles using history() function
values (float ) : array of range volume/1 values (either from ltf or chart candles using history() function (1s can be used for analysing candles in bucket/price range over time)
method tostring(this)
allows debug print of a bucket
Namespace types: Bucket
Parameters:
this (Bucket)
method draw(this, start_t, start_i, end_t, end_i, args, line_color)
allows drawing a line in a Profile, representing this bucket and it's value + it's value's fraction of the Profile total value
Namespace types: Bucket
Parameters:
this (Bucket)
start_t (int) : the time x coordinate of the line's left end (depends on the Profile box)
start_i (int) : the bar_index x coordinate of the line's left end (depends on the Profile box)
end_t (int) : the time x coordinate of the line's right end (depends on the Profile box)
end_i (int) : the bar_index x coordinate of the line's right end (depends on the Profile box)
args (LineArgs type from robbatt/lib_plot_objects/24) : the default arguments for the line style
line_color (color) : the color override for POC/VAH/VAL lines
method draw(this, forced_width)
draw all components of this Profile (Box, Background, Bucket lines, POC/VAH/VAL overlay levels and labels)
Namespace types: Profile
Parameters:
this (Profile)
forced_width (int) : allows to force width of the Profile Box, overrides the ProfileArgs.default_size and ProfileArgs.extend arguments (default: na)
method init(this)
Namespace types: ProfileArgs
Parameters:
this (ProfileArgs)
method init(this)
Namespace types: Profile
Parameters:
this (Profile)
profile(tops, bottoms, values, resolution, vah_pc, val_pc, bucket_buffer)
split a chart/parent bar into 'resolution' sections, figure out in which section the most volume/time was spent, by analysing a given set of (intra)bars' top/bottom/volume values. Then return price center of the bin with the highest volume, essentially marking the point of control / highest volume (poc) in the chart/parent bar.
Parameters:
tops (float ) : array of range top/high values (either from ltf or chart candles using history() function
bottoms (float ) : array of range bottom/low values (either from ltf or chart candles using history() function
values (float ) : array of range volume/1 values (either from ltf or chart candles using history() function (1s can be used for analysing candles in bucket/price range over time)
resolution (int) : amount of buckets/price ranges to sort the candle data into (analyse how much volume / time was spent in a certain bucket/price range) (default: 25)
vah_pc (float) : a threshold percentage (of values' total) for the top end of the value area (default: 80)
val_pc (float) : a threshold percentage (of values' total) for the bottom end of the value area (default: 20)
bucket_buffer (Bucket ) : optional buffer of empty Buckets to fill, if omitted a new one is created and returned. The buffer length must match the resolution
Returns: poc (price level), vah (price level), val (price level), poc_index (idx in buckets), vah_index (idx in buckets), val_index (idx in buckets), buckets (filled buffer or new)
create_profile(start_idx, tops, bottoms, values, resolution, vah_pc, val_pc, args)
split a chart/parent bar into 'resolution' sections, figure out in which section the most volume/time was spent, by analysing a given set of (intra)bars' top/bottom/volume values. Then return price center of the bin with the highest volume, essentially marking the point of control / highest volume (poc) in the chart/parent bar.
Parameters:
start_idx (int) : the bar_index at which the Profile should start drawing
tops (float ) : array of range top/high values (either from ltf or chart candles using history() function
bottoms (float ) : array of range bottom/low values (either from ltf or chart candles using history() function
values (float ) : array of range volume/1 values (either from ltf or chart candles using history() function (1s can be used for analysing candles in bucket/price range over time)
resolution (int) : amount of buckets/price ranges to sort the candle data into (analyse how much volume / time was spent in a certain bucket/price range) (default: 25)
vah_pc (float) : a threshold percentage (of values' total) for the top end of the value area (default: 80)
val_pc (float) : a threshold percentage (of values' total) for the bottom end of the value area (default: 20)
args (ProfileArgs)
Returns: poc (price level), vah (price level), val (price level), poc_index (idx in buckets), vah_index (idx in buckets), val_index (idx in buckets), buckets (filled buffer or new)
history(src, len, offset)
allows fetching an array of values from the history series with offset from current candle
Parameters:
src (int)
len (int)
offset (int)
history(src, len, offset)
allows fetching an array of values from the history series with offset from current candle
Parameters:
src (float)
len (int)
offset (int)
history(src, len, offset)
allows fetching an array of values from the history series with offset from current candle
Parameters:
src (bool)
len (int)
offset (int)
history(src, len, offset)
allows fetching an array of values from the history series with offset from current candle
Parameters:
src (string)
len (int)
offset (int)
Bucket
Fields:
idx (series int) : the index of this Bucket within the Profile starting with 0 for the lowest Bucket at the bottom of the Profile
value (series float) : the value of this Bucket, can be volume or time, for using time pass and array of 1s to the update function
top (series float) : the top of this Bucket's price range (for calculation)
btm (series float) : the bottom of this Bucket's price range (for calculation)
center (series float) : the center of this Bucket's price range (for plotting)
fraction (series float) : the fraction this Bucket's value is compared to the total of the Profile
plot_bucket_line (Line type from robbatt/lib_plot_objects/24) : the line that resembles this bucket and it's valeu in the Profile
ProfileArgs
Fields:
show_poc (series bool) : whether to plot a POC line across the Profile Box (default: true)
show_profile (series bool) : whether to plot a line for each Bucket in the Profile Box, indicating the value per Bucket (Price range), e.g. volume that occured in a certain time and price range (default: false)
show_va (series bool) : whether to plot a VAH/VAL line across the Profile Box (default: false)
show_va_fill (series bool) : whether to fill the 'value' area between VAH/VAL line (default: false)
show_background (series bool) : whether to fill the Profile Box with a background color (default: false)
show_labels (series bool) : whether to add labels to the right end of the POC/VAH/VAL line (default: false)
show_price_levels (series bool) : whether add price values to the labels to the right end of the POC/VAH/VAL line (default: false)
extend (series bool) : whether extend the Profile Box to the current candle (default: false)
default_size (series int) : the default min. width of the Profile Box (default: 30)
args_poc_line (LineArgs type from robbatt/lib_plot_objects/24) : arguments for the poc line plot
args_va_line (LineArgs type from robbatt/lib_plot_objects/24) : arguments for the va line plot
args_poc_label (LabelArgs type from robbatt/lib_plot_objects/24) : arguments for the poc label plot
args_va_label (LabelArgs type from robbatt/lib_plot_objects/24) : arguments for the va label plot
args_profile_line (LineArgs type from robbatt/lib_plot_objects/24) : arguments for the Bucket line plots
args_profile_bg (BoxArgs type from robbatt/lib_plot_objects/24)
va_fill_color (series color) : color for the va area fill plot
Profile
Fields:
start (series int) : left x coordinate for the Profile Box
end (series int) : right x coordinate for the Profile Box
resolution (series int) : the amount of buckets/price ranges the Profile will dissect the data into
vah_threshold_pc (series float) : the percentage of the total data value to mark the upper threshold for the main value area
val_threshold_pc (series float) : the percentage of the total data value to mark the lower threshold for the main value area
args (ProfileArgs) : the style arguments for the Profile Box
h (series float) : the highest price of the data
l (series float) : the lowest price of the data
total (series float) : the total data value (e.g. volume of all candles, or just one each to analyse candle distribution over time)
buckets (Bucket ) : the Bucket objects holding the data for each price range bucket
poc_bucket_index (series int) : the Bucket index in buckets, that holds the poc Bucket
vah_bucket_index (series int) : the Bucket index in buckets, that holds the vah Bucket
val_bucket_index (series int) : the Bucket index in buckets, that holds the val Bucket
poc (series float) : the according price level marking the Point Of Control
vah (series float) : the according price level marking the Value Area High
val (series float) : the according price level marking the Value Area Low
plot_poc (Line type from robbatt/lib_plot_objects/24)
plot_vah (Line type from robbatt/lib_plot_objects/24)
plot_val (Line type from robbatt/lib_plot_objects/24)
plot_poc_label (Label type from robbatt/lib_plot_objects/24)
plot_vah_label (Label type from robbatt/lib_plot_objects/24)
plot_val_label (Label type from robbatt/lib_plot_objects/24)
plot_va_fill (LineFill type from robbatt/lib_plot_objects/24)
plot_profile_bg (Box type from robbatt/lib_plot_objects/24)
MMI Auto Backtesting StrategyDescription:
A strategy based on ATR with auto-backtesting capabilities, Take Profit and Stop Loss (either Normal or Trailing). It allows you to select ranges of values and step for each parameter, and backtest the strategy on a multitude of input combinations at once. You can alternatively use a constant value for each parameter. The backtesting results strive to be as close as possible to those given by Tradingview Strategy Tester.
The strategy displays a table with results for different input combinations. This has columns showing current input combination as well as the following stats: Net Profit, Number of trades, % of Profitable trades, Profit Factor, Max Drawdown, Max Runup, Average Trade and Average number of bars in a trade.
You can sort the table by any column (including sorting by multiple columns at the same time) to find, for example, input combination that gives highest Net Profit (or, if sorting by multiple columns, to find input combination with the best balance of Net Profit and % of Profitable trades). You can filter by any column as well (or multiple columns at the same time), using logical expressions like "< value", "> value", "<= value", ">= value". And you can use logical expressions like "< value%" for Net Profit, Max Drawdown, Max Runup and Average trade to filter by percentage value. You will see a "↓" symbol in column's header if that column is sorted from Highest to Lowest, a "↑" symbol if it's sorted from Lowest to Highest and a "𐕢" symbol if that column is being filtered.
The table has customisable styles (like text color, background color of cells, etc.), and can show the total number of backtested combinations with the time taken to test them. You can also change Initial Capital and Position Size (either Contracts, Currency or % of Equity).
Parameters:
The following parameters are located in the "INPUTS (USUAL STRATEGY)" group, and control the behaviour of strategy itself (not the auto-backtesting functionality):
- Period: ATR Length
- Multiplier: ATR Multiplier
- DPO: length of the filtering moving average
- SL: stop loss
- TP: take profit
- Use Stop Loss: enable stop loss
- Stop Loss Mode: stop loss mode (either Normal or Trailing)
- Use Take Profit: enable take profit
- Wicks: use high & low price, or close price
The strategy also has various parameters separated by different groups:
- INPUTS (AUTO-BACKTESTING): has the same parameters as the "INPUTS (USUAL STRATEGY)" group, but controls the input combinations for auto-backtesting; all the numeric parameters have 3 values: F/V (from), T (to) and S (step); if the checkbox to the left of F/V parameter is off, the value of F/V will indicate the constant value used for that parameter (if the checkbox is on, the values will be from F/V to T using step S)
- STRATEGY: contains strategy related parameters like Initial Capital and Position Size
- BACKTESTING: allows you to display either Percentage, Absolute or Both values in the table and has checkboxes that allow you to exclude certain columns from the table
- SORTING: allows you to select sorting mode (Highest to Lowest or vice versa) and has checkboxes in case you want to sort by multiple columns at the same time
- FILTERING: has a text field for each column of the strategy where you can type logical expressions to filter the values
- TABLE: contains styling parameters
Many parameters have the "(i)" description marker, so hover over it to see more details.
Problems:
- The script works best on lower timeframes and continuous markets (trades 24/7), in other cases the backtesting results may vary from those that Tradingview shows
- The script shows closest results when Take Profit and Stop Loss are not used
- Max Runup percentage value is often wrong
Limitations:
- As we are limited by the maximum time a script can be running (which is 20s for Free plan and 40s for Paid plans), we can only backtest several hundreds of combinations within that timeframe (though it depends on the parameters, market and timeframe of the chart you use)