【失敗】TSIゴールデンクロスで購入しMACDデッドクロスで売却

PineScript

バックテスト結果

対象VIX
対象期間2020年1月から2025年10月
純利益1.6%
トレード勝率134回中48回

反省点

・レンジ相場で「利益にならない売買」が多発する

→ 値動きが激しい時だけMACDのパラメータを変えたい

・MACDデッドクロスは景気動向に遅れて追従する指標であり、「上がった後に購入」「下がった後に売却」となることが多いから儲からない

→ 先行指標(TSIなど)と組み合わせて売却タイミングを決めたい

ソースコード

// @version=6
strategy("TSI積立法_MACD売却バックテスト", overlay=false, initial_capital=10000000)

// パラメータ
spanLong = input.int(12, "長期EMA", minval=1)
spanShort = input.int(6, "短期EMA", minval=1)
spanSignal = input.int(3, "シグナルEMA", minval=1)
macdFast = input.int(12, "MACD短期", minval=1)
macdSlow = input.int(26, "MACD長期", minval=1)
macdSignal = input.int(9, "MACDシグナル", minval=1)

// TSIの値を計算
tsi = ta.tsi(close, spanLong, spanShort)
tsiSignal = ta.ema(tsi, spanSignal)

// MACDの値を計算
[macdLine, signalLine, _] = ta.macd(close, macdFast, macdSlow, macdSignal)

// ゴールデンクロス(TSI)とデッドクロス(MACD)の判定
goldenCross = ta.crossover(tsi, tsiSignal)
deadCross = ta.crossunder(macdLine, signalLine)

// 購入金額の計算
var float buyAmount = 0.0
if tsi >= -10 and tsi < -0
    buyAmount := 100000.0
else if tsi >= -20 and tsi < -10
    buyAmount := 400000.0
else if tsi >= -30 and tsi < -20
    buyAmount := 900000.0
else if tsi < -30
    buyAmount := 1600000.0
else
    buyAmount := 0.0

// 保有情報の計算
var float totalInvested = 0.0  // 累計投資額
var float totalQty = 0.0       // 保有数量
var float realizedPL = 0.0     // 累計実現損益
var float realizedBuyCount = 0.0  // 累計購入回数
var float realizedBuyAmount = 0.0  // 累計購入金額

// 購入条件
if goldenCross and buyAmount > 0
    realizedBuyAmount := realizedBuyAmount + buyAmount
    realizedBuyCount := realizedBuyCount + 1
    // エントリーポイントをチャート上に青矢印でマーク
    strategy.entry(" ", strategy.long, qty=buyAmount / close)
    totalInvested := totalInvested + buyAmount
    totalQty := totalQty + (buyAmount / close)

// ポジションを閉じる条件(MACDデッドクロス)
if deadCross and totalQty > 0
    // 実現損益を計算(売却時の価格 - 投資額)
    realizedPL := realizedPL + (totalQty * close - totalInvested)
    strategy.close(" ")
    totalInvested := 0.0
    totalQty := 0.0

// 含み損益(円)
unrealizedPL = totalQty > 0 ? totalQty * close - totalInvested : 0.0

// 最後のバーで最終結果を表示
if barstate.islast
    var table results = table.new(position.bottom_right, 1, 1, border_width=1)
    table.cell(results, 0, 0, text="最終結果: 累計購入金額=" + str.tostring(realizedBuyAmount, "#,##0") + "円, 保有数量=" + str.tostring(totalQty, "#.####") + 
              ", 含み損益=" + str.tostring(unrealizedPL, "#,##0") + "円, 実現損益=" + str.tostring(realizedPL, "#,##0") + "円 累計購入回数=" + str.tostring(realizedBuyCount, "#") + "回", bgcolor=color.green, text_color=color.white)

// TSIとMACD表示
plot(tsi, "TSI短期", color=color.blue)
plot(tsiSignal, "TSI長期", color=color.orange)
plot(macdLine, "MACD Line", color=color.red)
plot(signalLine, "MACD Signal", color=color.yellow)
hline(0, "基準", color=color.gray)
BACK