La idea principal de esta estrategia es simular el comercio en tiempo real, recopilar datos de transacciones semanales y mostrar los resultados estadísticos en forma de tablas para ver el rendimiento de la estrategia de manera más intuitiva. Puede ayudarnos a evaluar rápidamente la rentabilidad de la estrategia, identificar los períodos de tiempo en los que la estrategia no funciona bien y, en consecuencia, ajustar y optimizar la estrategia.
Establezca el inicio y el final del ciclo de cálculo.
Establece la precisión de las estadísticas y el número de semanas que cada grupo contiene.
La estrategia de simulación RSI para comprar y vender.
Definir las variables en las tablas estadísticas.
Calcular el resultado del ciclo actual.
Si el ciclo cambia y permite la negociación, registre el tiempo y el resultado de este ciclo.
Si es la última línea K y se permite la transacción, registre el tiempo y el resultado del ciclo actual.
Si el ciclo cambia y no se permite el comercio, se registra el tiempo y el resultado del ciclo anterior.
Encuentra el máximo y el mínimo de los ciclos.
Las estadísticas de rendimiento.
En primer lugar, calcular el total de los períodos de estadística
Recorre cada ciclo, rinde la cabeza, el tiempo y el resultado
Resultados acumulados para cada grupo de ciclos
Los resultados positivos y negativos están marcados por colores
Puede ver en tiempo real los resultados de las operaciones semanales y evaluar rápidamente el rendimiento de la estrategia.
La presentación de los resultados de forma intuitiva, a primera vista, permite identificar los períodos en los que las estrategias no funcionan bien
Los parámetros de la estrategia se pueden ajustar y optimizar en función de las ganancias y pérdidas de un período de tiempo
Ganancias acumuladas de varias semanas de una estrategia de mantenimiento de posición a largo plazo
Se puede hacer un análisis comparativo de los estilos de negociación de diferentes períodos de tiempo
Precisión estadística y número de semanas de agrupación personalizadas para satisfacer diferentes necesidades
El código es sencillo, claro, fácil de entender y rediseñar.
Esta estrategia se basa en el RSI para hacer simulaciones de comercio, la estrategia RSI tiene sus propias desventajas de no ser lo suficientemente fuerte para seguir la tendencia
En el mercado real, los costos de transacción tienen un impacto mayor en los resultados.
Los datos históricos utilizados para la retroalimentación no siempre reflejan el entorno real de las transacciones
Los resultados estadísticos dependen de la cantidad de fondos en la cuenta real, y la cantidad de fondos predeterminados en la medición de retrospectiva no es necesariamente exacta.
Se debe tener cuidado para evitar la sobreadaptación y modificar los parámetros de la política a ciegas según los resultados de la evaluación.
Puede combinar más indicadores para juzgar la tendencia y optimizar los puntos de entrada y salida para fortalecer la estrategia RSI. Cuando se negocie en el mercado real, tenga en cuenta la configuración de las comisiones según los parámetros reales.
Se puede considerar la adición de la lógica de stop loss para controlar la pérdida individual
Optimización de los parámetros de la estrategia, como el ajuste de la tendencia a la baja y baja del RSI
Se puede probar con diferentes frecuencias de negociación, por ejemplo, el comercio en el día o la posesión mensual
Se pueden agregar más indicadores para determinar las tendencias del mercado y el momento de entrada
Se puede considerar la adición de la lógica de la parada
Configuración para optimizar los parámetros estadísticos
Se puede considerar la realización de estadísticas sobre varios tipos de activos
Al agregar un stop loss, se puede controlar mejor el riesgo y la relación de ganancias. Optimizar los parámetros RSI puede aumentar la tasa de ganancias. Adoptar más indicadores y diferentes frecuencias de negociación puede hacer que la estrategia sea más estable. Ajustar los parámetros estadísticos puede hacer que los resultados sean más destacados.
El objetivo de esta estrategia es recopilar los resultados de las operaciones periódicas y mostrarlos de manera visual en forma de tablas estadísticas, lo que permite juzgar rápidamente la rentabilidad de la estrategia en diferentes períodos de tiempo. Esto proporciona soporte de datos para la optimización de la estrategia.
/*backtest
start: 2023-09-12 00:00:00
end: 2023-10-12 00:00:00
period: 3h
basePeriod: 15m
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/
//@version=5
// strategy('Strategy weekly results as numbers v1', overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=25, commission_type=strategy.commission.percent, commission_value=0.04)
after = input(title='Trade after', defval=timestamp('01 Jan 2019 00:00 UTC'), tooltip="Strategy will be executed after this timestamp. The statistic table will include only periods after this date.")
before = input(title='Trade before', defval=timestamp('31 Dec 2024 23:59 UTC'), tooltip="Strategy will be executes before this timestamp. The statistic table will include only periods before this date.")
statisticPrecision = input.int(title='Statistic precision', group='Statistic visualisation', defval=1, tooltip="Defines how many digits should be rendered in every statistic cell.")
statisticGroupSize = input.int(title='Statistic group size', group='Statistic visualisation', defval=12, tooltip="Defines how many cells should be in one group inside the statistic table.")
// determinet whether the starategy should be traded between the period
isTradeEnabled = true
// *******************************************************************************************
// Core strategy simulation logic
// *******************************************************************************************
// calculate rsi strategy emulation data
rsiEmulationData = ta.rsi(close, 7)
rsiEmulationCrossover = ta.crossover(rsiEmulationData, 70)
rsiEmulationCrossunder = ta.crossunder(rsiEmulationData, 30)
// entry loogic based on the rsi calculations
if (isTradeEnabled and rsiEmulationCrossover)
strategy.entry('Long', strategy.long)
if (isTradeEnabled and rsiEmulationCrossunder)
strategy.entry('Short', strategy.short)
// *******************************************************************************************
// Weekly statistics table
// *******************************************************************************************
// define statistic variables
var statisticTable = table(na)
var statisticPeriodTime = array.new_int(0)
var statisticPeriodResult = array.new_float(0)
var statisticIsLatestCalculated = bool(na)
var statisticResultHighest = float(na)
var statisticResultLowest = float(na)
var statisticColorGray = color.new(color.gray, transp = 60)
var statisticColorGreen = color.new(color.green, transp = 60)
var statisticColorRed = color.new(color.red, transp = 60)
// claculate current period result
barResult = not na(strategy.equity[1])
? (strategy.equity / strategy.equity[1] - 1) : 0
isPeriodChanged = not na(time[1]) and weekofyear(time) != weekofyear(time[1])
currentPeriodResult = 0.0
currentPeriodResult := not na(currentPeriodResult[1]) and not isPeriodChanged
? ((1 + currentPeriodResult[1]) * (1 + barResult) - 1) : 0.0
// initialise highest and lowest results variables
statisticResultHighest := na(statisticResultHighest) ? currentPeriodResult : statisticResultHighest
statisticResultLowest := na(statisticResultLowest) ? currentPeriodResult : statisticResultLowest
// search for highest and lowest results
statisticResultHighest := currentPeriodResult > statisticResultHighest ? currentPeriodResult : statisticResultHighest
statisticResultLowest := currentPeriodResult < statisticResultLowest ? currentPeriodResult : statisticResultLowest
// new week while trade is active
if isPeriodChanged and isTradeEnabled
timeCalculated = time - 1000 * 60 * 60 * 24 * 7
resultCalculated = currentPeriodResult[1]
statisticIsLatestCalculated := false
array.push(statisticPeriodTime, timeCalculated)
array.push(statisticPeriodResult, resultCalculated)
// latest bar while trade is active
if barstate.islast and isTradeEnabled
timeCalculated = time - 1000 * 60 * 60 * 24 * (dayofweek(time) - 2)
resultCalculated = currentPeriodResult
array.push(statisticPeriodTime, timeCalculated)
array.push(statisticPeriodResult, resultCalculated)
// new week after trade disabled
if isPeriodChanged and not isTradeEnabled and not na(statisticIsLatestCalculated) and not statisticIsLatestCalculated
timeCalculated = time - 1000 * 60 * 60 * 24 * (dayofweek(time) + 5)
resultCalculated = currentPeriodResult[1]
statisticIsLatestCalculated := true
array.push(statisticPeriodTime, timeCalculated)
array.push(statisticPeriodResult, resultCalculated)
// render statistics table
if barstate.islast
statisticLength = array.size(statisticPeriodResult)
statisticTableSteps = math.floor(statisticLength / statisticGroupSize) + (statisticLength % statisticGroupSize != 0 ? 1 : 0)
statisticTable := table.new(position.bottom_right, columns = statisticGroupSize + 2, rows = statisticTableSteps + 1, border_width = 1)
// render headers
for i = 0 to (statisticGroupSize - 1)
statisticHeaderContent = str.tostring(i + 1)
table.cell(statisticTable, 1 + i, 0, statisticHeaderContent, bgcolor = statisticColorGray)
// render time points
for i = 0 to (statisticTableSteps - 1)
statisticPointContent = str.format("{0,date,medium}", array.get(statisticPeriodTime, i * statisticGroupSize))
table.cell(statisticTable, 0, 1 + i, statisticPointContent, bgcolor = statisticColorGray)
// render the result
statisticResultCummulative = 0.0
for i = 0 to (array.size(statisticPeriodTime) - 1)
statisticColumn = 1 + i % statisticGroupSize
statisticRow = 1 + math.floor(i / statisticGroupSize)
statisticResult = array.get(statisticPeriodResult, i)
statisticResultCummulative := (i % statisticGroupSize == 0) ? 0.0 : statisticResultCummulative
statisticResultCummulative := (1 + statisticResultCummulative) * (1 + statisticResult) - 1
statisticResultColor = statisticResult > 0 ? statisticColorGreen : statisticColorRed
table.cell(statisticTable, statisticColumn, statisticRow, str.tostring(math.round(statisticResult * 100, statisticPrecision)), bgcolor = statisticResultColor)
// if it is the last item of the row or data array
isStatisticLastOfTheRow = ((i + 1) % statisticGroupSize) == 0
isStatisticLastOfTheData = i == (statisticLength - 1)
if (isStatisticLastOfTheRow or isStatisticLastOfTheData)
resultsTableCummulativeCellColor = statisticResultCummulative > 0 ? statisticColorGreen : statisticColorRed
resultsTableCummulativeCellContent = str.tostring(math.round(statisticResultCummulative * 100, statisticPrecision))
table.cell(statisticTable, 1 + statisticGroupSize, statisticRow, resultsTableCummulativeCellContent, bgcolor = resultsTableCummulativeCellColor)