Statistics • Chi Square • P-value • SignificanceThe Statistics • Chi Square • P-value • Significance publication aims to provide a tool for combining different conditions and checking whether the outcome is significant using the Chi-Square Test and P-value.
🔶 USAGE
The basic principle is to compare two or more groups and check the results of a query test, such as asking men and women whether they want to see a romantic or non-romantic movie.
–––––––––––––––––––––––––––––––––––––––––––––
| | ROMANTIC | NON-ROMANTIC | ⬅︎ MOVIE |
–––––––––––––––––––––––––––––––––––––––––––––
| MEN | 2 | 8 | 10 |
–––––––––––––––––––––––––––––––––––––––––––––
| WOMEN | 7 | 3 | 10 |
–––––––––––––––––––––––––––––––––––––––––––––
|⬆︎ SEX | 10 | 10 | 20 |
–––––––––––––––––––––––––––––––––––––––––––––
We calculate the Chi-Square Formula, which is:
Χ² = Σ ( (Observed Value − Expected Value)² / Expected Value )
In this publication, this is:
chiSquare = 0.
for i = 0 to rows -1
for j = 0 to colums -1
observedValue = aBin.get(i).aFloat.get(j)
expectedValue = math.max(1e-12, aBin.get(i).aFloat.get(colums) * aBin.get(rows).aFloat.get(j) / sumT) //Division by 0 protection
chiSquare += math.pow(observedValue - expectedValue, 2) / expectedValue
Together with the 'Degree of Freedom', which is (rows − 1) × (columns − 1) , the P-value can be calculated.
In this case it is P-value: 0.02462
A P-value lower than 0.05 is considered to be significant. Statistically, women tend to choose a romantic movie more, while men prefer a non-romantic one.
Users have the option to choose a P-value, calculated from a standard table or through a math.ucla.edu - Javascript-based function (see references below).
Note that the population (10 men + 10 women = 20) is small, something to consider.
Either way, this principle is applied in the script, where conditions can be chosen like rsi, close, high, ...
🔹 CONDITION
Conditions are added to the left column ('CONDITION')
For example, previous rsi values (rsi ) between 0-100, divided in separate groups
🔹 CLOSE
Then, the movement of the last close is evaluated
UP when close is higher then previous close (close )
DOWN when close is lower then previous close
EQUAL when close is equal then previous close
It is also possible to use only 2 columns by adding EQUAL to UP or DOWN
UP
DOWN/EQUAL
or
UP/EQUAL
DOWN
In other words, when previous rsi value was between 80 and 90, this resulted in:
19 times a current close higher than previous close
14 times a current close lower than previous close
0 times a current close equal than previous close
However, the P-value tells us it is not statistical significant.
NOTE: Always keep in mind that past behaviour gives no certainty about future behaviour.
A vertical line is drawn at the beginning of the chosen population (max 4990)
Here, the results seem significant.
🔹 GROUPS
It is important to ensure that the groups are formed correctly. All possibilities should be present, and conditions should only be part of 1 group.
In the example above, the two top situations are acceptable; close against close can only be higher, lower or equal.
The two examples at the bottom, however, are very poorly constructed.
Several conditions can be placed in more than 1 group, and some conditions are not integrated into a group. Even if the results are significant, they are useless because of the group formation.
A population count is added as an aid to spot errors in group formation.
In this example, there is a discrepancy between the population and total count due to the absence of a condition.
The results when rsi was between 5-25 are not included, resulting in unreliable results.
🔹 PRACTICAL EXAMPLES
In this example, we have specific groups where the condition only applies to that group.
For example, the condition rsi > 55 and rsi <= 65 isn't true in another group.
Also, every possible rsi value (0 - 100) is present in 1 of the groups.
rsi > 15 and rsi <= 25 28 times UP, 19 times DOWN and 2 times EQUAL. P-value: 0.01171
When looking in detail and examining the area 15-25 RSI, we see this:
The population is now not representative (only checking for RSI between 15-25; all other RSI values are not included), so we can ignore the P-value in this case. It is merely to check in detail. In this case, the RSI values 23 and 24 seem promising.
NOTE: We should check what the close price did without any condition.
If, for example, the close price had risen 100 times out of 100, this would make things very relative.
In this case (at least two conditions need to be present), we set 1 condition at 'always true' and another at 'always false' so we'll get only the close values without any condition:
Changing the population or the conditions will change the P-value.
In the following example, the outcome is evaluated when:
close value from 1 bar back is higher than the close value from 2 bars back
close value from 1 bar back is lower/equal than the close value from 2 bars back
Or:
close value from 1 bar back is higher than the close value from 2 bars back
close value from 1 bar back is equal than the close value from 2 bars back
close value from 1 bar back is lower than the close value from 2 bars back
In both examples, all possibilities of close against close are included in the calculations. close can only by higher, equal or lower than close
Both examples have the results without a condition included (5 = 5 and 5 < 5) so one can compare the direction of current close.
🔶 NOTES
• Always keep in mind that:
Past behaviour gives no certainty about future behaviour.
Everything depends on time, cycles, events, fundamentals, technicals, ...
• This test only works for categorical data (data in categories), such as Gender {Men, Women} or color {Red, Yellow, Green, Blue} etc., but not numerical data such as height or weight. One might argue that such tests shouldn't use rsi, close, ... values.
• Consider what you're measuring
For example rsi of the current bar will always lead to a close higher than the previous close, since this is inherent to the rsi calculations.
• Be careful; often, there are na -values at the beginning of the series, which are not included in the calculations!
• Always keep in mind considering what the close price did without any condition
• The numbers must be large enough. Each entry must be five or more. In other words, it is vital to make the 'population' large enough.
• The code can be developed further, for example, by splitting UP, DOWN in close UP 1-2%, close UP 2-3%, close UP 3-4%, ...
• rsi can be supplemented with stochRSI, MFI, sma, ema, ...
🔶 SETTINGS
🔹 Population
• Choose the population size; in other words, how many bars you want to go back to. If fewer bars are available than set, this will be automatically adjusted.
🔹 Inputs
At least two conditions need to be chosen.
• Users can add up to 11 conditions, where each condition can contain two different conditions.
🔹 RSI
• Length
🔹 Levels
• Set the used levels as desired.
🔹 Levels
• P-value: P-value retrieved using a standard table method or a function.
• Used function, derived from Chi-Square Distribution Function; JavaScript
LogGamma(Z) =>
S = 1
+ 76.18009173 / Z
- 86.50532033 / (Z+1)
+ 24.01409822 / (Z+2)
- 1.231739516 / (Z+3)
+ 0.00120858003 / (Z+4)
- 0.00000536382 / (Z+5)
(Z-.5) * math.log(Z+4.5) - (Z+4.5) + math.log(S * 2.50662827465)
Gcf(float X, A) => // Good for X > A +1
A0=0., B0=1., A1=1., B1=X, AOLD=0., N=0
while (math.abs((A1-AOLD)/A1) > .00001)
AOLD := A1
N += 1
A0 := A1+(N-A)*A0
B0 := B1+(N-A)*B0
A1 := X*A0+N*A1
B1 := X*B0+N*B1
A0 := A0/B1
B0 := B0/B1
A1 := A1/B1
B1 := 1
Prob = math.exp(A * math.log(X) - X - LogGamma(A)) * A1
1 - Prob
Gser(X, A) => // Good for X < A +1
T9 = 1. / A
G = T9
I = 1
while (T9 > G* 0.00001)
T9 := T9 * X / (A + I)
G := G + T9
I += 1
G *= math.exp(A * math.log(X) - X - LogGamma(A))
Gammacdf(x, a) =>
GI = 0.
if (x<=0)
GI := 0
else if (x
Chisqcdf = Gammacdf(Z/2, DF/2)
Chisqcdf := math.round(Chisqcdf * 100000) / 100000
pValue = 1 - Chisqcdf
🔶 REFERENCES
mathsisfun.com, Chi-Square Test
Chi-Square Distribution Function
Square
Astro: Planetary Aspect DatesIn astrology, planetary aspects refer to the angles formed between two or more planets in a horoscope or birth chart. These angles are created by the positions of the planets in the sky and are thought to represent a particular energy or influence that can impact events on Earth.
The most common planetary aspects are the conjunction (when two planets are in the same position in the zodiac), the opposition (when two planets are direct across from each other in the zodiac), the trine (when two planets are 120 degrees apart in the zodiac), and the square (when two planets are 90 degrees apart in the zodiac).
This chart overlay is a simple companion indicator that highlights aspect dates for the following oscillator:
Strategy Myth-Busting #4 - LSMA+HULL Crossover - [MYN]This is part of a new series we are calling "Strategy Myth-Busting" where we take open public manual trading strategies and automate them. The goal is to not only validate the authenticity of the claims but to provide an automated version for traders who wish to trade autonomously.
Our fourth one we are automating is one of the strategies from "I Found The Best 1 Minute Scalping Strategy That Actually Works! ( Beginner Friendly )" from "Trade Domination" who claims to have made 366% profit on the 1 min chart of Solona despite having a 31% win rate in just a few weeks. As you can see from the backtest results below, I was unable to substantiate anything close to that that claim on the same symbol ( SOLUSD ), timeframe (1m) with identical instrument settings that "Trade Domination" was demonstrating with. Strategy Busted.
If you know of or have a strategy you want to see myth-busted or just have an idea for one, please feel free to message me.
This strategy uses a combination of 2 open-source public indicators:
LSMA
Hull Suite by InSilico
Trading Rules
1 min candles
Stop Loss on recent swing High/Low
1:5 Risk Ratio
Enter Long
LSMA cross above Red Hull Suite line
Price has to be above Hull Suite Line
Enter Short
LSMA crosses under green Hull Suite Line
Price has to be below Hull Suite Line
Gann Square of 144This indicator will create lines on the chart based on W.D. Gann's Square of 144. All the inputs will be detailed below
Why create this indicator?
I didn't find it on Tradingview (at least with open source). But the main reason is to study the strategy and be able to draw it fast. Manually drawing the square is not hard, but moving all together to the right spots and scale was time-consuming.
It has a lot of inputs...
Yes, each square point divisible by 6 has information with some options, so the user can create any configuration he wants. Also, it has the advantage of having the square built in seconds and adjusting itself on each new calculation.
About the inputs
Starting Date
This input will be used when the "Set Upper/Lower Prices and Start Bar Automatically" checkbox is not selected. The indicator will calculate all the line locations on the chart using the selected start date. When selecting this input, change the Manual Max and Min Prices to the better calculation
Manual Max/Min Price
This input will be used when the "Set Upper/Lower Prices and Start Bar Automatically" checkbox is not selected. The indicator will calculate all the line's locations on the chart using these prices
Set Upper/Lower Prices and Start Bar Automatically
Selects if the starting date will be automatically selected by the system or based on the input data. When it's set, the indicator will use the most recent bar as the middle point of the square, using the higher price as the Upper Price and the lowest price as the Lower Price in the latest 72 bars (or more based on the Candles Per Division parameter)
Update at a new bar
When this option is market, the indicator will update all created lines to match the new bar position, together with all the possible new Upper/Lower prices. Let it unchecked to watch the progression of the price while the square remains fixed in the chart.
Top X-Axis
When checked, it will display the labels on the Top of the square
Bottom X-Axis
When checked, it will display the labels on the Bottom of the square
Left X-Axis
When checked, it will display the labels on the left of the square
Right X-Axis
When checked, it will display the labels on the right of the square
Show Prices on the Right Y-Axis
When checked, it will display the prices together with the labels on the right of the square
Show Vertical Divisions
Show the lines that will divide the square into 9 equal parts
Show Extra Lines
Show unique lines that will come from the Top and bottom middle of the square, connecting the center to the 36 and 108 levels
Show Grid
When selected, it will display a grid in the square
Line Patterns
A selector with some options of built-in lines configuration. When any option besides None is selected, it will override the lines inputs below
Numbers Color
Select the color of each number on the Axis
Vertical Lines Color
Select the color of the vertical lines
Grid Color
Select the grid line color
Connections from corners to N
Each corner is represented by 2 characters, so they all fit in a single line
It will indicate where the line starts and where it ends
┏ ↓ = Top Left to Bottom
┏ → = Top Left to Right
┗ ↑ = Bottom Left to Top
┗ → = Bottom Left to Right
┓ ← = Top Right to Left
┓ ↓ = Top Right to Bottom
┛ ← = Bottom Right to Left
┛ ↑ = Bottom Right to Top
Besides selecting what line will be created, it's possible to select the color, the style, and the extension
How to use this indicator
When you dig into Gann's books for more information about the square of 144, you find that it was part of his setup with multiple indicators (technical and fundamental, and astrological). It is not a "one indicator" setup, so it's hard to say that you will find entries, exits, stop loss, and take profit in this. Still, it will help see trendiness, support, and resistance levels.
Mixing this with other indicators is probably a good idea, but some may find this indicator the only one needed.
Some aspects of the square
The end of the square is important, so where it starts is crucial. The end is important because it is where the price and time expire. The other parts of the square are defined based on their start and end, so placing them right is essential.
So, where to set the start of the square?
The last major low is the most indicated. The minimum price will be the lowest, and the max price will be the last major Top. Note that the indicator uses 1 candle on each point.
After finding the start, the minimum, and the maximum prices for the square, it will draw all lines. Another essential part of the square is The Midpoint.
The midpoint is the most crucial part of the square and is the best way to see if you positioned the square correctly. When the price is inside the square, using the starting candle as the start, a second higher low or a lower high occurs in that spot. When using the Vertical lines in the indicator, it's the middle square inside Gann's square.
The other divisions will be opposing each other most of the time. So if the price is rising in the 1/3 of the square, it's common to see the price fall in the 3/3 of the square.
More information about these aspects here
Considerations
This indicator was meant for price targets and a time calculator for possible support/resistances in the chart. It was created by William Delbert Gann and was part of his setup for trading almost a century ago. The lines will form geometric figures, which Gann used with high accuracy to predict tops/bottoms and when they would occur.
Relative Difference Of Squares Oscillator [CC]The Relative Difference Of Squares Oscillator was created by Marco Alves (Stocks and Commodities Aug 2020 pg 10) and this is a heavily customized version of his indicator that works for single stocks instead of the entire market. I have included extra buy and sell signals to account for strong signals vs normal signals based on some user feedback I got. Buy when the line turns green and sell when it turns red. Keep in mind that this is a lagging indicator so good for trend confirmation.
Let me know if there are any other scripts you would like to see me publish!
P-Square - Estimation of the Nth percentile of a seriesEstimation of the Nth percentile of a series
When working with built-in functions in TradingView we have to limit our length parameters to max 4999. In case we want to use a function on the whole available series (bar 0 all the way to the current bar), we can usually not do this without manually creating these calculations in our code. For things like mean or standard deviation, this is quite trivial, but for things like percentiles, this is usually very costly. In more complex scripts, this becomes impossible because of resource restrictions from the Pine Script execution servers.
One solution to this is to use an estimation algorithm to get close to the true percentile value. Therefore, I have ported this implementation of the P-Square algorithm to Pine Script. P-Square is a fast algorithm that does a good job at estimating percentiles in data streams. Here's the algorithms original paper .
The chart
On the chart we see:
The returns of the series (blue scatter plot)
The mean of the returns of the series (orange line)
The standard deviation of the returns of the series (yellow line)
The actual 84.1th percentile of the returns (white line)
The estimatedl 84.1th percentile of the returns using the P-Square algorithm (green line)
Note: We can see that the returns are not normally distributed as we can see that one standard deviation is higher than the 84.1th percentile. One standard deviation should equal the 84.1th percentile if the data is normally distributed.
Grid SystemThis script plots a a square composed of 8 equilateral triangles ("grid"). User can set the frequency of calculation/interval by adjusting the 't' parameter.
Steps for calculating grid:
1. Find the highest high and lowest low for last 't' periods.
2. Calculate midpoint for prices during that interval (highest high + lowest low) / 2.
3. Center of the grid = {time , price midpoint}.
Interpretation:
Volatility : If price is volatile for a given period, the area of the grid will expand, since the top and bottom sides are based on the highest high and lowest low for the period. So as range for a given period increases, the grid's area increases.
Support and resistance : The grid's center line often acts as the support / resistance line.
Trend Following : The example chart shows Cognex (CGNX) price using an interval of t=365. When the stock's trend was bullish, the area of the grids became increasingly larger and the y-coordinate of each grid was greater than that of the previous grid.
Squared Weighted Moving AverageThe Squared Weighted Moving Average is similar to the classic Weighted Moving Average but the difference is that it squares the weights instead of the classic weight values. Buy if the indicator line is green and sell when it goes red.
Let me know if you would like to see any more scripts from me or if you want something custom done!