メインコンテンツへスキップ
見出し画像

【Pine Script】変数完全解説ガイド Index 【E~N】

    📚 1. はじめに

    トレーディングでカスタムインジケーターや自動売買戦略を作成する際、Pine Scriptの多彩な変数を制することは必須です。以下の記事では、基礎から応用まで各変数の特徴を正確に解説し、実践で役立つTipsを可能な限り盛り込みました。

    この記事の使い方

    コード例をそのままコピー&ペースト 実際に動かしながら理解を深める Tipsを参考に自分なりのカスタマイズを試す
    //@version=5
    indicator("My First Indicator", overlay=true)
    
    // サンプル: 単純移動平均
    sma_length = input.int(20, "SMA期間")
    my_sma     = ta.sma(close, sma_length)
    plot(my_sma, title="20期間SMA")
    

    🔮 2. 収益予測関連変数:未来を読み解く鍵

    Pine Scriptのearnings名前空間には、決算予測や実績データを取得する変数が揃っています。精度や単位に注意し、必ずnaチェックを行いましょう。

    earnings.future_eps/earnings.actual_eps:次回予想EPSと直近実績EPS

    • 説明:

      • earnings.future_eps:次回決算予想EPS

      • earnings.actual_eps:直近決算の実績EPS

    //@version=5
    indicator("EPS予測アラート", overlay=true)
    
    prev_eps = earnings.actual_eps          // 過去実績
    fut_eps  = earnings.future_eps         // 予想
    
    // naチェック
    if not na(prev_eps) and not na(fut_eps)
        if fut_eps > prev_eps * 1.1
            label.new(bar_index, high, "EPS↑予測", color=color.green)
    

    Tip:na() で必ず存在確認を行う。未公開銘柄などではnaが返る場合あり。 小数点以下精度に注意し、丸め処理(math.round)で比較すると過剰検知を防げます。

    earnings.future_revenue/earnings.estimate_revenue:売上予測とコンセンサス

    • 説明:

      • earnings.future_revenue:次回決算予想売上高

      • earnings.estimate_revenue:市場予想売上高

    // 収益上振れ期待のマーク
    is_revenue_beat = not na(earnings.future_revenue) and
                       not na(earnings.estimate_revenue) and
                       earnings.future_revenue > earnings.estimate_revenue
    plotshape(is_revenue_beat, style=shape.triangleup, location=location.belowbar)
    

    Tip:企業ごとに決算発表タイミングが異なるため、security()で複数ティッカーを扱う際はgaps_offを指定しておくと安心。

    earnings.future_period_end_time:会計期間終了日時

    • 説明:次回の会計期間(四半期・年度)の終了時刻(ミリ秒)。

    // 会計期間終了から30日以内をマーク
    period_end = earnings.future_period_end_time
    days_to_end = (period_end - timenow) / (1000 * 60 * 60 * 24)
    is_ending_soon = not na(days_to_end) and days_to_end < 30
    plotshape(is_ending_soon, style=shape.diamond, location=location.abovebar)
    

    Tip:timenowはミリ秒単位。単純な日数計算には上記のように除算で対応。 ミリ秒誤差を防ぐため、±1日程度のマージン条件を持たせると安全。

    earnings.future_time:決算発表日時

    • 説明:次回決算発表のタイムスタンプ(ミリ秒)。

    // 決算予告アラート(7日前)
    if not na(earnings.future_time)
        days_before = (earnings.future_time - timenow) / (1000 * 60 * 60 * 24)
        if days_before < 7 and days_before[1] >= 7
            alert("1週間以内に決算発表予定", alert.freq_once_per_bar)
    

    Tip:通知はalert.freq_once_per_barで一度だけ発生させ、過剰なアラートを防止。


    📊 3. 価格変数:チャート分析の基礎

    バーごとの価格データは、あらゆるテクニカル指標の基盤です。特性を理解し、目的に応じて使い分けましょう。

    high/low:最高値・最安値

    price_range = high - low
    plot(price_range, title="値幅")
    

    Tip:セッション切り替え時のギャップはhigh - lowに異常値を生むことがあるため、任意のセッション時間でリセットするロジックを入れると精度向上。

    hl2:(high + low)/ 2

    mid = hl2
    plot(ta.sma(mid, 20), title="HL2 SMA")
    

    Tip:レンジ相場ではhl2を使うと終値だけよりも中心価格に基づくトレンド把握がしやすい。

    hlc3:(high + low + close)/ 3

    hlc3_sma = ta.sma(hlc3, 20)
    plot(hlc3_sma, title="HLC3 SMA")
    

    Tip:ノイズが多い短期足では、hlc3の移動平均が滑らかに反応しやすい。

    hlcc4:(high + low + close + close)/ 4

    plot(hlcc4, title="HLCC4")
    

    Tip:終値に2倍のウェイトを置くため、終値中心のトレンド把握に最適。 分析対象ごとに比較し、最も適した平均値を選択。


    ⏰ 4. 時間関連変数:タイミングを制する者がトレードを制す

    取引セッションや季節性をスクリプトで捉えるには時間変数が不可欠です。

    hour/minute/month/dayofweek

    is_nyse = (hour >= 14 and hour < 21)
    if is_nyse
        bgcolor(color.new(color.blue, 90))
    

    Tip:hourはチャートのタイムゾーンに依存。UTC基準の場合は調整が必要。 dayofweekは1=月曜、7=日曜。週末フィルターを組み込みやすい。

    last_bar_time:最新バーのタイムスタンプ

    minutes_passed = (timenow - last_bar_time) / 60000
    plot(minutes_passed, title="最終バーからの経過分")
    

    Tip:リアルタイムデータ遅延を検出し、更新停止時にアラートを出す用途で活躍。


    🔍 5. 特殊インデックスと視覚化要素

    チャート上の描画要素は、各種*.all変数で動的に管理可能です。

    last_bar_index

    if bar_index == last_bar_index
        label.new(bar_index, high, "最新バー")
    

    Tip:リプレイモードでは更新されないため、本番運用時は注意。

    line.all/linefill.all/label.all/box.all

    if array.size(line.all) > 5
        line.delete(array.get(line.all, 0))
    

    Tip:古い要素を定期的に削除しないとチャートが重くなる。 box.allも同様に管理し、無駄なbox生成を避ける。


    ❓ 6. 特殊値「na」の理解:エラー回避の秘訣

    naはデータ未取得を示す値です。存在確認とフォールバックが堅牢なスクリプトの要。

    safe_sma = na(my_sma) ? close : my_sma
    

    Tip:na()関数でチェック。== naは常にfalse。 フォールバック値を必ず用意し、ゼロ除算を回避。


    🚨 7. よくある間違いとトラブルシューティング

    エラー 原因 :対策
    変数未定義 スコープの誤り:varで初期化 or ブロック外で宣言
    未来データ参照 :close[bar_index+N] 過去参照のみ。close[N]を使用
    timezone誤差 チャートTZ未調整:input.timezoneでオフセット指定
    精度差(hl2等) 手動計算と組み込み差: math.round(..., 精度)で丸め



    🔥 8. 実践編:変数を組み合わせた爆速スクリプト

    以下は時間・価格・描画要素を統合したマルチファクター戦略例。

    //@version=5
    strategy("Multi-Factor Strategy", overlay=true)
    
    // 時間フィルター
    is_us = (hour >= 14 and hour < 20)
    
    // ピンバー検出
    body = math.abs(close - open)
    upper = high - math.max(open, close)
    lower = math.min(open, close) - low
    is_bull = lower > body * 2 and upper < body
    
    // ボラフィルター
    atrp = ta.atr(14) / close * 100
    is_volatile = atrp > 1.0
    
    // トレンドフィルター
    fast = ta.ema(hlc3, 9)
    slow = ta.ema(hlc3, 21)
    up   = fast > slow
    down = fast < slow
    
    if is_us and is_bull and is_volatile and up
        strategy.entry("Long", strategy.long)
    if is_us and not is_bull and is_volatile and down
        strategy.entry("Short", strategy.short)
    

    Tip:varを使った累積変数更新で計算回数を削減。 各種フィルターをinput.boolでON/OFF可能にして試行錯誤しやすく。


    📝 9. まとめ:次のステップとチェックリスト

    1. 変数の存在確認:na()を必ず挟む

    2. セッション管理:時刻変数はチャートTZに依存

    3. 描画要素管理:*.allで不要要素を削除

    4. フォールバック値設定:ゼロ除算・naに備える

    5. 自作戦略の分割と検証:小さなパーツごとにバックテスト

    これらを実践し、独自のPine Scriptライブラリを構築してみましょう。Happy Coding!

    あなたへのおすすめ