Machine Learning: Trend Lines [YinYangAlgorithms]Trend lines have always been a key indicator that may help predict many different types of price movements. They have been well known to create different types of formations such as: Pennants, Channels, Flags and Wedges. The type of formation they create is based on how the formation was created and the angle it was created. For instance, if there was a strong price increase and then there is a Wedge where both end points meet, this is considered a Bull Pennant. The formations Trend Lines create may be powerful tools that can help predict current Support and Resistance and also Future Momentum changes. However, not all Trend Lines will create formations, and alone they may stand as strong Support and Resistance locations on the Vertical.
The purpose of this Indicator is to apply Machine Learning logic to a Traditional Trend Line Calculation, and therefore allowing a new approach to a modern indicator of high usage. The results of such are quite interesting and goes to show the impacts a simple KNN Machine Learning model can have on Traditional Indicators.
Tutorial:
There are a few different settings within this Indicator. Many will greatly impact the results and if any are changed, lots will need ‘Fine Tuning’. So let's discuss the main toggles that have great effects and what they do before discussing the lengths. Currently in this example above we have the Indicator at its Default Settings. In this example, you can see how the Trend Lines act as key Support and Resistance locations. Due note, Support and Resistance are a relative term, as is their color. What starts off as Support or Resistance may change when the price crosses over / under them.
In the example above we have zoomed in and circled locations that exhibited markers of Support and Resistance along the Trend Lines. These Trend Lines are all created using the Default Settings. As you can see from the example above; just because it is a Green Upwards Trend Line, doesn’t mean it’s a Support Line. Support and Resistance is always shifting on Trend Lines based on the prices location relative to them.
We won’t go through all the Formations Trend Lines make, but the example above, we can see the Trend Lines formed a Downward Channel. Channels are when there are two parallel downwards Trend Lines that are at a relatively similar angle. This means that they won’t ever meet. What may happen when the price is within these channels, is it may bounce between the upper and lower bounds. These Channels may drive the price upwards or downwards, depending on if it is in an Upwards or Downwards Channel.
If you refer to the example above, you’ll notice that the Trend Lines are formed like traditional Trend Lines. They don’t stem from current Highs and Lows but rather Machine Learning Highs and Lows. More often than not, the Machine Learning approach to Trend Lines cause their start point and angle to be quite different than a Traditional Trend Line. Due to this, it may help predict Support and Resistance locations at are more uncommon and therefore can be quite useful.
In the example above we have turned off the toggle in Settings ‘Use Exponential Data Average’. This Settings uses a custom Exponential Data Average of the KNN rather than simply averaging the KNN. By Default it is enabled, but as you can see when it is disabled it may create some pretty strong lasting Trend Lines. This is why we advise you ZOOM OUT AS FAR AS YOU CAN. Trend Lines are only displayed when you’ve zoomed out far enough that their Start Point is visible.
As you can see in this example above, there were 3 major Upward Trend Lines created in 2020 that have had a major impact on Support and Resistance Locations within the last year. Lets zoom in and get a closer look.
We have zoomed in for this example above, and circled some of the major Support and Resistance locations that these Upward Trend Lines may have had a major impact on.
Please note, these Machine Learning Trend Lines aren’t a ‘One Size Fits All’ kind of thing. They are completely customizable within the Settings, so that you can get a tailored experience based on what Pair and Time Frame you are trading on.
When any values are changed within the Settings, you’ll likely need to ‘Fine Tune’ the rest of the settings until your desired result is met. By default the modifiable lengths within the Settings are:
Machine Learning Length: 50
KNN Length:5
Fast ML Data Length: 5
Slow ML Data Length: 30
For example, let's toggle ‘Use Exponential Data Averages’ back on and change ‘Fast ML Data Length’ from 5 to 20 and ‘Slow ML Data Length’ from 30 to 50.
As you can in the example above, all of the lines have changed. Although there are still some strong Support Locations created by the Upwards Trend Lines.
We will conclude our Tutorial here. Hopefully you’ve learned how to use Machine Learning Trend Lines and will be able to now see some more unorthodox Support and Resistance locations on the Vertical.
Settings:
Use Machine Learning Sources: If disabled Traditional Trend line sources (High and Low) will be used rather than Rational Quadratics.
Use KNN Distance Sorting: You can disable this if you wish to not have the Machine Learning Data sorted using KNN. If disabled trend line logic will be Traditional.
Use Exponential Data Average: This Settings uses a custom Exponential Data Average of the KNN rather than simply averaging the KNN.
Machine Learning Length: How strong is our Machine Learning Memory? Please note, when this value is too high the data is almost 'too' much and can lead to poor results.
K-Nearest Neighbour (KNN) Length: How many K-Nearest Neighbours are allowed with our Distance Clustering? Please note, too high or too low may lead to poor results.
Fast ML Data Length: Fast and Slow speed needs to be adjusted properly to see results. 3/5/7 all seem to work well for Fast.
Slow ML Data Length: Fast and Slow speed needs to be adjusted properly to see results. 20 - 50 all seem to work well for Slow.
If you have any questions, comments, ideas or concerns please don't hesitate to contact us.
HAPPY TRADING!
Fraction
HL-D Close Fraction Oscillator | AdulariDescription:
This indicator calculates the difference between price high's and low's, and fractions it by the close price. If it calculates the difference between a high and low or low and high is defined by whether the current close is higher than the previous close. It is then also rescaled to ensure the value is always appropriate compared to the last set amount of bars.
This indicator can be used to determine whether a market is trending or ranging, and if so in which direction it is trending.
How do I use it?
Never use this indicator as standalone trading signal, it should be used as confluence.
When the value is above the middle line this shows the bullish trend is strong.
When the value is below the middle line this shows the bearish trend is strong.
When the value crosses above the upper line this indicates the trend may reverse downwards.
When the value crosses below the lower line this indicates the trend may reverse upwards.
When the value crosses above the signal this indicates the current bearish trend is getting weak and may reverse upwards.
When the value crosses below the signal this indicates the current bullish trend is getting weak and may reverse downwards.
Features:
Oscillator value indicating the difference between highs and lows fractioned by the close price.
Signal indicating a clear trend and base line value.
Horizontal lines such as oversold, overbought and middle lines, indicating possible interest zones.
How does it work?
1 — Define trend by checking if current close is above or below previous close.
2 — If the current close is above the previous close, calculate the oscillator's value using this formula:
(high - low) / close
2 — If the current close is below the previous close, calculate the oscillator's value using this formula:
(low - high) / close
3 — Smooth the original value using a specified moving average.
4 — Rescale the value using this formula:
newMin + (newMax - newMin) * (value - oldMin) / math.max(oldMax - oldMin, 10e-10)
5 — Calculate signal value by applying smoothing to the oscillator's value.
fractionLibrary "fraction"
Fraction Creation and Basic Operations.
Cracked a tough problem in making this Polarity Agnostic Decimal without a cheating "abs * sign of input".
it's quite fast, however still test for errors before production use.
>> Big Neon Sign on 1/0 value. <<
Int Array (LOC 0/1)..
To/From Decimal(float)
Comparison ( < / == / >)
Add / Sub / Mult / Div
Invert polarity +/-
String output with 2 formats ..
make(_numerator, _denominator, _val)
Parameters:
_numerator : (int) above the line integer ie: ____ of (___ / bottom )
_denominator : (int) below the line integer ie: ____ of (top / ______ )
_val : (int) OPTIONAL (for no real reason including it) integer to multiply
Returns: array where index 0 is Numerator, 1 is Denominator
add(_fraction, _fraction2)
Perform add operation (left adds right onto )
Parameters:
_fraction : (array) left side Fraction Object
_fraction2 : (array) right side Fraction Object
Returns: array where index 0 is Numerator, 1 is Denominator
subtract(_fraction, _fraction2)
Perform subtract operation (left subtracts right from )
Parameters:
_fraction : (array) left side Fraction Object
_fraction2 : (array) right side Fraction Object
Returns: array where index 0 is Numerator, 1 is Denominator
multiply(_fraction, _fraction2)
Perform multiply operation (left multiplies by right )
Parameters:
_fraction : (array) left side Fraction Object
_fraction2 : (array) right side Fraction Object
Returns: array where index 0 is Numerator, 1 is Denominator
divide(_fraction, _fraction2)
Perform divide operation (left divides by right )
Parameters:
_fraction : (array) left side Fraction Object
_fraction2 : (array) right side Fraction Object
Returns: array where index 0 is Numerator, 1 is Denominator
negative(_fraction)
Perform Negative number inversion ie: (-1/2 => 1/2) or (3/5 => -3/5)
Parameters:
_fraction : (array) Fraction Object to invert to/from negative
Returns: array where index 0 is Numerator, 1 is Denominator
isSmaller(_fraction, _fraction2)
Check if first fraction is smaller
Parameters:
_fraction : (array) left side Fraction Object
_fraction2 : (array) right side Fraction Object
Returns: True if smaller, false if bigger
isLarger(_fraction, _fraction2)
Check if first fraction is larger
Parameters:
_fraction : (array) left side Fraction Object
_fraction2 : (array) right side Fraction Object
Returns: True if smaller, false if bigger
isEqual(_fraction, _fraction2)
Check if first fraction is equal
Parameters:
_fraction : (array) left side Fraction Object
_fraction2 : (array) right side Fraction Object
Returns: True if smaller, false if bigger
fromDec(_input, _epsilon, _iterations)
Convert Decimal to Fraction array
note : this is my own Negative Number Capable (tiny speed loss)
adaptation of the fastest algo out there
Exclusive for Tradingview.
Parameters:
_input : (float) Decimal Input
_epsilon : (int) (OPTIONAL) to precision 0's after dec 0.0000 -> epsilon 0's
_iterations : (int) (OPTIONAL) Maximum iterations Till give up
Returns: array where index 0 is Numerator, 1 is Denominator
toDec()
Convert Fraction to Decimal Output
Returns: Float of fration
toString(_fraction)
Create "A/B" or "A and B/C" String Value of Fraction.
Parameters:
_fraction : (array) Fraction Object to invert to/from negative
Returns: String as (-)? A and B/C format
FunctionKellyCriterionLibrary "FunctionKellyCriterion"
Kelly criterion methods.
the kelly criterion helps with the decision of how much one should invest in
a asset as long as you know the odds and expected return of said asset.
simplified(win_p, rr)
simplified version of the kelly criterion formula.
Parameters:
win_p : float, probability of winning.
rr : float, reward to risk rate.
Returns: float, optimal fraction to risk.
usage:
simplified(0.55, 1.0)
partial(win_p, loss_p, win_rr, loss_rr)
general form of the kelly criterion formula.
Parameters:
win_p : float, probability of the investment returns a positive outcome.
loss_p : float, probability of the investment returns a negative outcome.
win_rr : float, reward on a positive outcome.
loss_rr : float, reward on a negative outcome.
Returns: float, optimal fraction to risk.
usage:
partial(0.6, 0.4, 0.6, 0.1)
from_returns(returns)
Calculate the fraction to invest from a array of returns.
Parameters:
returns : array trade/asset/strategy returns.
Returns: float, optimal fraction to risk.
usage:
from_returns(array.from(0.1,0.2,0.1,-0.1,-0.05,0.05))
final_f(fraction, max_expected_loss)
Final fraction, eg. if fraction is 0.2 and expected max loss is 10%
then you should size your position as 0.2/0.1=2 (leverage, 200% position size).
Parameters:
fraction : float, aproximate percent fraction invested.
max_expected_loss : float, maximum expected percent on a loss (ex 10% = 0.1).
Returns: float, final fraction to invest.
usage:
final_f(0.2, 0.5)
hpr(fraction, trade, biggest_loss)
Holding Period Return function
Parameters:
fraction : float, aproximate percent fraction invested.
trade : float, profit or loss in a trade.
biggest_loss : float, value of the biggest loss on record.
Returns: float, multiplier of effect on equity so that a win of 5% is 1.05 and loss of 5% is 0.95.
usage:
hpr(fraction=0.05, trade=0.1, biggest_loss=-0.2)
twr(returns, rr, eps)
Terminal Wealth Relative, returns a multiplier that can be applied
to the initial capital that leadds to the final balance.
Parameters:
returns : array, list of trade returns.
rr : float , reward to risk rate.
eps : float , minimum resolution to void zero division.
Returns: float, optimal fraction to invest.
usage:
twr(returns=array.from(0.1,-0.2,0.3), rr=0.6)
ghpr(returns, rr, eps)
Geometric mean Holding Period Return, represents the average multiple made on the stake.
Parameters:
returns : array, list of trade returns.
rr : float , reward to risk rate.
eps : float , minimum resolution to void zero division.
Returns: float, multiplier of effect on equity so that a win of 5% is 1.05 and loss of 5% is 0.95.
usage:
ghpr(returns=array.from(0.1,-0.2,0.3), rr=0.6)
run_coin_simulation(fraction, initial_capital, n_series, n_periods)
run multiple coin flipping (binary outcome) simulations.
Parameters:
fraction : float, fraction of capital to bet.
initial_capital : float, capital at the start of simulation.
n_series : int , number of simulation series.
n_periods : int , number of periods in each simulation series.
Returns: matrix(n_series, n_periods), matrix with simulation results per row.
usage:
run_coin_simulation(fraction=0.1)
run_asset_simulation(returns, fraction, initial_capital)
run a simulation over provided returns.
Parameters:
returns : array, trade, asset or strategy percent returns.
fraction : float , fraction of capital to bet.
initial_capital : float , capital at the start of simulation.
Returns: array, array with simulation results.
usage:
run_asset_simulation(returns=array.from(0.1,-0.2,0.-3,0.4), fraction=0.1)
strategy_win_probability()
calculate strategy() current probability of positive outcome in a trade.
strategy_avg_won()
calculate strategy() current average won on a trade with positive outcome.
strategy_avg_loss()
calculate strategy() current average lost on a trade with negative outcome.
MTF High and Low FractionsMTF High and Low Fractions
Description
An experimental script that prints 1/3, 1/4 and 1/8 levels of the previous timeframe's high and low to the current timeframe. The idea is quite simple. It mirrors the the previous high and low with user selected levels. The default setting is the previous daily high and low but can be customized on user discretion.
New levels are printed after the close of the previous timeframe and open of the new timeframe (user's timeframe setting).
How To Use
Levels should not be used blindly. Levels can be used as confluence when aligned with high probability supply and demand zones, support, resistance, order blocks, and so on.
How To Count DecimalsCustom f_nDecimals() function returns precision of decimal numbers of the following forms:
const, input, simple, and series of the following types: float, integer, and string.
Error checking is performed for valid numbers and invalid values return NaN.
NOTICE: This is an example script and not meant to be used as an actual strategy. By using this script or any portion thereof, you acknowledge that you have read and understood that this is for research purposes only and I am not responsible for any financial losses you may incur by using this script!