Strategy PnL LibraryLibrary "Strategy_PnL_Library"
TODO: This is a library that helps you learn current pnl of open position and use it to create your own dynamic take profit or stop loss rules based on current level of your profit. It should only be used with strategies.
inTrade()
inTrade: Checks if a position is currently open.
Returns: bool: true for yes, false for no.
notInTrade()
inTrade: Checks if a position is currently open. Interchangeable with inTrade but just here for simple semantics.
Returns: bool: true for yes, false for no.
pnl()
pnl: Calculates current profit or loss of position after the commission. If the strategy is not in trade it will always return na.
Returns: float: Current Profit or Loss of position, positive values for profit, negative values for loss.
entryBars()
entryBars: Checks how many bars it's been since the entry of the position.
Returns: int: Returns a int of strategy entry bars back. Minimum value is always corrected to 1 to avoid lookback errors.
pnlvelocity()
pnlvelocity: Calculates the velocity of pnl by following the change in open profit compared to previous bar. If the strategy is not in trade it will always return na.
Returns: float: Returns a float value of pnl velocity.
pnlacc()
pnlacc: Calculates the acceleration of pnl by following the change in profit velocity compared to previous bar. If the strategy is not in trade it will always return na.
Returns: float: Returns a float value of pnl acceleration.
pnljerk()
pnljerk: Calculates the jerk of pnl by following the change in profit acceleration compared to previous bar. If the strategy is not in trade it will always return na.
Returns: float: Returns a float value of pnl jerk.
pnlhigh()
pnlhigh: Calculates the highest value the pnl has reached since the start of the current position. If the strategy is not in trade it will always return na.
Returns: float: Returns a float highest value the pnl has reached.
pnllow()
pnllow: Calculates the lowest value the pnl has reached since the start of the current position. If the strategy is not in trade it will always return na.
Returns: float: Returns a float lowest value the pnl has reached.
pnldev()
pnldev: Calculates the deviance of the pnl since the start of the current position. If the strategy is not in trade it will always return na.
Returns: float: Returns a float deviance value of the pnl.
pnlvar()
pnlvar: Calculates the variance value of the pnl since the start of the current position. If the strategy is not in trade it will always return na.
Returns: float: Returns a float variance value of the pnl.
pnlstdev()
pnlstdev: Calculates the stdev value of the pnl since the start of the current position. If the strategy is not in trade it will always return na.
Returns: float: Returns a float stdev value of the pnl.
pnlmedian()
pnlmedian: Calculates the median value of the pnl since the start of the current position. If the strategy is not in trade it will always return na.
Returns: float: Returns a float median value of the pnl.
Statistics
ctndLibrary "ctnd"
Description:
Double precision algorithm to compute the cumulative trivariate normal distribution
found in A.Genz, Numerical computation of rectangular bivariate and trivariate normal
and t probabilities”, Statistics and Computing, 14, (3), 2004. The cumulative trivariate
normal is needed to price window barrier options, see G.F. Armstrong, Valuation formulae
or window barrier options”, Applied Mathematical Finance, 8, 2001.
References:
link.springer.com
www.tandfonline.com
citeseerx.ist.psu.edu
The Complete Guide to Option Pricing Formulas, 2nd ed. (Espen Gaarder Haug)
CTND(LIMIT1, LIMIT2, LIMIT3, SIGMA1, SIGMA2, SIGMA3)
Returns the Cumulative Trivariate Normal Distribution
Parameters:
LIMIT1 : float,
LIMIT2 : float,
LIMIT3 : float,
SIGMA1 : float,
SIGMA2 : float,
SIGMA3 : float,
Returns: float.
combinLibrary "combin"
Description:
The combin function is a the combination function
as it calculates the number of possible combinations for two given numbers.
This function takes two arguments: the number and the number_chosen.
For example, if the number is 5 and the number chosen is 1,
there are 5 combinations, giving 5 as a result.
Reference:
ideone.com
support.microsoft.com
combin(n, kin)
Returns the number of combinations for a given number of items. Use to determine the total possible number of groups for a given number of items.
Parameters:
n : int, The number of items.
kin : int, The number of items in each combination.
Returns: int.
norminvLibrary "norminv"
Description:
An inverse normal distribution is a way to work backwards
from a known probability to find an x-value. It is an informal term and
doesn't refer to a particular probability distribution. Returns the
value of the inverse normal distribution function for a specified value,
mean, and standard deviation.
Reference:
github.com
support.microsoft.com
norminv(x, mean, stdev)
Returns the value of the inverse normal distribution function for a specified value, mean, and standard deviation.
Parameters:
x : float, The input to the normal distribution function.
mean : float, The mean (mu) of the normal distribution function
stdev : float, The standard deviation (sigma) of the normal distribution function.
Returns: float.
cbndLibrary "cbnd"
Description:
A standalone Cumulative Bivariate Normal Distribution (CBND) functions that do not require any external libraries.
This includes 3 different CBND calculations: Drezner(1978), Drezner and Wesolowsky (1990), and Genz (2004)
Comments:
The standardized cumulative normal distribution function returns the probability that one random
variable is less than a and that a second random variable is less than b when the correlation
between the two variables is p. Since no closed-form solution exists for the bivariate cumulative
normal distribution, we present three approximations. The first one is the well-known
Drezner (1978) algorithm. The second one is the more efficient Drezner and Wesolowsky (1990)
algorithm. The third is the Genz (2004) algorithm, which is the most accurate one and therefore
our recommended algorithm. West (2005b) and Agca and Chance (2003) discuss the speed and
accuracy of bivariate normal distribution approximations for use in option pricing in
ore detail.
Reference:
The Complete Guide to Option Pricing Formulas, 2nd ed. (Espen Gaarder Haug)
CBND1(A, b, rho)
Returns the Cumulative Bivariate Normal Distribution (CBND) using Drezner 1978 Algorithm
Parameters:
A : float,
b : float,
rho : float,
Returns: float.
CBND2(A, b, rho)
Returns the Cumulative Bivariate Normal Distribution (CBND) using Drezner and Wesolowsky (1990) function
Parameters:
A : float,
b : float,
rho : float,
Returns: float.
CBND3(x, y, rho)
Returns the Cumulative Bivariate Normal Distribution (CBND) using Genz (2004) algorithm (this is the preferred method)
Parameters:
x : float,
y : float,
rho : float,
Returns: float.
cndLibrary "cnd"
Cumulative Normal Distribution
CND1(x)
Returns the Cumulative Normal Distribution (CND) using the Hart (1968) method. (preferred method, 14-18 decimal accuracy)
Parameters:
x : float,
Returns: float.
CND2(x)
Returns the Cumulative Normal Distribution (CND) using the Abromowitz and Stegun (1974) Polynomial Approximation.
Parameters:
x : float,
Returns: float.
CND3(x)
Returns the Cumulative Normal Distribution (CND) using Newton-Cotes method, Boole’s rule
Parameters:
x : float,
Returns: float.
chi2InvLibrary "chi2Inv"
chi2Inv(p, n)
Returns the inverse cumulative distribution function (icdf) of the chi-square distribution with degrees of freedom nu, evaluated at the probability values in p. Goldstein approximation
Parameters:
p : float, probability
n : float, degress of freedom source.
Returns: float.
TradersCustomLibraryLibrary "TradersCustomLibrary"
TODO: add library description here
SelectOptimalTimeframeTrendlineSettings()
calculateShortStopLoss()
calculateLongStopLoss()
werdygerTrend()
trendLines()
stoch()
timeToString()
TALibrary "TA"
General technical analysis functions
div_bull(pS, iS, cp_length_after, cp_length_before, pivot_length, lookback, no_broken, pW, iW, hidW, regW)
Test for bullish divergence
Parameters:
pS : Price series (float)
iS : Indicator series (float)
cp_length_after : Bars after current (divergent) pivot low to be considered a valid pivot (optional int)
cp_length_before : Bars before current (divergent) pivot low to be considered a valid pivot (optional int)
pivot_length : Bars before and after prior pivot low to be considered valid pivot (optional int)
lookback : Bars back to search for prior pivot low (optional int)
no_broken : Flag to only consider divergence valid if the pivot-to-pivot trendline is unbroken (optional bool)
pW : Weight of change in price, used in degree of divergence calculation (optional float)
iW : Weight of change in indicator, used in degree of divergence calculation (optional float)
hidW : Weight of hidden divergence, used in degree of divergence calculation (optional float)
regW : Weight of regular divergence, used in degree of divergence calculation (optional float)
Returns:
flag = true if divergence exists (bool)
degree = degree (strength) of divergence (float)
type = 1 = regular, 2 = hidden (int)
lx1 = x coordinate 1 (int)
ly1 = y coordinate 1 (float)
lx2 = x coordinate 2 (int)
ly2 = y coordinate 2 (float)
div_bear(pS, iS, cp_length_after, cp_length_before, pivot_length, lookback, no_broken, pW, iW, hidW, regW)
Test for bearish divergence
Parameters:
pS : Price series (float)
iS : Indicator series (float)
cp_length_after : Bars after current (divergent) pivot high to be considered a valid pivot (optional int)
cp_length_before : Bars before current (divergent) pivot highto be considered a valid pivot (optional int)
pivot_length : Bars before and after prior pivot high to be considered valid pivot (optional int)
lookback : Bars back to search for prior pivot high (optional int)
no_broken : Flag to only consider divergence valid if the pivot-to-pivot trendline is unbroken (optional bool)
pW : Weight of change in price, used in degree of divergence calculation (optional float)
iW : Weight of change in indicator, used in degree of divergence calculation (optional float)
hidW : Weight of hidden divergence, used in degree of divergence calculation (optional float)
regW : Weight of regular divergence, used in degree of divergence calculation (optional float)
Returns:
flag = true if divergence exists (bool)
degree = degree (strength) of divergence (float)
type = 1 = regular, 2 = hidden (int)
lx1 = x coordinate 1 (int)
ly1 = y coordinate 1 (float)
lx2 = x coordinate 2 (int)
ly2 = y coordinate 2 (float)
testJust testing how to use libraries ignore this
Just testing how to use libraries ignore this
Just testing how to use libraries ignore this
Just testing how to use libraries ignore this
Just testing how to use libraries ignore this
AllTimeHighLowLibrary "AllTimeHighLow"
Provides functions calculating the all-time high/low of values.
hi(val)
Calculates the all-time high of a series.
Parameters:
val : Series to use (`high` is used if no argument is supplied).
Returns: The all-time high for the series.
lo(val)
Calculates the all-time low of a series.
Parameters:
val : Series to use (`low` is used if no argument is supplied).
Returns: The all-time low for the series.
L_BetaLibrary "L_Beta"
TODO: add library description here
length()
beta()
simple_beta()
index_selector()
CalulateWinLossLibrary "CalulateWinLoss"
TODO: add library description here
colorwhitered(x)
TODO: add function description here
Parameters:
x : TODO: add parameter x description here
Returns: TODO: add what function returns
colorredwhite()
cal()
FunctionPatternFrequencyLibrary "FunctionPatternFrequency"
Counts the word or integer number pattern frequency on a array.
reference:
rosettacode.org
count(pattern)
counts the number a pattern is repeated.
Parameters:
pattern : : array : array with patterns to be counted.
Returns:
array : list of unique patterns.
array : list of counters per pattern.
usage:
count(array.from('a','b','c','a','b','a'))
count(pattern)
counts the number a pattern is repeated.
Parameters:
pattern : : array : array with patterns to be counted.
Returns:
array : list of unique patterns.
array : list of counters per pattern.
usage:
count(array.from(1,2,3,1,2,1))
DatasetWeatherTokyoMeanAirTemperatureLibrary "DatasetWeatherTokyoMeanAirTemperature"
Provides a data set of the monthly mean air temperature (°C) for the city of Tokyo in Japan.
this was just for fun, no financial implications in this.
reference:
www.data.jma.go.jp
TOKYO WMO Station ID:47662 Lat 35o41.5'N Lon 139o45.0'E
year_()
the years of the data set.
Returns: array : year values.
january()
the january values of the dataset
Returns: array\ : data values for january.
february()
the february values of the dataset
Returns: array\ : data values for february.
march()
the march values of the dataset
Returns: array\ : data values for march.
april()
the april values of the dataset
Returns: array\ : data values for april.
may()
the may values of the dataset
Returns: array\ : data values for may.
june()
the june values of the dataset
Returns: array\ : data values for june.
july()
the july values of the dataset
Returns: array\ : data values for july.
august()
the august values of the dataset
Returns: array\ : data values for august.
september()
the september values of the dataset
Returns: array\ : data values for september.
october()
the october values of the dataset
Returns: array\ : data values for october.
november()
the november values of the dataset
Returns: array\ : data values for november.
december()
the december values of the dataset
Returns: array\ : data values for december.
annual()
the annual values of the dataset
Returns: array\ : data values for annual.
select_month(idx)
get the temperature values for a specific month.
Parameters:
idx : int, month index (1 -> 12 | any other value returns annual average values).
Returns: array\ : data values for selected month.
select_value(year_, month_)
get the temperature value of a specified year and month.
Parameters:
year_ : int, year value.
month_ : int, month index (1 -> 12 | any other value returns annual average values).
Returns: float : value of specified year and month.
diff_to_median(month_)
the difference of the month air temperature (ºC) to the median of the sample.
Parameters:
month_ : int, month index (1 -> 12 | any other value returns annual average values).
Returns: float : difference of current month to median in (Cº)
FunctionDynamicTimeWarpingLibrary "FunctionDynamicTimeWarping"
"In time series analysis, dynamic time warping (DTW) is an algorithm for
measuring similarity between two temporal sequences, which may vary in
speed. For instance, similarities in walking could be detected using DTW,
even if one person was walking faster than the other, or if there were
accelerations and decelerations during the course of an observation.
DTW has been applied to temporal sequences of video, audio, and graphics
data — indeed, any data that can be turned into a linear sequence can be
analyzed with DTW. A well-known application has been automatic speech
recognition, to cope with different speaking speeds. Other applications
include speaker recognition and online signature recognition.
It can also be used in partial shape matching applications."
"Dynamic time warping is used in finance and econometrics to assess the
quality of the prediction versus real-world data."
~~ wikipedia
reference:
en.wikipedia.org
towardsdatascience.com
github.com
cost_matrix(a, b, w)
Dynamic Time Warping procedure.
Parameters:
a : array, data series.
b : array, data series.
w : int , minimum window size.
Returns: matrix optimum match matrix.
traceback(M)
perform a backtrace on the cost matrix and retrieve optimal paths and cost between arrays.
Parameters:
M : matrix, cost matrix.
Returns: tuple:
array aligned 1st array of indices.
array aligned 2nd array of indices.
float final cost.
reference:
github.com
report(a, b, w)
report ordered arrays, cost and cost matrix.
Parameters:
a : array, data series.
b : array, data series.
w : int , minimum window size.
Returns: string report.
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.
AdxlLibrary "Adxl"
Functions to calculate the Average Directional Index
getDirectionUp(bar, lookback)
Bar high changed from open for bar
Parameters:
bar : series int The bar to calculate at
lookback : series int The lookback period
Returns: series float
getDirectionDown(bar, lookback)
Bar low changed from open for bar
Parameters:
bar : series int The bar to calculate at
lookback : series int The lookback period
Returns: series float
getPositiveDirectionalMovement(bar, lookback)
Positive directional movement for bar during lookback
Parameters:
bar : series int The bar to calculate at
lookback : series int The lookback period
Returns: series float
getNegativeDirectionalMovement(bar, lookback)
Negative directional movement for bar during lookback
Parameters:
bar : series int The bar to calculate at
lookback : series int The lookback period
Returns: series float
getTrueRangeMovingAverage(bar, lookback)
True range moving average for bar during lookback
Parameters:
bar : series int The bar to calculate at
lookback : simple int The lookback period
Returns: series int
getDirectionUpIndex(bar, lookback)
Direction up index for bar during lookback
Parameters:
bar : series int The bar to calculate at
lookback : simple int The lookback period
Returns: series int
getDirectionDownIndex(bar, lookback)
Direction down index for bar during lookback
Parameters:
bar : series int The bar to calculate at
lookback : simple int The lookback period
Returns: series int
getTotalDirectionIndex(bar, lookback)
Total direction index for bar during lookback
Parameters:
bar : series int The bar to calculate at
lookback : simple int The lookback period
Returns: series int
getAverageDirectionalIndex(bar, lookback)
Average Directional Index (ADX) for bar during lookback
Parameters:
bar : series int The bar to calculate at
lookback : simple int The lookback period
Returns: series int
AdxCalcHourlyLibrary "AdxCalcHourly"
getBars()
getBars: Returns the number of bars to use in the historical lookback period
Returns: simple int
directionDown()
directionDown: Calculates the direction down for bar_index
Returns: series float
directionUp()
directionUp: Calculates the direction up for bar_index
Returns: series float
trueRangeMovingAverage()
trueRangeMovingAverage: Calculates the true range moving average over the historical lookback period
Returns: series float
positiveDirectionalMovement()
positiveDirectionalMovement: Calculates the positive direction movement for bar_index
Returns: series float
negativeDirectionalMovement()
negativeDirectionalMovement: Calculates the begative direction movement for bar_index
Returns: series float
totalDirectionDown()
totalDirectionDown: Calculates the total direction down for the historical lookback period
Returns: series float
totalDirectionUp()
totalDirectionUp: Calculates the total direction up for the historical lookback period
Returns: series float
totalDirection()
totalDirection: Calculates the total direction movement for the historical lookback period
Returns: series float
averageDirectionalIndex()
averageDirectionalIndex: Calculates the average directional index (ADX) based on the trend for the historical lookback period
Returns: series float
getAdxHistoricalAverage()
getAdxHistoricalAverage: Calculates the average directional index (ADX) for the historical lookback period
Returns: series float
getAdxHistoricalHigh()
getAdxHistoricalHigh: Calculates the historical high of the directional index (ADX) for the historical lookback period
Returns: series float
getAdxHistoricalLow()
getAdxHistoricalLow: Calculates the historical low of the directional index (ADX) for the historical lookback period
Returns: series float
getAdxOpinion()
getAdxOpinion: Calculatesa recomendation for the directional index (ADX) based on the historical lookback period
Returns: series float
WpProbabilisticLibLibrary "WpProbabilisticLib"
Library that contains functions to calculate probabilistic based on historical candle analysis
CandleType(open, close) This function check what type of candle is, based on its close and open prices
Parameters:
open : series float (open price)
close : series float (close price)
Returns: This function return the candle type (1 for Bullish, -1 Bearish, 0 as Doji candle)
CandleTypePercentDiff(open, close, qtd_candles_before, consider_dojis) This function calculates the percentage difference between Bullish and Bearish in a candlestick range back in time and which is the type with the least occurrences
Parameters:
open : series float (open price series)
close : series float (close price series)
qtd_candles_before : simple int (Number of candles before to calculate)
consider_dojis : simple string (How to consider dojis (no consider "NO", as bearish "AS_RED", as bullish "AS_GREEN"))
Returns: tuple(float, int) (Returns the percentage difference between Bullish and Bearish candles and which type of candle has the least occurrences)
PivotThis library was designed to create three different datasets using Bill Williams fractals. The goal is to spot trends in reversal data and ultimately use these datasets to help predict future price reversals.
First, the pivot() function is used to initialize and populate three separate arrays (high pivot , low pivot , all pivots ). Since each high/low price depends on the bar_index, the bar_index, pivot direction(high/low), and high/low values are compressed into a string to maintain the data's integrity ("__"). Once each string array is populated and organized by bar_index, all three are returned inside a tuple. The return value must be deconstructed H,L,A =pivot() for each array's values to be accessed using getPivot() . This boilerplate allows for data to be accessed more efficiently in a recursive environment. getPivot() was designed to be used inside of a for or while block to populate matrices for further analyses. Again, getPivot() return values must be exposed through deconstruction. x,d,y =getPivot(). See code for more details.
pivot(int XLR) initializes and populates arrays
Parameters
XLR - number of bars to the left and right that must be lower for a high to be considered a pivotHigh, or vice versa. This number will drastically change the size and scope of the returned datasets. smaller values will produce much larger datasets, which might model short term price activity well. In contrast, larger values will produce smaller datasets which might model longer term price activity well.
Returns - tuple [string ]
getPivot(string arrayID, int index) accesses array data
Parameters
arrayID - the variable name for one of the three arrays returned by pivot().
index - the index of the provided array, with 0 being the most recent pivot point. can be set to " i " in a loop to access values recursively
Returns - tuple
AutoFiboRetraceLibrary "AutoFiboRetrace"
TODO: add library description here
fun(x) TODO: add function description here
Parameters:
x : TODO: add parameter x description here
Returns: TODO: add what function returns
MonthlyReturnsVsMarketLibrary "MonthlyReturnsVsMarket" is a repackaging of the script here
Credits to @QuantNomad for orginal script
Now you can avoid to pollute your own strategy's code with the monthly returns table code and just import the library and call displayMonthlyPnL(int precision) function
To be used in strategy scripts.