【失敗】MACDゴールデンクロスとMACDデッドクロスで売買
バックテスト
失敗
ソースコード
// @version=6
strategy("TSI積立法_MACD売買バックテスト", overlay=false, initial_capital=10000000)
// パラメータ
spanLong = input.int(12, "TSI長期EMA", minval=1)
spanShort = input.int(6, "TSI短期EMA", minval=1)
spanSignal = input.int(3, "TSIシグナル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)
// ゴールデンクロス・デッドクロス(MACD)
macdGolden = ta.crossover(macdLine, signalLine)
macdDead = ta.crossunder(macdLine, signalLine)
// 購入金額の計算(TSIの値で決める)
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
// 購入条件(MACDゴールデンクロス)
if macdGolden and buyAmount > 0
realizedBuyAmount += buyAmount
realizedBuyCount += 1
strategy.entry("Buy", strategy.long, qty=buyAmount / close)
totalInvested += buyAmount
totalQty += (buyAmount / close)
// 売却条件(MACDデッドクロス)
if macdDead and totalQty > 0
realizedPL += (totalQty * close - totalInvested)
strategy.close("Buy")
totalInvested := 0.0
totalQty := 0.0
// 含み損益
unrealizedPL = totalQty > 0 ? totalQty * close - totalInvested : 0.0
// プロット
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)