Ferramenta de Análise de Estratégia Dinâmica


Data de criação: 2023-10-13 15:54:35 última modificação: 2023-10-13 15:54:35
cópia: 1 Cliques: 465
1
focar em
1235
Seguidores

Visão geral

A ideia principal desta estratégia é simular negociações em tempo real, coletar dados de negociação semanais e apresentar os resultados estatísticos em forma de tabela, para visualizar o desempenho da estratégia de forma mais intuitiva. Ela pode nos ajudar a avaliar rapidamente os ganhos e perdas da estratégia, identificar períodos de tempo em que a estratégia não está funcionando bem e, portanto, ajustar e otimizar a estratégia.

Princípio da estratégia

  1. Configure o início e o fim do ciclo de cálculo.

  2. Configure a precisão das estatísticas e o número de semanas incluídas em cada grupo.

  3. Simulação de estratégias de RSI para compra e venda.

  4. Defina uma variável na tabela estatística.

  5. Calcule o resultado do ciclo atual.

  6. Caso o ciclo mude e permita a negociação, registre o tempo e o resultado desse ciclo.

  7. Se for a última linha K e permitir transações, registre o tempo e o resultado do ciclo atual.

  8. Caso o ciclo mude e não permita transações, anote o tempo e os resultados do ciclo anterior.

  9. Procure o resultado do ciclo máximo e mínimo.

  10. Tabela estatística de renderização.

  • Em primeiro lugar, calcule o número total de períodos de estatística.

  • Percorra cada ciclo, a cabeça, o tempo e o resultado

  • Cumulação de resultados para cada grupo de ciclos

  • Cores para os resultados positivos e negativos

Análise de vantagens

  • Observação de resultados semanais em tempo real para avaliar rapidamente o desempenho da estratégia

  • A demonstração intuitiva dos resultados, de uma só vez, permite identificar os períodos de fracasso da estratégia

  • Parâmetros de estratégia que podem ser ajustados e otimizados de acordo com os ganhos e perdas do período

  • Com facilidade, pode-se acompanhar o retorno acumulado de várias semanas de uma estratégia de longo prazo

  • Análise comparativa de estilos de negociação de diferentes períodos de tempo

  • A precisão estatística personalizada e o número de semanas de agrupamento para atender a diferentes necessidades

  • Código simples, claro, fácil de entender e reutilizar

Análise de Riscos

  • Esta estratégia baseia-se em simulações de negociação RSI, a estratégia RSI em si tem uma desvantagem de não ser forte o suficiente para acompanhar a tendência

  • No mercado físico, as taxas de transação têm maior influência nos resultados.

  • Os dados históricos usados para a retrospectiva não necessariamente refletem o ambiente de negociação real.

  • Os resultados estatísticos dependem da quantidade de fundos na conta real, e a quantidade de fundos padrão na retrospectiva não é necessariamente exata

  • Prevenção de overfitting, modificando os parâmetros da estratégia de forma cega com base nos resultados da avaliação

Pode-se combinar mais indicadores para julgar a tendência, otimizar o ponto de entrada e saída, para aumentar a estratégia RSI. Quando negociar em tempo real, preste atenção ao ajuste de comissões de acordo com os parâmetros reais.

Direção de otimização

  • Pode-se considerar a adição de lógica de stop loss para controlar a perda individual

  • Optimizar os parâmetros da estratégia, como ajustar a tendência de queda e queda do RSI

  • Pode-se experimentar diferentes frequências de negociação, como negociação diária ou posições mensais

  • Mais indicadores podem ser adicionados para avaliar tendências de mercado e tempo de entrada

  • Pode considerar a inclusão da lógica de bloqueio

  • Configurações que permitem otimizar parâmetros estatísticos

  • Pode-se considerar a implementação de estatísticas para vários tipos de ativos

Ao adicionar um stop loss, é possível controlar melhor o risco e a taxa de ganho. Otimizar os parâmetros do RSI pode aumentar a taxa de vitória. Adotar mais indicadores e diferentes frequências de negociação pode tornar a estratégia mais estável. Ajustar os parâmetros estatísticos pode tornar os resultados mais destacados.

Resumir

O objetivo da estratégia é coletar os resultados das negociações periódicas, apresentando-os de forma intuitiva em forma de tabelas estatísticas, para que seja possível avaliar rapidamente os ganhos e perdas da estratégia em diferentes períodos de tempo. Isso fornece suporte de dados para a otimização da estratégia.

Código-fonte da estratégia
/*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)