Curso Gratuito - Trading IA
Indicador de regresión lineal en tradestation

Hola, estoy intentando hacer el indicador del canal de regresión para Scanner1 a partir del indicador de regresión lineal de TradesTation, pero no consigo ver cómo le pongo la desviación para que se forme el canal con las dos líneas nuevas que he añadido. Me podéis echar una mano?
{ Search Tag: WA-Linear Reg Line } {
If the 'EndDate_YYMMDD' input is set to 0, the indicator draws a linear regression
line ending at the last bar on the chart at the time the indicator is applied to
the chart. At the close of each bar, the line is recalculated and updated on the
chart. If the 'EndDate_YYMMDD' input is NOT set to 0, the indicator draws a linear
regression line ending at the bar with the specified date ('EndDate_YYMMDD' input
value) and time ('EndTime_HHMMSS' input value). This line drawn once as a
historical line and is NOT udpated at the close of each bar.
} using elsystem;
using elsystem.drawing;
using elsystem.drawingobjects; inputs:
double Price( Close ) [DisplayName = "Price", ToolTip =
"Enter an EasyLanguage expression to specify the data series to be used in the linear regression calculation."],
int Length1( 70 ) [DisplayName = "LengthCorto", ToolTip =
"Enter the number of bars over which to calculate the linear regression."],
int Length2( 140) [DisplayName = "LengthLargo", ToolTip =
"Enter the number of bars over which to calculate the linear regression."],
double EndDate_YYMMDD( 0 ) [DisplayName = "EndDate_YYMMDD", ToolTip =
"Enter the end date for the linear regression line; either 0 or YYMMDD. If EndDate_YYMMDD = 0, EndTime_HHMMSS ignored and last bar on chart is used."],
string EndTime_HHMMSS( "16:00:00" ) [DisplayName = "EndTime_HHMMSS", ToolTip =
"Enter ending 24-hr time as a string of HH:MM:SS"],
int TrendlineColor( Yellow ) [DisplayName = "TrendlineColor", ToolTip =
"Enter the color to be used for the linear regression trendline."],
int ExtRight( 0 ) [DisplayName = "ExtRight", ToolTip =
"Extend Right. Enter 1 if the trendline should be extended to the right; enter 0 if it should not be extended."],
int Deviations (2.0) [DisplayName = "Desviación", ToolTip = ""]; variables:
intrabarpersist bool UseBNPoint( false ),
intrabarpersist bool InAChart( false ),
int DrawingObjectBarNumber( 0 ),
TrendLine LinearRegTL( NULL ),
TrendLine UpperChannel( NULL ),
Trendline LowerChannel( NULL ),
DateTime EndDateTime( NULL ),
TimeSpan EndTimeTS( NULL ),
intrabarpersist EndDate( 0 ),
double LRV( 0 ),
double LRVAgo( 0 ),
intrabarpersist bool UpdateTrendlineInRealTime( false ),
upperlinecolor(yellow),
lowerlinecolor(yellow); method void ErrorCheckInputs()
variables: string ErrorString;
begin
{ if EndDate_YYMMDD = 0, we do not use the time, so we will only try to
parse the time input if EndDate_YYMMDD <> 0 }
if EndDate_YYMMDD <> 0 then
begin
ErrorString = CreateEndTimeDateTime(); { if an error string is returned when we try to parse the time, we will
raise a runtime error and display the error string }
if ErrorString.Length <> 0 then
throw Exception.Create( ErrorString );
end; end; { create TimeSpan objects for end time }
method string CreateEndTimeDateTime()
variables: datetime tempDateTime, string ErrorString;
begin
ErrorString = ""; if DateTime.TryParse( EndTime_HHMMSS, tempDateTime ) then
begin
EndTimeTS = tempDateTime.TimeOfDay;
end
else
begin
{ the end time could not be parsed; set error message }
ErrorString = !( "EndTime_HHMMSS invalid value or format. Enter ending 24-hr time as a string of HH:MM:SS." );
end;
return ErrorString; end; method TrendLine CreateLinRegTrendline()
variables: TrendLine tempTL, TrendLine upperTL, Trendline lowerTL;
begin
{ these trendlines are horizontal in nature so the TLPrice is used for
both the start price and end price for the trendline }
if UseBNPoint then
begin
tempTL = TrendLine.Create(
BNPoint.Create( DrawingObjectBarNumber[Length1 - 1], LRVAgo ),
BNPoint.Create( DrawingObjectBarNumber, LRV ) );
upperTL = TrendLine.Create(
BNPoint.Create( DrawingObjectBarNumber[Length1 - 1], LRVAgo ),
BNPoint.Create( DrawingObjectBarNumber, LRV ) );
lowerTL = TrendLine.Create(
BNPoint.Create( DrawingObjectBarNumber[Length1 - 1], LRVAgo ),
BNPoint.Create( DrawingObjectBarNumber, LRV ) );
end
else { use DTPoint }
begin
tempTL = TrendLine.Create(
DTPoint.Create( BarDateTime[Length1 - 1], LRVAgo ),
DTPoint.Create( BarDateTime, LRV ) );
upperTL = TrendLine.Create(
DTPoint.Create( BarDateTime[Length1 - 1], LRVAgo ),
DTPoint.Create( BarDateTime, LRV ) );
lowerTL = TrendLine.Create(
DTPoint.Create( BarDateTime[Length1 - 1], LRVAgo ),
DTPoint.Create( BarDateTime, LRV ) ); end;
{
Setting 'Persist' to false causes the trendline to be deleted on an
intrabar tick. When set to false, a trendline that is created on the
closing tick of the bar is saved/retained.
}
tempTL.Persist = false;
tempTL.Lock = true; { prevent inadvertant moving of the trendline }
tempTL.Color = GetColorFromInteger( 255, TrendlineColor );
tempTL.ExtLeft = false;
tempTL.ExtRight = ExtRight = 1;
upperTL.Persist = false;
upperTL.Lock = true; { prevent inadvertant moving of the trendline }
upperTL.Color = GetColorFromInteger( 255, upperlinecolor );
upperTL.ExtLeft = false;
upperTL.ExtRight = ExtRight = 1;
lowerTL.Persist = false;
lowerTL.Lock = true; { prevent inadvertant moving of the trendline }
lowerTL.Color = GetColorFromInteger( 255, lowerlinecolor );
lowerTL.ExtLeft = false;
lowerTL.ExtRight = ExtRight = 1;
{
this is how the trendline is "shown"; the trendline is added to the
DrawingObjects collection; if you want to remove the trendline, you can
use the Delete method of the DrawingObjects class; DrawingObjects collection
is not available in RadarScreen (it is NULL), so we check to ensure the
DrawingObjects are not NULL
}
if DrawingObjects <> NULL then
begin
DrawingObjects.Add( tempTL );
DrawingObjects.Add( upperTL );
DrawingObjects.Add( lowerTL );
end;
return tempTL;
return upperTL;
return lowerTL; end; { convert integer color to a color object and return the color object }
method Color GetColorFromInteger( int Alpha, int ColorInteger )
begin
return Color.FromARGB( Alpha, GetRValue( ColorInteger ),
GetGValue( ColorInteger ), GetBValue( ColorInteger ) );
end; once
begin
ErrorCheckInputs(); if EndDate_YYMMDD < 500000 then
EndDate = EndDate_YYMMDD + 1000000
else
EndDate = EndDate_YYMMDD;
{
When this study is applied to tick bars or advanced bars, we use BNPoint
positioning of text labels. This ensures that the text labels are positioned
on the correct bar even when multiple bars occur in the same second (as can
occur with very short-term tick bars). When positioning time-based bars, on
the other hand, we’ll use DTPoint positioning. This type of positioning can
account for missing bars in the data stream (periods of no trading activity,
as can occur with ‘thin’ issues). Missing bars, of course, cannot occur when
using tick-based charts or advanced bars, since these bar-building mechanisms
do not move along the x-axis until enough trades have occurred to complete a
bar. Thus, the approach illustrated here gives us the best of both worlds
– sub-second positioning and automatic accounting for missing bars.
}
UseBNPoint = BarType = 0 or ( BarType > 4 and BarType <> 14 );
InAChart = GetAppInfo( aiApplicationType ) = cChart; end; { set the bar number for the drawing object }
if UseBNPoint then
DrawingObjectBarNumber = CurrentBar + MaxBarsBack - 1; { if the trendline is NULL, we will check to see if one needs to be created
based on the input values }
if LinearRegTL = NULL then
begin
{
if the EndDate_YYMMDD = 0, EndDate calculuates to 1000000; the time
specified in the 'EndTime_HHMMSS' input is not used; we will draw a
linear regression line once we get to the last bar on the chart and will
update it at the close of each bar in real time
}
if EndDate = 1000000 and LastBarOnChartEx then
begin
LRV = LinearRegValue( Price, Length1, 0 );
LRVAgo = LinearRegValue( Price, Length1, Length1 - 1 );
LinearRegTL = CreateLinRegTrendline();
//upperchannel = CreateLinRegTrendline();
//lowerchannel = CreateLinRegTrendline();
{
now that the trendline has been created and EndDate_YYMMDD = 0, we will
update the trendline in real time; the 'UpdateTrendlineInRealTime'
variable will be used to update the trendline in real time, so we will
set it to true
}
UpdateTrendlineInRealTime = true;
end
else if Date = EndDate and BarDateTime.TimeOfDay = EndTimeTS then
begin
LRV = LinearRegValue( Price, Length1, 0 );
LRVAgo = LinearRegValue( Price, Length1, Length1 - 1 );
LinearRegTL = CreateLinRegTrendline();
end;
end; if UpdateTrendlineInRealTime then
begin
{
reset the end-points of the linear regression line at each new bar (study is
set to run the code at bar closing) after it has been drawn; this effectively
results in a new LRLine each time the code runs (at the close of the bar)
}
LRV = LinearRegValue( Price, Length1, 0 );
LRVAgo = LinearRegValue( Price, Length1, Length1 - 1 ); if UseBNPoint then
begin
LinearRegTL.SetStartPoint( BNPoint.Create(
DrawingObjectBarNumber[Length1 - 1], LRVAgo ) );
LinearRegTL.SetEndPoint( BNPoint.Create(
DrawingObjectBarNumber, LRV ) );
end
else
begin
LinearRegTL.SetStartPoint(
DTPoint.Create( BarDateTime[Length1 - 1], LRVAgo ) );
LinearRegTL.SetEndPoint( DTPoint.Create( BarDateTime, LRV ) );
end; end;
Comentarios
-
Yo ahi no entiendo la mitad de lo que pone, se me antoja que son muchas lineas
0 -
Bueno, ya por lo menos sé lo que hace el original y después de unas cuantas lineas y pruebas sé cómo hacer las otras lineas del canal, aunque no sé si es la mejor forma o la más eficiente.
Hasta ahora lo he hecho todo en pinescript y es lo primero que hago en tradestation para familiarizarme un poco con el código y las diferencias del lenguaje. Me gustaría implementar el scanner en tradestation y todos los indicadores de scalping poco a poco porque finalmente es la plataforma que seguramente usaré (al menos para scalping)
Poco a poco
0 -
En primer lugar, el indicador es el que viene por defecto en tradestation, verdad? Este solo dibuja una línea y quieres dibujar dos paralelas para marcar límites superior e inferior del canal.
En la teoría tienes ejemplos sencillos del cálculo manual de esto que quieres hacer en pinescript.
Quizás sea buena idea estudiar este ejemplo e intentar traducirlo (o implementar a este lo que comentas de la desviación en base a las fórmulas del otro).
Por aquí lo dejo: link.
//@version=5 indicator('Regresión', overlay=true) // Número de velas anteriores que analizaremos. periodo_r = input(100) // Si la aumentamos, veremos como el canal se hace más ámplio o menos. A más estrecho, más velas saldrán de él. deviations = 2 // Cálculo de la recta de regresión // Esto son matemáticas, no hemos inventado nada nuevo, simplemente implementada la ecuación de esta recta. // No te preocupes si solo ves un lío de números y no los entiendes, con que entiendas qué hacen es suficiente. // Aquí tienes un video explicativo sobre la recta de regresión: https://www.youtube.com/watch?v=z5BLYKGcDjM periodMinusOne = periodo_r-1 Ex = 0.0, Ey = 0.0, Ex2 = 0.0,Ey2 =0.0, Exy = 0.0, for i=0 to periodMinusOne closeI = nz(close[i]), Ex := Ex + i, Ey := Ey + closeI, Ex2 := Ex2 + (i * i),Ey2 := Ey2 + (closeI * closeI), Exy := Exy + (closeI * i) ExT2 = math.pow(Ex,2.0) //Sum of X THEN Squared EyT2 = math.pow(Ey,2.0) //Sym of Y THEN Squared // Cálculo del coeficiente de correlación PearsonsR = (Exy - ((Ex*Ey)/periodo_r))/(math.sqrt(Ex2-(ExT2/periodo_r))*math.sqrt(Ey2-(EyT2/periodo_r))) ExEx = Ex * Ex, slope = Ex2==ExEx ? 0.0 : (periodo_r * Exy - Ex * Ey) / (periodo_r * Ex2 - ExEx) // Parámetros para el dibujo de los canales tendenciales linearRegression = (Ey - slope * Ex) / periodo_r intercept = linearRegression + bar_index * slope deviation = 0.0, for i=0 to periodMinusOne deviation := deviation + math.pow(nz(close[i]) - (intercept - slope * (bar_index[i])), 2.0) deviation := deviations * math.sqrt(deviation / periodMinusOne) startingPointY = linearRegression + slope * periodMinusOne // Visualizar coeficiente R plotchar(PearsonsR, char="", title="R") // LÍNEAS var line upperChannelLine = na , var line medianChannelLine = na , var line lowerChannelLine = na // Retrasar X periodos: de esta forma veremos la regresión hace X periodos var backtest = input(0) // Si hay backtest, parar una vez superado este periodo if last_bar_index - bar_index > backtest // Representar // Primero elimino la representación en la vela anterior line.delete(upperChannelLine[1]), line.delete(medianChannelLine[1]), line.delete(lowerChannelLine[1]) // Dibujo el canal para el periodo actual: linea superior, upperChannelLine := line.new(bar_index - periodo_r + 1, startingPointY + deviation, bar_index, linearRegression + deviation, xloc.bar_index, extend.none, color.new(#00FF00, 0), line.style_solid , 1) medianChannelLine := line.new(bar_index - periodo_r + 1, startingPointY , bar_index, linearRegression , xloc.bar_index, extend.none, color.black, line.style_solid , 1) lowerChannelLine := line.new(bar_index - periodo_r + 1, startingPointY - deviation, bar_index, linearRegression - deviation, xloc.bar_index, extend.none, color.new(#00FF00, 0), line.style_solid , 1)
Hago incapié en este fragmento del código:
deviation = 0.0, for i=0 to periodMinusOne deviation := deviation + math.pow(nz(close[i]) - (intercept - slope * (bar_index[i])), 2.0) deviation := deviations * math.sqrt(deviation / periodMinusOne)
2 -
Creo que acabas antes y aprendes más si traduces directo el de pine script a easy language, yo era lo que hacía (y sigo haciendo ejercicios de estos)
🇪🇦
1 -
También he empezado a hacerlo así y es como voy a hacer los demás indicadores, pero también quería ver esa otra forma para entender la forma de programar.
1 -
También lo estoy haciendo y creo que ya lo tengo traducido "literalmente". El caso es que me dibuja el canal de regresión, pero no donde debería. Estoy dibujando las diferente variables para ver los valores que toman y veo que toman valores diferentes en cada lenguage, por lo tanto algo me falta o en cada lenguaje se hacen los cálculos de otra manera. Te explico un parámetro concreto por ejemplo de mi indicador que es sacado del indicador de regresión que tenemos en el curso.https://docs.google.com/document/d/1ZzECJkPFLrwbyO3raiMlGdZaQaO4t4CPGVNjmqtc_bQ/edit
Si me dibujo en el gráfico el parámetro Ex = Ex+i
- en tradingview me dibuja una línea horizontal en el gráfico y el valor es inmutable a lo largo de todo el histórico para todos los parámetros que contienen la "x".
- en tradestation me dibuja unos puntos a partir de la primera vela del inicio del canal que va creciendo hacia arriba
- para los parámetros que tienen la "y", sí que va tomando valores diferente con el tiempo en tradingview
Este sería un primer fragmento de mi indicador de partida en tradingview para traducirlo:
// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/// © forexchp
//@version=5indicator("Scanner pruebas para traducción", overlay=true)
///////////////////////////////////////////////// SCANNER 1 //////////////////////////////////////////R de Pearson//@version=5//indicator('Regresión', overlay=true)
// Número de velas anteriores que analizaremos.//ModoDepuracion= trueScanner1=input.bool(true,title="Mostrar Scanner1")PeriodoCortoSc1 = input(70)PeriodoLargoSc1 = input(140)
// Si la aumentamos, veremos como el canal se hace más ámplio o menos. A más estrecho, más velas saldrán de él.deviationsSc1 = input.float(2.0,step=0.1)
// Cálculo de la recta de regresiónperiodMinusOne1Sc1 = PeriodoCortoSc1-1periodMinusOne2Sc1 = PeriodoLargoSc1-1
//Periodo cortoExcortoSc1 = 0.0, EycortoSc1 = 0.0, Ex2cortoSc1 = 0.0,Ey2cortoSc1 =0.0, ExycortoSc1 = 0.0, for i=0 to periodMinusOne1Sc1 closeI = nz(close[i]), ExcortoSc1 := ExcortoSc1 + i, EycortoSc1 := EycortoSc1 + closeI, Ex2cortoSc1 := Ex2cortoSc1 + (i * i),Ey2cortoSc1 := Ey2cortoSc1 + (closeI * closeI), ExycortoSc1 := ExycortoSc1 + (closeI * i)ExT2cortoSc1 = math.pow(ExcortoSc1,2.0) //Sum of X THEN SquaredEYT2cortoSc1 = math.pow(EycortoSc1,2.0) //Sym of Y THEN Squaredplot(ExcortoSc1, title="ExcortoSc1")plot(EycortoSc1, title="EycortoSc1")plot(Ex2cortoSc1, title="Ex2cortoSc1")plot(Ey2cortoSc1, title="Ey2cortoSc1")plot(ExT2cortoSc1, title="ExT2cortoSc1")plot(EYT2cortoSc1, title="EyT2cortoSc1")Esta es la traducción que he hecho de ese fragmento
//Declaración de Variables y Parámetros de Entrada Inputs:
periodo_corto(70),
periodo_largo(140),
deviations(0.2); Vars:
periodMinusOne1(periodo_corto - 1), Excorto(0), Eycorto(0), Ex2corto(0), Ey2corto(0), Exycorto(0), ExT2corto(0), EyT2corto(0), ExExcorto(0),
PearsonsRcorto(0), slopecorto(0), linearRegressioncorto(0), interceptcorto(0), deviationcorto(0), startingPointYcorto(0), periodMinusOne2(periodo_largo - 1), Exlargo(0), Eylargo(0), Ex2largo(0), Ey2largo(0), Exylargo(0), ExT2largo(0), EyT2largo(0), ExExlargo(0),
PearsonsRlargo(0), slopelargo(0), linearRegressionlargo(0), interceptlargo(0), deviationlargo(0), startingPointYlargo(0),
closeI(0),
e(0); //Cálculo de la Recta de Regresión para Periodo Corto For e = 0 to periodMinusOne1 begin
Excorto = Excorto + e;
Eycorto = Eycorto + close[e];
Ex2corto = Ex2corto + (e * e);
Ey2corto = Ey2corto + Square(close[e]);
Exycorto = Exycorto + (close[e] * e);
end; ExT2corto = Square(Excorto);
EyT2corto = Square(Eycorto); Plot10(Excorto, "Excorto");
Plot11(Eycorto, "Eycorto");No sé si el fallo puede estar en el bucle porque en tradestation no puedo usar [i] al ser reservada en programa y la he sustituido por e.
Otra cosa que he cambiado es CloseI=(nz(close[i])) Donde nz me devuelve el valor no nulo o 0 si es nulo. Yo simplemente he cambiado que closeI=close[e], porque entiendo que no va a tomar valor nulo (quizá es otro fallo) .Antes lo tenía hecho con una comparación, pero el resultado era el mismo.
A ver si vosotros que estáis más puestos en esto veis el fallo.
0 -
Aquí tienes una regresión lineal en pine script:
//@version=4
study(title="Regresión Lineal", shorttitle="LinReg", overlay=true) // Parámetros
length = input(14, title="Longitud") // Calcula la regresión lineal
linReg = linreg(close, length, 0) // Dibuja la línea de regresión
plot(linReg, color=color.blue, linewidth=2, title="Regresión Lineal")Añadiendo la desviación típica:
//@version=4
study(title="Regresión Lineal + Bollinger Bands", shorttitle="LinReg + BB", overlay=true) // Parámetros
length = input(14, title="Longitud")
deviations = input(2, title="Desviaciones estándar") // Calcula la regresión lineal
linReg = linreg(close, length, 0) // Calcula la desviación estándar
stdDev = stdev(close, length) // Calcula los canales de tendencia (Bollinger Bands)
upperBB = linReg + deviations * stdDev
lowerBB = linReg - deviations * stdDev // Dibuja la línea de regresión y los canales de tendencia
plot(linReg, color=color.blue, linewidth=2, title="Regresión Lineal")
plot(upperBB, color=color.green, linewidth=1, title="Upper BB")
plot(lowerBB, color=color.red, linewidth=1, title="Lower BB")Traducido a versión 5 de pine script:
//@version=5
indicator(title="Regresión Lineal + Bollinger Bands", shorttitle="LinReg + BB", overlay=true) // Parámetros
length = input.int(14, title="Longitud")
deviations = input.float(2, title="Desviaciones estándar") // Calcula la regresión lineal
linReg = ta.linreg(close, length, 0) // Calcula la desviación estándar
stdDev = ta.stdev(close, length) // Calcula los canales de tendencia (Bollinger Bands)
upperBB = linReg + deviations * stdDev
lowerBB = linReg - deviations * stdDev // Dibuja la línea de regresión y los canales de tendencia
plot(linReg, color=color.blue, linewidth=2, title="Regresión Lineal")
plot(upperBB, color=color.green, linewidth=1, title="Upper BB")
plot(lowerBB, color=color.red, linewidth=1, title="Lower BB")En este código, he utilizado las funciones específicas de Pine Script versión 5, como
input.int
,input.float
,ta.linreg
yta.stdev
. Los canales de Bollinger se calculan alrededor de la línea de regresión lineal. Puedes ajustar los parámetros según tus preferencias.Esta respuesta ha sido generada con sistemas de Inteligencia Artificial y revisada por el equipo de este foro.
1 -
Pues por muchas vueltas que le he dado y pruebas varias, no sé qué estoy haciendo mal, será una tontería, pero no doy. Si me podéis dar alguna pista os lo agradezco.
0 -
Bueno, lo he rehecho todo de nuevo tanto en pinescript como en la traducción a tradestation (con ayuda de mi amigo chatgpt) y parece que , aunque no es perfecto, va tomando forma.
1 -
Podrías compartir el código final si lo ves bien
🇪🇦
0 -
Claro, aquí te lo paso en pinescript. Es sólo un canal y es lo que he usado como base para crear el de Easylanguage ya con sus dos canales.
//@version=5 indicator("Recta de Regresión con Canal", overlay=true) // Parámetros de entrada length = input(70, title="Longitud de la Regresión") deviations = input.float(2.0, title="Desviaciones", step=0.1) // Variables para el cálculo de la regresión float sumX = 0 float sumY = 0 float sumXY = 0 float sumX2 = 0 float sumY2 = 0 // Bucle para calcular las sumas necesarias para la regresión for i = 0 to length - 1 sumX := sumX + i sumY := sumY + close[i] sumXY := sumXY + i * close[i] sumX2 := sumX2 + i * i sumY2 := sumY2 + close[i] * close[i] // Cálculo de los coeficientes de la recta de regresión slope = (length * sumXY - sumX * sumY) / (length * sumX2 - sumX * sumX) intercept = (sumY - slope * sumX) / length // Cálculo de la desviación estándar float deviation = 0 for i = 0 to length - 1 // deviation := deviation + math.pow(close[i] - (slope * i + intercept), 2) //deviation := math.sqrt(deviation / length) * deviations deviation := deviation + math.pow(nz(close[i]) - (intercept - slope * (bar_index[i])), 2.0) deviation := deviation * math.sqrt(deviation / (length-1)) // Cálculo del coeficiente de correlación de Pearson float pearsonR = ((length * sumXY) - (sumX * sumY)) / (math.sqrt((length * sumX2 - (sumX * sumX)) * (length * sumY2 - (sumY * sumY)))) // Variables para almacenar las líneas de la recta de regresión y los canales var line regLine = na var line upperChannel = na var line lowerChannel = na // Crear nuevas líneas y eliminar las anteriores if barstate.isconfirmed // Eliminar las líneas anteriores if not na(regLine) line.delete(regLine) if not na(upperChannel) line.delete(upperChannel) if not na(lowerChannel) line.delete(lowerChannel) // Dibujar la nueva recta de regresión y los canales en la última vela cerrada regLine := line.new(x1=bar_index-length+1, y1=slope * (length - 1) + intercept, x2=bar_index, y2=slope * 0 + intercept, color=color.blue, width=1) upperChannel := line.new(x1=bar_index-length+1, y1=slope * (length - 1) + intercept + deviation, x2=bar_index, y2=slope * 0 + intercept + deviation, color=color.red, width=1, style=line.style_dotted) lowerChannel := line.new(x1=bar_index-length+1, y1=slope * (length - 1) + intercept - deviation, x2=bar_index, y2=slope * 0 + intercept - deviation, color=color.green, width=1, style=line.style_dotted) // Opcional: Mostrar los valores de la regresión y desviación plot(slope, title="Pendiente", color=color.blue) plot(intercept, title="Intersección", color=color.red) plot(deviation, title="Desviación", color=color.green) plot(pearsonR*100, title="Coeficiente de Pearson", color=color.purple)
Puedes ver que es prácticamente lo mismo que el que tenemos en la formación, aunque hay una diferencia en el cálculo de la intersección, que me da unos valores muy distintos con el indicador de Luis y con éste, pero los valores de PearsonR y demás me dan iguales o muy parecidos a la centésima. Si Luis ve algún fallo que lo diga.
Ahora en EasyLanguage sería algo así. Ten en cuenta que la visualización de las líneas de tendencia aún no lo tengo terminado porque no me borra las anteriores y entonces va llenando el gráfico de líneas. Pero los cálculos los hace correctamente. Aquí ya tienes los dos canales de regresión corto y largo. Aún me queda bastante trabajo por hacerle pero llegar aquí también me ha costado bastante, así que a seguir con ello.
Inputs:
lengthCortoSc1(70),
deviationsCortoSc1(2.0),
lengthLargoSc1(140),
deviationsLargoSc1(2.0),
PearsonCortoAlcista(-0.7),
PearsonLargoAlcista(-0.4),
PearsonCortoBajista(0.7),
PearsonLargoBajista(0.4); Vars:
sumXCortoSc1(0),
sumYCortoSc1(0),
sumXYCortoSc1(0),
sumX2CortoSc1(0),
sumY2CortoSc1(0),
slopeCortoSc1(0),
interceptCortoSc1(0),
deviationCortoSc1(0),
pearsonRCortoSc1(0),
sumXLargoSc1(0),
sumYLargoSc1(0),
sumXYLargoSc1(0),
sumX2LargoSc1(0),
sumY2LargoSc1(0),
slopeLargoSc1(0),
interceptLargoSc1(0),
deviationLargoSc1(0),
pearsonRLargoSc1(0),
index(0),
closeI(0),
x1(0),
y1(0),
x2(0),
y2(0),
lineCorto1(0),
lineCorto2(0),
lineCorto3(0),
lineLargo1(0),
lineLargo2(0),
lineLargo3(0),
texto1(0),
texto2(0),
texto3(0),
texto4(0),
FiltroPearson(false),
FiltroPearsonBajista(false),
FiltroPearsonAlcista(false),
BGColor(0),
prevLineLargo1(0), prevLineLargo2(0), prevLineLargo3(0); // Calcular las sumatorias necesarias para el canal corto
sumXCortoSc1 = 0;
sumYCortoSc1 = 0;
sumXYCortoSc1 = 0;
sumX2CortoSc1 = 0;
sumY2CortoSc1 = 0; For index = 0 to lengthCortoSc1 - 1 Begin
closeI = Close[index];
sumXCortoSc1 = sumXCortoSc1 + index;
sumYCortoSc1 = sumYCortoSc1 + closeI;
sumXYCortoSc1 = sumXYCortoSc1 + index * closeI;
sumX2CortoSc1 = sumX2CortoSc1 + index * index;
sumY2CortoSc1 = sumY2CortoSc1 + closeI * closeI;
End; // Calcular los coeficientes de la recta de regresión para el canal corto
slopeCortoSc1 = (lengthCortoSc1 * sumXYCortoSc1 - sumXCortoSc1 * sumYCortoSc1) / (lengthCortoSc1 * sumX2CortoSc1 - sumXCortoSc1 * sumXCortoSc1);
interceptCortoSc1 = (sumYCortoSc1 - slopeCortoSc1 * sumXCortoSc1) / lengthCortoSc1; // Calcular la desviación estándar para el canal corto
deviationCortoSc1 = 0;
For index = 0 to lengthCortoSc1 - 1 Begin
closeI = Close[index];
deviationCortoSc1 = deviationCortoSc1 + (closeI - (slopeCortoSc1 * index + interceptCortoSc1)) * (closeI - (slopeCortoSc1 * index + interceptCortoSc1));
End;
deviationCortoSc1 = SquareRoot(deviationCortoSc1 / lengthCortoSc1) * deviationsCortoSc1; // Calcular el coeficiente de correlación de Pearson para el canal corto
pearsonRCortoSc1 = ((lengthCortoSc1 * sumXYCortoSc1) - (sumXCortoSc1 * sumYCortoSc1)) / SquareRoot((lengthCortoSc1 * sumX2CortoSc1 - (sumXCortoSc1 * sumXCortoSc1)) * (lengthCortoSc1 * sumY2CortoSc1 - (sumYCortoSc1 * sumYCortoSc1))); // Calcular las sumatorias necesarias para el canal largo
sumXLargoSc1 = 0;
sumYLargoSc1 = 0;
sumXYLargoSc1 = 0;
sumX2LargoSc1 = 0;
sumY2LargoSc1 = 0; For index = 0 to lengthLargoSc1 - 1 Begin
closeI = Close[index];
sumXLargoSc1 = sumXLargoSc1 + index;
sumYLargoSc1 = sumYLargoSc1 + closeI;
sumXYLargoSc1 = sumXYLargoSc1 + index * closeI;
sumX2LargoSc1 = sumX2LargoSc1 + index * index;
sumY2LargoSc1 = sumY2LargoSc1 + closeI * closeI;
End; // Calcular los coeficientes de la recta de regresión para el canal largo
slopeLargoSc1 = (lengthLargoSc1 * sumXYLargoSc1 - sumXLargoSc1 * sumYLargoSc1) / (lengthLargoSc1 * sumX2LargoSc1 - sumXLargoSc1 * sumXLargoSc1);
interceptLargoSc1 = (sumYLargoSc1 - slopeLargoSc1 * sumXLargoSc1) / lengthLargoSc1; // Calcular la desviación estándar para el canal largo
deviationLargoSc1 = 0;
For index = 0 to lengthLargoSc1 - 1 Begin
closeI = Close[index];
deviationLargoSc1 = deviationLargoSc1 + (closeI - (slopeLargoSc1 * index + interceptLargoSc1)) * (closeI - (slopeLargoSc1 * index + interceptLargoSc1));
End;
deviationLargoSc1 = SquareRoot(deviationLargoSc1 / lengthLargoSc1) * deviationsLargoSc1; // Calcular el coeficiente de correlación de Pearson para el canal largo
pearsonRLargoSc1 = ((lengthLargoSc1 * sumXYLargoSc1) - (sumXLargoSc1 * sumYLargoSc1)) / SquareRoot((lengthLargoSc1 * sumX2LargoSc1 - (sumXLargoSc1 * sumXLargoSc1)) * (lengthLargoSc1 * sumY2LargoSc1 - (sumYLargoSc1 * sumYLargoSc1))); // Dibujar las líneas de la recta de regresión y los canales
If LastBarOnChart Then Begin
//Tl_delete(lineCorto1);Tl_delete(lineCorto2[1]);Tl_delete(lineCorto3[1]);
// Canal corto
x1 = BarNumber - lengthCortoSc1 + 1;
y1 = slopeCortoSc1 * (lengthCortoSc1 - 1) + interceptCortoSc1;
x2 = BarNumber;
y2 = slopeCortoSc1 * 0 + interceptCortoSc1; lineCorto1 = TL_New(Date[lengthCortoSc1], Time[lengthCortoSc1], y1, Date[1], Time[1], y2);
TL_SetColor(lineCorto1, Blue);
TL_SetSize(lineCorto1, 1);
lineCorto2 = TL_New(Date[lengthCortoSc1], Time[lengthCortoSc1], y1 + deviationCortoSc1, Date[1], Time[1], y2 + deviationCortoSc1);
TL_SetColor(lineCorto2, Red);
TL_SetSize(lineCorto2, 1);
TL_SetStyle(lineCorto2, Tool_Dotted);
lineCorto3 = TL_New(Date[lengthCortoSc1], Time[lengthCortoSc1], y1 - deviationCortoSc1, Date[1], Time[1], y2 - deviationCortoSc1);
TL_SetColor(lineCorto3, Green);
TL_SetSize(lineCorto3, 1);
TL_SetStyle(lineCorto3, Tool_Dotted);
// Canal largo
x1 = BarNumber - lengthLargoSc1 + 1;
y1 = slopeLargoSc1 * (lengthLargoSc1 - 1) + interceptLargoSc1;
x2 = BarNumber;
y2 = slopeLargoSc1 * 0 + interceptLargoSc1;
// Eliminar las líneas anteriores si existen
//TL_Delete(prevLineLargo1);
//TL_Delete(prevLineLargo2);
//TL_Delete(prevLineLargo3);
lineLargo1 = TL_New(Date[lengthLargoSc1], Time[lengthLargoSc1], y1, Date[1], Time[1], y2);
TL_SetColor(lineLargo1, Cyan);
TL_SetSize(lineLargo1, 1);
lineLargo2 = TL_New(Date[lengthLargoSc1], Time[lengthLargoSc1], y1 + deviationLargoSc1, Date[1], Time[1], y2 + deviationLargoSc1);
TL_SetColor(lineLargo2, Magenta);
TL_SetSize(lineLargo2, 1);
TL_SetStyle(lineLargo2, Tool_Dotted);
lineLargo3 = TL_New(Date[lengthLargoSc1], Time[lengthLargoSc1], y1 - deviationLargoSc1, Date[1], Time[1], y2 - deviationLargoSc1);
TL_SetColor(lineLargo3, White);
TL_SetSize(lineLargo3, 1);
TL_SetStyle(lineLargo3, Tool_Dotted);
// Guardar referencias a las líneas actuales para eliminarlas en la próxima iteración
prevLineLargo1 = lineLargo1;
prevLineLargo2 = lineLargo2;
prevLineLargo3 = lineLargo3;
// Mostrar los valores de la regresión y la desviación
//Plot1(slope, "Pendiente",cyan);
//Plot2(intercept, "Intersección", Red);
//Plot3(deviation, "Desviación", Darkcyan);
//Plot4(pearsonR * 100, "Coeficiente de Pearson", yellow);
// Colorear el fondo del gráfico en verde cuando FiltroPearsonAlcista es verdadero y en rojo cuando FiltroPearsonBajista es verdadero
If FiltroPearsonAlcista Then
SetPlotColor(1, RGB(0, 230, 119)); // Verde
If FiltroPearsonBajista Then
SetPlotColor(1, RGB(230, 0, 0)); // Rojo
If FiltroPearsonAlcista = False and FiltroPearsonBajista = False Then
Setplotcolor(1, RGB(128, 128, 128)); // Neutro //SetPlotBGColor(1,RGB(0, 230, 119) );set
Plot1(pearsonRCortoSc1);No olvides que este código no es definitivo, sino que estoy en el proceso de creación y depuración, por tanto no confíes en la totalidad sin antes hacer tus propias comprobaciones. Si encuentras fallos o tienes alguna sugerencia, hazlo saber.
Cualquier cosa me dices.
1 -
Yo no le he dado al scanner todavia, pero como he visto el codigo de pine y tal, me puse ayer con esto y lo he sacado asi, que no se si estara bien, pero las lineas las pinta
Inputs:
Periodo1(100), Desviaciones(2); // Período para la regresión
Variables:
Slope(0), Intercept(0), Angle(0), LRValue(0),
e(0), Regresion(0), linea(0), periodMinusOne(0);
// Calcula los valores de la regresión lineal
linea = LinearReg(Close, Periodo1, 0, Slope, Angle, Intercept, LRValue);
// Dibuja la línea de regresión
for e = 0 to Periodo1 begin
Regresion = Intercept + Slope * (Periodo1 - 1 - e);
Plot1(Regresion, "Regresion");
end;
// CALCULOS LINEAS
Vars: linearRegression(0), desviacion(0),
startingPointY(0), backtest(0), finalpoint(0),
upperChannelLine(0), medianChannelLine(0), lowerChannelLine(0), interseccion(0);
periodMinusOne = Periodo1 - 1;
startingPointY = Regresion[Periodo1];
finalpoint = Regresion;
// Cálculo de la media y desviación estándar
desviacion = StandardDev(Close, Periodo1, 1);
// Cálculo de los puntos para el canal
vars: upperY(0), lowerY(0), regressionValue(0);
upperY = startingPointY + Desviaciones * desviacion;
lowerY = startingPointY - Desviaciones * desviacion;
if LastBarOnChart then begin
// Eliminar las líneas anteriores
if upperChannelLine < > 0 then
TL_Delete(upperChannelLine);
if lowerChannelLine < > 0 then
TL_Delete(lowerChannelLine);
// Crear las nuevas líneas del canal
upperChannelLine = TL_New(Date[periodMinusOne], Time[periodMinusOne], upperY, Date, Time, finalPoint + Desviaciones * desviacion);
TL_SetColor(upperChannelLine, Green);
TL_SetExtRight(upperChannelLine, false); medianChannelLine = TL_New(Date[Periodo1], Time[Periodo1], startingPointY, Date, Time, finalpoint);
TL_SetColor(medianChannelLine, white);
TL_SetExtRight(medianChannelLine, false); lowerChannelLine = TL_New(Date[periodMinusOne], Time[periodMinusOne], lowerY, Date, Time, finalPoint - Desviaciones * desviacion);
TL_SetColor(lowerChannelLine, Red);
TL_SetExtRight(lowerChannelLine, false); end;0 -
Lo de la desviación Standar es lo que no veo, pero lo de borrar las líneas lo tienes igual que lo había hecho yo y no me funciona. Cuando el mercado está parado no repinta porque no hay velas nuevas pero cuando se empiezan a crear las velas, empiezan a quedarse las líneas anteriores. He probado muchas cosas pero no lo he conseguido, a ver si tú aportas algo de luz.
0 -
A ver si es porque lo tienes despues en vez de antes del codigo que las pinta, o lo mismo cuando habra el mercado me las pinta a mi tambien que lo hecho ayer y hoy es festivo en USA
0 -
lo tuve antes del código y de diversas formas, pero no me lo hacía. A lo mejor era un detalle que se me pasó y a tí te funciona, luego cuando haya mercado y lo compruebes nos dices a ver qué tal. De todas formas es algo que no me preocupa porque lo uso para depurar y ver las entradas y demás pero para el strategy no lo necesito. Además puedo añadir un filtro para que me pinte o no y no activo cuando quiero verlo y luego lo desactivo, que opciones hay muchas, aunque claro que lo que quiero al final es poder hacerlo bien.
0
Categorías
- Todas las Categorías
- 19 Presentaciones
- 46 Nuestros sistemas (Curso gratuito)
- 70 Operativa y Sistemas de trading
- 44 Inversiones
- 12 Inteligencia Artificial y Optimización de Algoritmos
- 63 Plataformas
- 27 Programación e Inteligencia Artificial
- 21 Brokers
- 11 Bancos
- 31 Pruebas de fondeo
- 8 Psicología y Trading
- 6 Fiscalidad
- Emails
- 88 Otros temas