Repaints Machine Learning: Logistic Regression For ThinkOrSwim

Repaints

jmoney99

New member
With the volatility filter enabled I've found it pretty accurate at predicting long / short signals on the 3 minute timeframe.

The Author states:
This strategy uses a classic machine learning algorithm that came from statistics - Logistic Regression (LR).

The first and most important thing about logistic regression is that it is not a 'Regression' but a 'Classification' algorithm. The name itself is somewhat misleading. Regression gives a continuous numeric output but most of the time we need the output in classes (i.e. categorical, discrete). For example, we want to classify emails into “spam” or 'not spam', classify treatment into “success” or 'failure', classify statement into “right” or 'wrong', classify election data into 'fraudulent vote' or 'non-fraudulent vote', classify market move into 'long' or 'short' and so on. These are the examples of logistic regression having a binary output (also called dichotomous).

You can also think of logistic regression as a special case of linear regression when the outcome variable is categorical, where we are using log of odds as dependent variable. In simple words, it predicts the probability of occurrence of an event by fitting data to a logit function.

Basically, the theory behind Logistic Regression is very similar to the one from Linear Regression, where we seek to draw a best-fitting line over data points, but in Logistic Regression, we don’t directly fit a straight line to our data like in linear regression. Instead, we fit a S shaped curve, called Sigmoid, to our observations, that best SEPARATES data points. Technically speaking, the main goal of building the model is to find the parameters (weights) using gradient descent.

In this script the LR algorithm is retrained on each new bar trying to classify it into one of the two categories. This is done via the logistic_regression function by updating the weights w in the loop that continues for iterations number of times. In the end the weights are passed through the sigmoid function, yielding a prediction.

Mind that some assets require to modify the script's input parameters. For instance, when used with BTCUSD and USDJPY, the 'Normalization Lookback' parameter should be set down to 4 (2,...,5..), and optionally the 'Use Price Data for Signal Generation?' parameter should be checked. The defaults were tested with EURUSD.
ruPoeHm.png


I'm trying to use chatgpt to convert a trading view script (Machine Learning Logistic Regression by Capissimo) but getting errors in thinkscript. With the volatility filter enabled I've found it pretty accurate at predicting long / short signals on the 3 minute timeframe. Anyone have any ideas how to convert it or if there is a conversion app available? Sorry I'm not that familiar with Thinkscript coding and just started using ThinkorSwim. Any help would be appreciated. Here is the link to the script: https://www.tradingview.com/script/49YIV1jW-Machine-Learning-Logistic-Regression/
 
Last edited by a moderator:
I'm trying to use chatgpt to convert a trading view script (Machine Learning Logistic Regression by Capissimo) but getting errors in thinkscript. With the volatility filter enabled I've found it pretty accurate at predicting long / short signals on the 3 minute timeframe. Anyone have any ideas how to convert it or if there is a conversion app available? Sorry I'm not that familiar with Thinkscript coding and just started using ThinkorSwim. Any help would be appreciated. Here is the link to the script: https://www.tradingview.com/script/49YIV1jW-Machine-Learning-Logistic-Regression/

Code is below:
Code:
/ This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © capissimo

//@version=4
study('Machine Learning: Logistic Regression (v.3)', '', true)

// Multi-timeframe Strategy based on Logistic Regression algorithm

// Description:

// This strategy uses a classic machine learning algorithm that came from statistics -
// Logistic Regression (LR).

// The first and most important thing about logistic regression is that it is not a
// 'Regression' but a 'Classification' algorithm. The name itself is somewhat misleading.
// Regression gives a continuous numeric output but most of the time we need the output in
// classes (i.e. categorical, discrete). For example, we want to classify emails into “spam” or
// 'not spam',  classify treatment into “success” or 'failure', classify statement into “right”
// or 'wrong', classify election data into 'fraudulent vote' or 'non-fraudulent vote',
// classify market move into 'long' or 'short' and so on. These are the examples of
// logistic regression having a binary output (also called dichotomous).

// You can also think of logistic regression as a special case of linear regression when the
// outcome variable is categorical, where we are using log of odds as dependent variable.
// In simple words, it predicts the probability of occurrence of an event by fitting data to a
// logit function.

// Basically, the theory behind Logistic Regression is very similar to the one from Linear
// Regression, where we seek to draw a best-fitting line over data points, but in Logistic
// Regression, we don’t directly fit a straight line to our data like in linear regression.
// Instead, we fit a S shaped curve, called Sigmoid, to our observations, that best
// SEPARATES data points. Technically speaking, the main goal of building the model is to
// find the parameters (weights) using gradient descent.

// In this script the LR algorithm is retrained on each new bar trying to classify it
// into one of the two categories. This is done via the logistic_regression function by
// updating the weights w in the loop that continues for iterations number of times.
// In the end the weights are passed through the sigmoid function, yielding a
// prediction.

// Mind that some assets require to modify the script's input parameters. For instance,
// when used with BTCUSD and USDJPY, the 'Normalization Lookback' parameter should be set
// down to 4 (2,...,5..), and optionally the 'Use Price Data for Signal Generation?'
// parameter should be checked. The defaults were tested with EURUSD.

// Note: TradingViews's playback feature helps to see this strategy in action.
// Warning: Signals ARE repainting.

// Style tags: Trend Following, Trend Analysis
// Asset class: Equities, Futures, ETFs, Currencies and Commodities
// Dataset: FX Minutes/Hours++/Days

//-------------------- Inputs

ptype      = input('Close','Price Type', options=['Open','High','Low','Close','HL2','OC2','OHL3','HLC3','OHLC4'])
reso       = input('',     'Resolution', input.resolution)
lookback   = input(3,      'Lookback Window Size |2..n| (2)',       minval=2)
nlbk       = input(2,      'Normalization Lookback |2..240| (120)', minval=2,      maxval=240)
lrate      = input(0.0009, 'Learning Rate |0.0001..0.01|',          minval=0.0001, maxval=0.01, step=0.0001)
iterations = input(1000,   'Training Iterations |50..20000|',       minval=50)
ftype      = input('None', 'Filter Signals by',                     options=['Volatility','Volume','Both','None'])
curves     = input(false,  'Show Loss & Prediction Curves?')
easteregg  = input(true,   'Optional Calculation?')
useprice   = input(true,   'Use Price Data for Signal Generation?')
holding_p  = input(5,      'Holding Period |1..n|',                 minval=1)

//-------------------- System Variables

var BUY = 1, var SELL = -1, var HOLD = 0
var signal     = HOLD
var hp_counter = 0

//-------------------- Custom Functions

cAqua(g) =>  g>9?#0080FFff:g>8?#0080FFe5:g>7?#0080FFcc:g>6?#0080FFb2:g>5?#0080FF99
           : g>4?#0080FF7f:g>3?#0080FF66:g>2?#0080FF4c:g>1?#0080FF33:#00C0FF19
cPink(g) =>  g>9?#FF0080ff:g>8?#FF0080e5:g>7?#FF0080cc:g>6?#FF0080b2:g>5?#FF008099
           : g>4?#FF00807f:g>3?#FF008066:g>2?#FF00804c:g>1?#FF008033:#FF008019

volumeBreak(thres) =>
    rsivol   = rsi(volume, 14)
    osc      = hma(rsivol, 10)
    osc > thres                   

volatilityBreak(volmin, volmax) => atr(volmin) > atr(volmax)

dot(v, w, p) => sum(v * w, p)  // dot product

sigmoid(z) => 1.0 / (1.0 + exp(-z))

logistic_regression(X, Y, p, lr, iterations) =>
    w = 0.0, loss = 0.0
    for i=1 to iterations
        hypothesis = sigmoid(dot(X, 0.0, p))  //-- prediction
        loss := -1.0 / p * (dot(dot(Y, log(hypothesis) + (1.0 - Y), p), log(1.0 - hypothesis), p))
        gradient = 1.0 / p * (dot(X, hypothesis - Y, p))
        w := w - lr * gradient               //-- update weights
  
    [loss, sigmoid(dot(X, w, p))]            //-- current loss & prediction

minimax(ds, p, min, max) =>  // normalize to price
    hi = highest(ds, p), lo = lowest(ds, p)
    (max - min) * (ds - lo)/(hi - lo) + min

//-------------------- Logic

ds       =  ptype=='Open'  ? open
          : ptype=='High'  ? high
          : ptype=='Low'   ? low
          : ptype=='Close' ? close
          : ptype=='HL2'   ? (high+low)/2
          : ptype=='OC2'   ? (open+close)/2
          : ptype=='OHL3'  ? (open+high+low)/3
          : ptype=='HLC3'  ? (high+low+close)/3
          :                  (open+high+low+close)/4
        
base_ds  = security('', reso, ds[barstate.ishistory ? 0 : 1])
synth_ds = log(abs(pow(base_ds, 2) - 1) + .5)  //-- generate a synthetic dataset

base  = easteregg ? time    : base_ds          //-- standard and optional calculation
synth = easteregg ? base_ds : synth_ds       

[loss, prediction] = logistic_regression(base, synth, lookback, lrate, iterations)
scaled_loss        = minimax(loss,       nlbk, lowest(base_ds, nlbk), highest(base_ds, nlbk))
scaled_prediction  = minimax(prediction, nlbk, lowest(base_ds, nlbk), highest(base_ds, nlbk))

filter =   ftype=='Volatility' ? volatilityBreak(1, 10)
         : ftype=='Volume'     ? volumeBreak(49)
         : ftype=='Both'       ? volatilityBreak(1, 10) and volumeBreak(49)
         :                       true

signal :=  useprice ?
           base_ds < scaled_loss and filter ? SELL : base_ds > scaled_loss and filter ? BUY : nz(signal[1])
         : crossunder(scaled_loss, scaled_prediction) and filter ? SELL : crossover(scaled_loss, scaled_prediction) and filter ? BUY : nz(signal[1])

changed = change(signal)
  
hp_counter := changed ? 0 : hp_counter + 1

startLongTrade  = changed and signal==BUY 
startShortTrade = changed and signal==SELL 
endLongTrade    = (signal==BUY  and hp_counter==holding_p and not changed) or (changed and signal==SELL)
endShortTrade   = (signal==SELL and hp_counter==holding_p and not changed) or (changed and signal==BUY)

//-------------------- Rendering

plot(curves ? scaled_loss : na,       '', color.blue, 3)
plot(curves ? scaled_prediction : na, '', color.lime, 3)

plotshape(startLongTrade  ? low  : na, 'Buy',  shape.labelup,   location.belowbar, cAqua(10), size=size.small)
plotshape(startShortTrade ? high : na, 'Sell', shape.labeldown, location.abovebar, cPink(10), size=size.small)
plot(endLongTrade         ? high : na, 'StopBuy',  cAqua(6), 2, plot.style_cross)
plot(endShortTrade        ? low  : na, 'StopSell', cPink(6), 2, plot.style_cross)

//-------------------- Alerting

alertcondition(startLongTrade,  'Buy',  'Go long!')
alertcondition(startShortTrade, 'Sell', 'Go short!')
alertcondition(startLongTrade or startShortTrade, 'Alert', 'Deal Time!') //-- general alert

//-------------------- Backtesting (TODO)

lot_size  = input(0.01, 'Lot Size', options=[0.01,0.1,0.2,0.3,0.5,1,2,3,5,10,20,30,50,100,1000])

ohl3 = (open+high+low)/3

var float start_long_trade  = 0.
var float long_trades       = 0.
var float start_short_trade = 0.
var float short_trades      = 0.
var int   wins              = 0
var int   trade_count       = 0

if startLongTrade
    start_long_trade := ohl3
if endLongTrade
    trade_count  := 1
    ldiff = (ohl3 - start_long_trade)
    wins         := ldiff > 0 ? 1 : 0
    long_trades  := ldiff * lot_size 
if startShortTrade
    start_short_trade := ohl3
if endShortTrade
    trade_count  := 1
    sdiff = (start_short_trade - ohl3)
    wins         := sdiff > 0 ? 1 : 0
    short_trades := sdiff * lot_size
  
cumreturn   = cum(long_trades) + cum(short_trades)  //-- cumulative return
totaltrades = cum(trade_count)
totalwins   = cum(wins)
totallosses = totaltrades - totalwins == 0 ? 1 : totaltrades - totalwins

//-------------------- Information

show_info = input(true, 'Show Info?')

var label lbl = na

tbase = (time - time[1]) / 1000
tcurr = (timenow - time_close[1]) / 1000

info =  'CR='          + tostring(cumreturn,             '#.#')
      + '\nTrades: '   + tostring(totaltrades,           '#')
      + '\nWin/Loss: ' + tostring(totalwins/totallosses, '#.##')
      + '\nWinrate: '  + tostring(totalwins/totaltrades, '#.#%')
      + '\nBar Time: ' + tostring(tcurr / tbase,         '#.#%')

if show_info and barstate.islast
    lbl := label.new(bar_index, close, info, xloc.bar_index, yloc.price,
                     color.new(color.blue, 100), label.style_label_left, color.black, size.small, text.align_left)
    label.delete(lbl[1])

and this is what chatgpt gave me (which just errors out).

Code:
# Machine Learning: Logistic Regression (v.3)
# ThinkScript version by ChatGPT

declare lower;

# Multi-timeframe Strategy based on Logistic Regression algorithm



# Inputs

input ptype = close;
input reso = AggregationPeriod.DAY;
input int lookback = 3;
input int nlbk = 2;
input float lrate = 0.0009;
input int iterations = 1000;
input string ftype = "None";
input bool curves = no;
input bool easteregg = yes;
input bool useprice = yes;
input int holding_p = 5;

# System Variables

def BUY = 1;
def SELL = -1;
def HOLD = 0;
def signal = HOLD;
def hp_counter = 0;

# Custom Functions

def cAqua(g) =>
    g > 9 ? color.cyan :
    g > 8 ? color.cyan[75] :
    g > 7 ? color.cyan[60] :
    g > 6 ? color.cyan[45] :
    g > 5 ? color.cyan[30] :
    g > 4 ? color.cyan[15] :
    g > 3 ? color.cyan[5] :
    g > 2 ? color.cyan[10] :
    g > 1 ? color.cyan[20] :
    color.cyan[90];

def cPink(g) =>
    g > 9 ? color.magenta :
    g > 8 ? color.magenta[75] :
    g > 7 ? color.magenta[60] :
    g > 6 ? color.magenta[45] :
    g > 5 ? color.magenta[30] :
    g > 4 ? color.magenta[15] :
    g > 3 ? color.magenta[5] :
    g > 2 ? color.magenta[10] :
    g > 1 ? color.magenta[20] :
    color.magenta[90];

def volumeBreak(thres) =>
    def rsivol = reference RSI(14, volume);
    def osc = reference HullMovingAverage(rsivol, 10);
    osc > thres;

def volatilityBreak(volmin, volmax) =>
    AverageTrueRange(volmin) > AverageTrueRange(volmax);

def dot(v, w, p) =>
    TotalSum(v * w, p);

def sigmoid(z) =>
    1.0 / (1.0 + Exp(-z));

def logistic_regression(X, Y, p, lr, iterations) {
    def w = 0.0;
    def loss = 0.0;
    for (int i = 1; i <= iterations; i++) {
        def hypothesis = sigmoid(dot(X, 0.0, p));  // prediction
        loss = -1.0 / p * (dot(dot(Y, Log(hypothesis) + (1.0 - Y), p), Log(1.0 - hypothesis), p));
        def gradient = 1.0 / p * (dot(X, hypothesis - Y, p));
        w = w - lr * gradient;  // update weights
    }
    return [loss, sigmoid(dot(X, w, p))];  // current loss & prediction
}

def minimax(ds, p, min, max) => {
    def hi = Highest(ds, p);
    def lo = Lowest(ds, p);
    return (max - min) * (ds - lo) / (hi - lo) + min;
}

# Logic

def ds;
switch (ptype) {
    case "Open":
        ds = open;
    case "High":
        ds = high;
    case "Low":
        ds = low;
    case "Close":
        ds = close;
    case "HL2":
        ds = (high + low) / 2;
    case "OC2":
        ds = (open + close) / 2;
    case "OHL3":
        ds = (open + high + low) / 3;
    case "HLC3":
        ds = (high + low + close) / 3;
    default:
        ds = (open + high + low + close) / 4;
}

def base_ds = reference ds[1];
def synth_ds = Log(Abs(Pow(base_ds, 2) - 1) + 0.5);

def base = easteregg ? GetTime() : base_ds;
def synth = easteregg ? base_ds : synth_ds;

def result = logistic_regression(base, synth, lookback, lrate, iterations);
def loss = result[0];
def prediction = result[1];
def scaled_loss = minimax(loss, nlbk, Lowest(base_ds, nlbk), Highest(base_ds, nlbk));
def scaled_prediction = minimax(prediction, nlbk, Lowest(base_ds, nlbk), Highest(base_ds, nlbk));

def filter;
switch (ftype) {
    case "Volatility":
        filter = volatilityBreak(1, 10);
    case "Volume":
        filter = volumeBreak(49);
    case "Both":
        filter = volatilityBreak(1, 10) and volumeBreak(49);
    default:
        filter = yes;
}

signal[1] = signal;
signal = useprice ?
    if base_ds < scaled_loss and filter then SELL
    else if base_ds > scaled_loss and filter then BUY
    else signal[1]
:
    if IsNaN(scaled_loss) then signal[1]
    else if Inverse(scaled_loss < scaled_prediction and filter) then SELL
    else if Inverse(scaled_loss > scaled_prediction and filter) then BUY
    else signal[1];

def changed = signal != signal[1];
hp_counter = if changed then 0 else hp_counter + 1;

def startLongTrade = changed and signal == BUY;
def startShortTrade = changed and signal == SELL;
def endLongTrade = (signal == BUY and hp_counter == holding_p and not changed) or (changed and signal == SELL);
def endShortTrade = (signal == SELL and hp_counter == holding_p and not changed) or (changed and signal == BUY);

# Rendering

plot if curves then scaled_loss else Double.NaN;
plot if curves then scaled_prediction else Double.NaN;

plotshape(if startLongTrade then low else Double.NaN, "Buy", shape.triangleup, Color.CYAN, size = size.small);
plotshape(if startShortTrade then high else Double.NaN, "Sell", shape.triangledown, Color.MAGENTA, size = size.small);
plot(if endLongTrade then high else Double.NaN, "StopBuy", Color.CYAN, size = size.small);
plot(if endShortTrade then low else Double.NaN, "StopSell", Color.MAGENTA, size = size.small);

# Alerting

alert(if startLongTrade then 1 else 0, "Buy", "Go long!");
alert(if startShortTrade then 1 else 0, "Sell", "Go short!");
alert(if startLongTrade or startShortTrade then 1 else 0, "Alert", "Deal Time!");  # general alert

# Backtesting (TODO)

input lot_size = 0.01;

def ohl3 = (open + high + low) / 3;
def start_long_trade = 0.0;
def long_trades = 0.0;
def start_short_trade = 0.0;
def short_trades = 0.0;
def wins = 0;
def trade_count = 0;

if startLongTrade {
    start_long_trade = ohl3;
}
if endLongTrade {
    trade_count = 1;
    def ldiff = (ohl3 - start_long_trade);
    wins = ldiff > 0 ? 1 : 0;
    long_trades = ldiff * lot_size;
}
if startShortTrade {
    start_short_trade = ohl3;
}
if endShortTrade {
    trade_count = 1;
    def sdiff = (start_short_trade - ohl3);
    wins = sdiff > 0 ? 1 : 0;
    short_trades = sdiff * lot_size;
}

def cumreturn = long_trades + short_trades;  # cumulative return
def totaltrades = trade_count;
def totalwins = wins;
def totallosses = totaltrades - totalwins == 0 ? 1 : totaltrades - totalwins;

# Information

def show_info = yes;
def info =
    "CR=" + AsString(cumreturn, NumberFormat.TWO_DECIMAL_PLACES)
    + "\nTrades: " + AsString(totaltrades)
    + "\nWin/Loss: " + AsString(totalwins / totallosses, NumberFormat.TWO_DECIMAL_PLACES)
    + "\nWinrate: " + AsString(totalwins / totaltrades, NumberFormat.TWO_DECIMAL_PLACES) + "%"
    + "\nBar Time: " + AsString(tcurr / tbase, NumberFormat.TWO_DECIMAL_PLACES);

AddLabel(show_info and IsNaN(close[1]), info, Color.BLUE);
;

Anyone know if this is possible with thinkscript or can it not do some of these pinescript functions?
check the below/

CSS:
#// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
#// Multi-timeframe Strategy based on Logistic Regression algorithm
#// https://www.tradingview.com/v/49YIV1jW/
#// © capissimo
#// For more information on KernelFunctions refer to to the original open source indicator by @jdehorty located here:
#// https://www.tradingview.com/script/...son-Rational-Quadratic-Kernel-Non-Repainting/
#// Nadaraya-Watson Kernel Regression Settings
#study('Machine Learning: Logistic Regression (v.3)
# Converted by Sam4Cok@Samer800    - 02/2024
#//-------------------- Inputs
input show_label = yes;            # 'Show Info?'
input signalStyle = {Default "Arrows", "Bubbles"};
input priceType  = {"Open", "High", "Low", default "Close", "HL2", "OC2", "OHL3", "HLC3", "OHLC4", "HLCC4"};
input timeframe = {Default "Chart Timeframe", "Custom Timeframe"};
input customTimeframe = AggregationPeriod.FIFTEEN_MIN;    # 'Resolution'
input LookbackWindowSize   = 3;                                # 'Lookback Window Size |2..n| (2)'
input NormalizationLookback = 2;                     # 'Normalization Lookback |2..240| (120)'
input LearningRate      = 0.0009;                    # 'Learning Rate |0.0001..0.01|'
input TrainingIterations = 1000;                     # 'Training Iterations |50..20000|'
input FilterSignalsBy  = {default Volatility, Volume, Both , None};    # 'Filter Signals by'
input ShowLossAndPredictionCurves     = no;          # 'Show Loss & Prediction Curves?'
input useOptionalCalculation  = yes;                    # 'Optional Calculation?'
input UsePriceDataForSignalGeneration   = yes;       # 'Use Price Data for Signal Generation?'
input HoldingPeriod  = 5;                            # 'Holding Period |1..n|'
input lot_size  = 1.0;

#//-------------------- System Variables
def na = Double.NaN;
def arrow = signalStyle==signalStyle."Arrows";
def lookback = LookbackWindowSize;
def nlbk = NormalizationLookback;
def lrate = LearningRate;
def iterations = TrainingIterations;
def curves = ShowLossAndPredictionCurves;
def easteregg = useOptionalCalculation;
def useprice = UsePriceDataForSignalGeneration;
def time = GetTime()/1000;#BarNumber();
def ishistory = !IsNaN(close[-1]);

def volume_ = volume;
#-- Color
DefineGlobalColor("Lup", CreateColor(33,150,243));
DefineGlobalColor("Ldn", CreateColor(0,230,118));
DefineGlobalColor("up", CreateColor(0,128,255));
DefineGlobalColor("dn", CreateColor(255,0,128));
DefineGlobalColor("dup", CreateColor(0,69,137));
DefineGlobalColor("ddn", CreateColor(137,0,69));

def open_;
def high_;
def low_;
def close_;
switch (timeframe) {
case "Custom Timeframe" :
    open_   = open(Period = customTimeframe);
    high_   = high(Period = customTimeframe);
    low_    = low(Period = customTimeframe);
    close_  = close(Period = customTimeframe);
Default :
    open_   = open;
    high_   = high;
    low_    = low;
    close_  = close;
}
#//-------------------- Custom Functions
#volumeBreak(thres) => 
    def rsivol   = RSI(Price = volume_, Length = 14);
    def osc      = HullMovingAvg(rsivol, 10);
    def volumeBreak = osc > 49;
#volatilityBreak(volmin, volmax)
    def volatilityBreak = ATR(LENGTH=1) > ATR(LENGTH=10);
#dot(v, w, p)
script dot {
    input v = 1;
    input w = 1;
    input p = 10;
    def dot = Sum(v * w, p);#  // dot product
    plot out = dot;
}
#sigmoid(z) =>
script sigmoid {
    input z = 1;
    def sigmoid = 1.0 / (1.0 + Exp(-z));
    plot out = sigmoid;
}
#logistic_regression(X, Y, p, lr, iterations) =>
script logistic_regression {
    input X = close;
    input Y = close;
    input p = 10;
    input lr = 0.0009;
    input iterations = 1000;
    def ishistory = IsNaN(close);
    def hypothesis = sigmoid(dot(X, 0.0, p));#  //-- prediction
    def loss = -1.0 / p * (dot(dot(Y, Log(hypothesis) + (1.0 - Y), p), Log(1.0 - hypothesis), p));
    def gradient = 1.0 / p * (dot(X, hypothesis - Y, p));
    def w = fold i = 1 to iterations with q do
            q - lr * gradient;
    def predict = sigmoid(dot(X, w, p));
    plot los  = if ishistory then Double.NaN else loss;
    plot pred = if ishistory then Double.NaN else predict;
}
#minimax(ds, p, min, max) =>
script minimax {
    input ds = close;
    input p  = 10;
    input min = 0;
    input max = 100;
    def hi = Highest(ds, p);
    def lo = Lowest(ds, p);
    def minimax = (max - min) * (ds - lo) / (hi - lo) + min;
    plot out = if isNaN(minimax) then Double.NaN else minimax;
}
#//-------------------- Logic
def ds;
switch (priceType) {
case "Open" : ds = open_;
case "High" : ds = high_;
case "Low"  : ds = low_;
case "HL2"  : ds = (high_ + low_) / 2;
case "OC2"  : ds = (open_ + close_) / 2;
case "OHL3" : ds = (open_ + high_ + low_) / 3;
case "HLC3" : ds = (high_ + low_ + close_) / 3;
case "OHLC4" : ds = (open_ + high_ + low_ + close_) / 4;
case "HLCC4" : ds = (high_ + low_ + close_ + close_) / 4;
Default      : ds = close_;
}

def base_ds  = if ishistory then ds else ds[1];
def synth_ds = Log(AbsValue(Power(base_ds, 2) - 1) + 0.5);# //-- generate a synthetic dataset

def base  = if easteregg then time else base_ds;         # //-- standard and optional calculation
def synth = if easteregg then base_ds else synth_ds;
def lowstBase   = Lowest(base_ds, nlbk);
def highestBase = Highest(base_ds, nlbk);

def loss       = logistic_regression(base, synth, lookback, lrate, iterations).los;
def prediction = logistic_regression(base, synth, lookback, lrate, iterations).pred;
def scaled_loss        = minimax(loss,       nlbk, lowstBase, highestBase);
def scaled_prediction  = minimax(prediction, nlbk, lowstBase, highestBase);

#--- Filter
def volt = volatilityBreak;
def vol  = volumeBreak;
def all = volt and vol;
def filter = if FilterSignalsby == FilterSignalsby.Volatility then volt else
             if FilterSignalsby == FilterSignalsby.Volume     then vol else
             if FilterSignalsby == FilterSignalsby.Both       then all else yes;
def signal = if useprice then
             if base_ds < scaled_loss and filter then -1 else
             if base_ds > scaled_loss and filter then  1 else signal[1] else
             if scaled_loss < scaled_prediction and filter then -1 else
             if scaled_loss > scaled_prediction and filter then  1 else signal[1];

def changed = signal - signal[1];
def hp_counter = if changed then 0 else hp_counter[1] + 1;

def startLongTrade  = changed and signal == 1;
def startShortTrade = changed and signal ==-1;
def endLongTrade    = (signal == 1 and hp_counter == HoldingPeriod and !changed) or (changed and signal ==-1);
def endShortTrade   = (signal ==-1 and hp_counter == HoldingPeriod and !changed) or (changed and signal == 1);

#//-------------------- Rendering
def lowFrac = low * 0.03 / 100;
def highFrac = high * 0.03 / 100;

plot CurveLoss = if curves and scaled_loss then scaled_loss else na;
plot CurvePred = if curves and scaled_prediction then scaled_prediction else na;
CurveLoss.SetLineWeight(2);
CurvePred.SetLineWeight(2);
CurveLoss.SetDefaultColor(GlobalColor("Lup"));
CurvePred.SetDefaultColor(GlobalColor("Ldn"));

#-- Signals
AddChartBubble(!arrow and startLongTrade, low, "B", GlobalColor("up"), no);
AddChartBubble(!arrow and startShortTrade, high, "S", GlobalColor("dn"));

plot BuySig = if arrow and startLongTrade  then low  - lowFrac else na;     # "Buy"
plot SelSig = if arrow and startShortTrade then high + highFrac else na;    # "Sell"
plot endLong  = if endLongTrade then high else na;    # 'StopBuy'
plot endShort = if endShortTrade then low else na;    # 'StopSell'

BuySig.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
SelSig.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);
BuySig.SetLineWeight(2);
SelSig.SetLineWeight(2);
BuySig.SetDefaultColor(GlobalColor("up"));
SelSig.SetDefaultColor(GlobalColor("dn"));
endLong.SetPaintingStrategy(PaintingStrategy.BOOLEAN_WEDGE_UP);
endShort.SetPaintingStrategy(PaintingStrategy.BOOLEAN_WEDGE_DOWN);
endLong.SetDefaultColor(GlobalColor("dup"));
endShort.SetDefaultColor(GlobalColor("ddn"));

#//-------------------- Backtesting (TODO)
def ohl3 = (open + high + low) / 3;

def long_trades;
def short_trades;
def wins;
def trade_count;
def start_long_trade  = if startLongTrade then ohl3 else (if isNaN(start_long_trade[1]) then 0 else start_long_trade[1]);
def start_short_trade = if startShortTrade then ohl3 else (if isNaN(start_short_trade[1]) then 0 else start_short_trade[1]);
if endLongTrade {
    trade_count  = if isNaN(trade_count[1]) then 0 else trade_count[1] + 1;
    wins         = if isNaN(wins[1]) then 0 else if (ohl3 - start_long_trade) > 0 then wins[1] + 1 else wins[1];
    long_trades  = (if isNaN(long_trades[1]) then 0 else long_trades[1]) + (ohl3 - start_long_trade) * lot_size;
    short_trades = short_trades[1];
} else
if endShortTrade {
    trade_count  = if isNaN(trade_count[1]) then 0 else trade_count[1] + 1;
    wins         = if isNaN(wins[1]) then 0 else if (start_short_trade - ohl3) > 0 then wins[1] + 1 else wins[1];
    short_trades = (if isNaN(short_trades[1]) then 0 else short_trades[1]) + (start_short_trade - ohl3) * lot_size;
    long_trades  = long_trades[1];
} else {
    trade_count  = trade_count[1];
    wins         = wins[1];
    long_trades  = long_trades[1];
    short_trades = short_trades[1];
}
def cumreturn   = long_trades + short_trades;
def totaltrades = trade_count;
def totalwins   = wins;
def totallosses = if totaltrades - totalwins == 0 then 1 else totaltrades - totalwins;
def cr = Round(cumreturn, 2);
def winLoss = Round(totalwins / totallosses, 2);
def winRate = Round(totalwins / totaltrades * 100, 1);
#/-------------------- Information

AddLabel(show_label, "CR= $" + cr, if cr>0 then Color.LIGHT_GREEN else Color.PINK);
AddLabel(show_label, "Trades: " + totaltrades, Color.WHITE);
AddLabel(show_label, "Win/Loss: " + winLoss, if winLoss>1 then Color.LIGHT_GREEN else Color.PINK);
AddLabel(show_label, "Winrate: " + winRate + "%", if winRate>50 then Color.LIGHT_GREEN else Color.PINK);

#---- END of CODE
 

Join useThinkScript to post your question to a community of 21,000+ developers and traders.

Thread starter Similar threads Forum Replies Date
J Machine Learning kNN-based Indicator For ThinkOrSwim Custom 8
samer800 ML: Multiple Logistic Regression for ThinkOrSwim Custom 0

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
375 Online
Create Post

Similar threads

Similar threads

The Market Trading Game Changer

Join 2,500+ subscribers inside the useThinkScript VIP Membership Club
  • Exclusive indicators
  • Proven strategies & setups
  • Private Discord community
  • ‘Buy The Dip’ signal alerts
  • Exclusive members-only content
  • Add-ons and resources
  • 1 full year of unlimited support

Frequently Asked Questions

What is useThinkScript?

useThinkScript is the #1 community of stock market investors using indicators and other tools to power their trading strategies. Traders of all skill levels use our forums to learn about scripting and indicators, help each other, and discover new ways to gain an edge in the markets.

How do I get started?

We get it. Our forum can be intimidating, if not overwhelming. With thousands of topics, tens of thousands of posts, our community has created an incredibly deep knowledge base for stock traders. No one can ever exhaust every resource provided on our site.

If you are new, or just looking for guidance, here are some helpful links to get you started.

What are the benefits of VIP Membership?
VIP members get exclusive access to these proven and tested premium indicators: Buy the Dip, Advanced Market Moves 2.0, Take Profit, and Volatility Trading Range. In addition, VIP members get access to over 50 VIP-only custom indicators, add-ons, and strategies, private VIP-only forums, private Discord channel to discuss trades and strategies in real-time, customer support, trade alerts, and much more. Learn all about VIP membership here.
How can I access the premium indicators?
To access the premium indicators, which are plug and play ready, sign up for VIP membership here.
Back
Top