[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6GC3CQ836EMCMKQ81Y7ERN7":3,"skill-same:01M6GC3CQ836EMCMKQ81Y7ERN7":88},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":39,"linkOnly":40,"markdownContent":41,"markdownBody":42,"frontMatter":43,"refName":66,"commitSha":67,"skillDirectory":68,"forksCount":69,"repositoryHtmlUrl":70,"repositoryHomepageUrl":6,"ownerHtmlUrl":71,"ownerBlogUrl":6,"ownerDescription":72,"updatedAt":73,"install":74,"resources":87},"01M6GC3CQ836EMCMKQ81Y7ERN7","fx-lstm-forecast",null,"FX予測エンジン LSTMスキル - 短期〜中短期の通貨ペアリターン分布推定","zapabob\u002FSkills","zapabob","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F130830376?v=4","01M6DBMYZAGRTFQDSQYW3W764P","峯岸 亮","01M6DBMZ3GKDSJ01NZ9XTZD7JD",2,"MIT","https:\u002F\u002Fgithub.com\u002Fzapabob\u002FSkills\u002Fblob\u002Fmain\u002Farchive\u002Fskill-md-reviewed\u002Fsha256\u002Fa3\u002Fa3f993b5a46f2412731b6657446ad8f15e84f731b16c491f0a304259a4745b2c\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38],"fx lstm forecast","fx","forecast","lstm","hermes agent","size","paper","social","patterns","devops","management","linux","hermes","risk","risk-management","demo","windows","sync","research","memory","2026-11-10 10:12:30",false,"---\r\nname: fx-lstm-forecast\r\ndescription: FX予測エンジン LSTMスキル - 短期〜中短期の通貨ペアリターン分布推定\r\nversion: 0.1.0\r\nauthor: Hermes Agent\r\nlicense: MIT\r\nplatforms: [linux, windows]\r\nmetadata:\r\n  hermes.tags: [\"fx\", \"lstm\", \"forecast\", \"trading\", \"risk-management\"]\r\n  hermes.category: \"devops\"\r\n  hermes.related_skills: [\"cronjob-management\", \"memory-social-sync-patterns\"]\r\n  hermes.config:\r\n    gpu.visible_device: \"GPUインデックス\"\r\n    gpu.memory_fraction: \"VRAM使用率上限\"\r\n    data.symbols: \"予測対象シンボル\"\r\n    model.lstm.hidden_size: \"LSTM_hidden_size\"\r\n    model.lstm.num_layers: \"LSTM層数\"\r\n    model.lstm.dropout: \"ドロップアウト率\"\r\n    model.lstm.batch_size: \"バッチサイズ\"\r\n    model.lstm.max_epochs: \"最大エポック数\"\r\n    risk.max_risk_per_trade: \"トレードあたり最大リスク\"\r\n    risk.max_daily_loss: \"日間最大損失\"\r\n    risk.max_consecutive_losses: \"連続損失上限\"\r\n    execution.mode: \"実行モード（research|paper|demo）\"\r\n---\r\n\r\n# fx-lstm-forecast Skill\r\n\r\n## When to Use\r\n\r\n- デモ口座またはペーパートレードでLSTMモデルの妥当性を検証したいとき\r\n- GPU 12〜16GB環境（RTX 3060\u002F4060 Ti\u002F5060 Ti等）で推論・学習を試したいとき\r\n- 無料のYahooファイナンスデータ（yfinance）だけでまずは検証を開始したいとき\r\n- Hermes Agentから `fx_forecast` ツールを叩いて予測結果を得たいとき\r\n\r\n## Prerequisites\r\n\r\n- Python 3.12 + CUDA 12.1+ (RTX 5060 Tiは cu128 ビルド必須)\r\n- GPU: NVIDIA RTX 12GB以上推奨（VRAM 16GB確保）\r\n- 仮想環境: `.venv` または `conda` env\r\n- インストール済みパッケージ: `torch`, `numpy`, `pandas`, `yfinance`, `scikit-learn`, `fastapi`, `pyyaml`\r\n- FXデータへのアクセス: `yfinance`（無料）または任意のREST APIエンドポイント\r\n\r\n## How to Run\r\n\r\n### 1. 環境セットアップ\r\n\r\n```bash\r\n# リポジトリのクローンまたは新規作成\r\ngit clone https:\u002F\u002Fgithub.com\u002Fyour-org\u002Ffx-research-engine.git\r\ncd fx-research-engine\r\n\r\n# 仮想環境構築\r\npython -m venv .venv\r\n.\\.venv\\Scripts\\Activate.ps1  # Windows\r\nsource .venv\u002Fbin\u002Factivate      # Linux\u002FmacOS\r\n\r\n# 依存パッケージインストール（cu128対応PyTorch）\r\nuv pip install --index-strategy unsafe-best-match \\\r\n  --extra-index-url https:\u002F\u002Fdownload.pytorch.org\u002Fwhl\u002Fcu128 \\\r\n  torch numpy pandas yfinance scikit-learn fastapi \"uvicorn[standard]\" \\\r\n  scipy matplotlib pytest pyyaml\r\n\r\n# 開発モードインストール\r\nuv pip install -e .\r\n```\r\n\r\n### 2. 設定ファイルの確認\r\n\r\n`configs\u002Fresearch.yaml` を確認し、以下をチェック：\r\n\r\n```yaml\r\ngpu:\r\n  visible_device: \"0\"           # 使用GPUのインデックス\r\n  memory_fraction: 0.85         # VRAM使用率上限（16GB環境で15GB程度に制限）\r\n  precision: \"fp16\"             # 混合精度推論\r\n\r\ndata:\r\n  symbols: [\"USDJPY=X\", \"GBPJPY=X\", \"EURJPY=X\"]\r\n  timeframe: \"1h\"\r\n  lookback_years: 2\r\n\r\nmodel:\r\n  lstm:\r\n    hidden_size: 128\r\n    num_layers: 2\r\n    dropout: 0.3\r\n    batch_size: 32\r\n    max_epochs: 100\r\n\r\nrisk:\r\n  max_risk_per_trade: 0.005\r\n  max_daily_loss: 0.02\r\n  max_consecutive_losses: 3\r\n  paper_only: true\r\n\r\nexecution:\r\n  mode: \"research\"          # research | paper | demo\r\n```\r\n\r\n### 3. 最初の予測を実行\r\n\r\n```bash\r\n# ツールとして実行（Hermes読み込み時）\r\n\u002Fskill fx-lstm-forecast forecast --symbol USDJPY --timeframe H1 --horizon 5\r\n\r\n# または CLI 直接実行\r\npython -m fx_engine forecast --config configs\u002Fresearch.yaml --symbol USDJPY --timeframe H1 --horizon 5\r\n```\r\n\r\n## Quick Reference\r\n\r\n| コマンド \u002F ツール | 説明 |\r\n|---|---|\r\n| `\u002Fskill fx-lstm-forecast forecast` | 直近N本のリターン分布を予測 |\r\n| `python -m fx_engine lstm train` | LSTMモデルの学習 |\r\n| `python -m fx_engine lstm forecast` | 学習済みモデルでの推論 |\r\n| `python -m fx_engine walkforward` | ウォークフォワード検証 |\r\n| `python -m fx_engine report` | 学習・検証レポートの生成 |\r\n| `python -m fx_engine paper` | ペーパートレード記録\r\n\r\n## Alternative: Hermes Plugin\r\n\r\nFor immediate experimentation without installing dependencies, you can use the Hermes plugin `fx_lstm_forecast` which provides a simple forecast tool.\r\n\r\n```bash\r\n\u002Fskill fx_lstm_forecast forecast --symbol USDJPY --timeframe H1 --horizon 5\r\n```\r\n\r\nThis plugin tries to fetch real data from Yahoo Finance; if unavailable, it falls back to deterministic mock data so you always get a prediction.\r\n\r\n## Procedure\r\n\r\n### ステップ 1: 環境とデータの準備\r\n\r\n```python\r\n# verify_cuda.py スクリプト実行\r\npython scripts\u002Fverify_cuda.py\r\n# → CUDA利用可・GPU名称・VRAM確認\r\n\r\n# データ取得テスト\r\npython -c \"\r\nimport yfinance as yf\r\ndf = yf.download('USDJPY=X', period='2y', interval='1h')\r\nprint(f'取得バー数: {len(df)}')\r\nprint(f'期間: {df.index[0].date()} ~ {df.index[-1].date()}')\r\n\"\r\n```\r\n\r\n### ステップ 2: 特徴量エンジニアリング\r\n\r\n`src\u002Ffx_engine\u002Ffeatures\u002Ftechnicals.py` によります。以下の指標を計算し、将来のデータを参照しないよう注意：\r\n\r\n```python\r\n# 例: 単純移動平均・RSI・ボリンジャーバンド\r\ndef add_technical_features(df):\r\n    df['sma_5'] = df['Close'].rolling(5).mean()\r\n    df['sma_20'] = df['Close'].rolling(20).mean()\r\n    delta = df['Close'].diff()\r\n    ups = delta.clip(lower=0).rolling(14).mean()\r\n    downs = -delta.clip(upper=0).rolling(14).mean()\r\n    df['rsi'] = 100 - (100 \u002F (1 + ups \u002F downs))\r\n    df['bb_upper'] = df['Close'].rolling(20).mean() + 2 * df['Close'].rolling(20).std()\r\n    df['bb_lower'] = df['Close'].rolling(20).mean() - 2 * df['Close'].rolling(20).std()\r\n    return df\r\n```\r\n\r\n### ステップ 3: データ分割（時系列順）\r\n\r\n```python\r\n# ランダムシャッフル厳禁！\r\ntrain_end = int(len(df) * 0.7)\r\nval_end = int(len(df) * 0.85)\r\ntrain_df, val_df, test_df = df.iloc[:train_end], df.iloc[train_end:val_end], df.iloc[val_end:]\r\n```\r\n\r\n### ステップ 4: LSTMモデル学習\r\n\r\n`src\u002Ffx_engine\u002Fmodels\u002Flstm.py` 参照。AMP (FP16) を使用し、VRAM OOM対策で `max_norm_grad` 等を設定：\r\n\r\n```python\r\n# モデル定義（簡略版）\r\nclass LSTMForecaster(nn.Module):\r\n    def __init__(self, input_size, hidden_size=128, num_layers=2, dropout=0.3):\r\n        super().__init__()\r\n        self.lstm = nn.LSTM(input_size, hidden_size, num_layers, dropout=dropout, batch_first=True)\r\n        self.fc = nn.Linear(hidden_size, 1)  # 1ステップ先リターン予測\r\n\r\n    def forward(self, x):\r\n        out, _ = self.lstm(x)\r\n        out = self.fc(out[:, -1, :])  # 最後のタイムステップのみ使用\r\n        return out\r\n```\r\n\r\n学習時の重要ポイント：\r\n\r\n```python\r\n# 混合精度学習（AMP）の有効化\r\nscaler = torch.cuda.amp.GradScaler()\r\noptimizer = torch.optim.AdamW(model.parameters(), lr=3e-4)\r\n\r\nfor epoch in range(max_epochs):\r\n    model.train()\r\n    for batch in train_loader:\r\n        inputs, targets = batch  # shape: (B, seq_len, features), (B, 1)\r\n\r\n        optimizer.zero_grad()\r\n        with torch.cuda.amp.autocast():\r\n            outputs = model(inputs)\r\n            loss = criterion(outputs, targets)\r\n\r\n        scaler.scale(loss).backward()\r\n        scaler.unscale_(optimizer)\r\n        torch.nn.clip_grad_norm_(model.parameters(), max_norm=1.0)\r\n        scaler.step(optimizer)\r\n        scaler.update()\r\n\r\n    # 検証・早期停止処理...\r\n```\r\n\r\n### ステップ 5: 推論と予測分布\r\n\r\n```python\r\nmodel.eval()\r\nwith torch.no_grad():\r\n    with torch.cuda.amp.autocast():\r\n        pred = model(test_inputs)  # shape: (B, 1)\r\n\r\n    # 予測分布の計算（複数シミュレーションで区間推定）\r\n    n_simulations = 100\r\n    preds = []\r\n    for _ in range(n_simulations):\r\n        # ドロップアウト有効化によるモンテカルロ推定\r\n        pred_i = model(test_inputs)\r\n        preds.append(pred_i.item())\r\n\r\n    quantiles = np.percentile(preds, [10, 50, 90])\r\n    direction_prob = sum(1 for p in preds if p > 0) \u002F n_simulations\r\n```\r\n\r\n### ステップ 6: ウォークフォワード検証\r\n\r\n```python\r\n#  rolling-origin cross-validation\r\nresults = []\r\nfor fold in range(n_folds):\r\n    train = data[fold*step : fold*step + train_len]\r\n    test = data[fold*step + train_len : fold*step + train_len + test_len]\r\n\r\n    # モデル再学習・評価\r\n    model, score = train_and_evaluate(train, test)\r\n    results.append(score)\r\n\r\n# レポートにまとめる\r\nprint(f\"勝率: {sum(1 for s in results if s > 0) \u002F len(results):.2f}\")\r\nprint(f\"平均シャープ: {np.mean([s['sharpe'] for s in results]):.3f}\")\r\n```\r\n\r\n### ステップ 7: レポート生成\r\n\r\n```bash\r\npython -m fx_engine report --output artifacts\u002Freports\u002Flstm-h1-v001.json\r\n```\r\n\r\n## Pitfalls\r\n\r\n1. **CUDAバージョン不一致** → RTX 5060 Ti (sm_120) は必ず `cu128` ビルドのPyTorchでないとカーネルが実行されずエラーになる。常に `torch --version` で確認。\r\n2. **データリーク** → 時系列分割でランダムシャッフルを厳禁。特に技術指標の`shift()`処理をおろそかにすると未来情報が漏れる。\r\n3. **バッチサイズ過大** → 16GB VRAMでも LSTM のバッチサイズ 64 以上だと OOMになることがある。`fp16`・`gradient_accumulation` で調整。\r\n4. **予測 horizon の誤用** → 1本〜5本先まで。それ以上 then モデル不安定になるので実験時は短めに。\r\n5. **特徴量のスケーリング忘れ** → 標準化（StandardScaler）は訓練データのみで fit し、テスト\u002F予測時は transform だけ適用。\r\n\r\n## Verification\r\n\r\n### CUDA 有効確認\r\n\r\n```bash\r\npython -c \"import torch; print('CUDA available:', torch.cuda.is_available()); print('GPU:', torch.cuda.get_device_name(0)); print('VRAM:', torch.cuda.get_device_properties(0).total_memory \u002F 1e9, 'GB')\"\r\n# → True \u002F NVIDIA GeForce RTX 5060 Ti \u002F 16.311 GB\r\n```\r\n\r\n### LSTM 形状チェック\r\n\r\n```python\r\nimport torch\r\nx = torch.randn(4, 10, 5)  # (batch, seq_len, features)\r\nprint(x.shape)  # torch.Size([4, 10, 5])\r\n# モデル forward 実行可能かテスト\r\n```\r\n\r\n### 予測結果の妥当性\r\n\r\n```python\r\n# 予測リターンが極端に外れていないかチェック\r\npred_return = 0.0015  # 0.15% の予測\r\nassert -0.1 \u003C pred_return \u003C 0.1, \"予測リターンが現実的範囲外です\"\r\n```\r\n\r\n### レポート スキーマ検証\r\n\r\n`artifacts\u002Freports\u002F*.json` は以下のキーを必須とします。\r\n\r\n```json\r\n{\r\n  \"symbol\": \"USDJPY\",\r\n  \"timeframe\": \"H1\",\r\n  \"horizon_bars\": 5,\r\n  \"predicted_return\": 0.0012,\r\n  \"quantiles\": {\"p10\": -0.0008, \"p50\": 0.0012, \"p90\": 0.0027},\r\n  \"direction_probability\": 0.64,\r\n  \"model_version\": \"lstm-h1-v001\",\r\n  \"data_timestamp\": \"2026-10-10T12:00:00Z\",\r\n  \"training_history\": {...},\r\n  \"walkforward_results\": [...]\r\n}\r\n```\r\n\r\n## Support Files\r\n\r\nThis skill is accompanied by the following support files in the skill directory:\r\n\r\n- `references\u002Ftechnical-indicators.md` - Detailed technical indicator calculations and shift() warnings\r\n- `scripts\u002Fverify_cuda.py` - CUDA verification script\r\n- `scripts\u002Fcheck_data_leak.py` - Data leakage detection script for time series\r\n\r\nThese files are referenced in the skill's `references\u002F` directory and can be loaded via `skill_view(name='fx-lstm-forecast', file_path='references\u002Ftechnical-indicators.md')` etc.\r\n\r\nASI_ACCEL.","# fx-lstm-forecast Skill\r\n\r\n## When to Use\r\n\r\n- デモ口座またはペーパートレードでLSTMモデルの妥当性を検証したいとき\r\n- GPU 12〜16GB環境（RTX 3060\u002F4060 Ti\u002F5060 Ti等）で推論・学習を試したいとき\r\n- 無料のYahooファイナンスデータ（yfinance）だけでまずは検証を開始したいとき\r\n- Hermes Agentから `fx_forecast` ツールを叩いて予測結果を得たいとき\r\n\r\n## Prerequisites\r\n\r\n- Python 3.12 + CUDA 12.1+ (RTX 5060 Tiは cu128 ビルド必須)\r\n- GPU: NVIDIA RTX 12GB以上推奨（VRAM 16GB確保）\r\n- 仮想環境: `.venv` または `conda` env\r\n- インストール済みパッケージ: `torch`, `numpy`, `pandas`, `yfinance`, `scikit-learn`, `fastapi`, `pyyaml`\r\n- FXデータへのアクセス: `yfinance`（無料）または任意のREST APIエンドポイント\r\n\r\n## How to Run\r\n\r\n### 1. 環境セットアップ\r\n\r\n```bash\r\n# リポジトリのクローンまたは新規作成\r\ngit clone https:\u002F\u002Fgithub.com\u002Fyour-org\u002Ffx-research-engine.git\r\ncd fx-research-engine\r\n\r\n# 仮想環境構築\r\npython -m venv .venv\r\n.\\.venv\\Scripts\\Activate.ps1  # Windows\r\nsource .venv\u002Fbin\u002Factivate      # Linux\u002FmacOS\r\n\r\n# 依存パッケージインストール（cu128対応PyTorch）\r\nuv pip install --index-strategy unsafe-best-match \\\r\n  --extra-index-url https:\u002F\u002Fdownload.pytorch.org\u002Fwhl\u002Fcu128 \\\r\n  torch numpy pandas yfinance scikit-learn fastapi \"uvicorn[standard]\" \\\r\n  scipy matplotlib pytest pyyaml\r\n\r\n# 開発モードインストール\r\nuv pip install -e .\r\n```\r\n\r\n### 2. 設定ファイルの確認\r\n\r\n`configs\u002Fresearch.yaml` を確認し、以下をチェック：\r\n\r\n```yaml\r\ngpu:\r\n  visible_device: \"0\"           # 使用GPUのインデックス\r\n  memory_fraction: 0.85         # VRAM使用率上限（16GB環境で15GB程度に制限）\r\n  precision: \"fp16\"             # 混合精度推論\r\n\r\ndata:\r\n  symbols: [\"USDJPY=X\", \"GBPJPY=X\", \"EURJPY=X\"]\r\n  timeframe: \"1h\"\r\n  lookback_years: 2\r\n\r\nmodel:\r\n  lstm:\r\n    hidden_size: 128\r\n    num_layers: 2\r\n    dropout: 0.3\r\n    batch_size: 32\r\n    max_epochs: 100\r\n\r\nrisk:\r\n  max_risk_per_trade: 0.005\r\n  max_daily_loss: 0.02\r\n  max_consecutive_losses: 3\r\n  paper_only: true\r\n\r\nexecution:\r\n  mode: \"research\"          # research | paper | demo\r\n```\r\n\r\n### 3. 最初の予測を実行\r\n\r\n```bash\r\n# ツールとして実行（Hermes読み込み時）\r\n\u002Fskill fx-lstm-forecast forecast --symbol USDJPY --timeframe H1 --horizon 5\r\n\r\n# または CLI 直接実行\r\npython -m fx_engine forecast --config configs\u002Fresearch.yaml --symbol USDJPY --timeframe H1 --horizon 5\r\n```\r\n\r\n## Quick Reference\r\n\r\n| コマンド \u002F ツール | 説明 |\r\n|---|---|\r\n| `\u002Fskill fx-lstm-forecast forecast` | 直近N本のリターン分布を予測 |\r\n| `python -m fx_engine lstm train` | LSTMモデルの学習 |\r\n| `python -m fx_engine lstm forecast` | 学習済みモデルでの推論 |\r\n| `python -m fx_engine walkforward` | ウォークフォワード検証 |\r\n| `python -m fx_engine report` | 学習・検証レポートの生成 |\r\n| `python -m fx_engine paper` | ペーパートレード記録\r\n\r\n## Alternative: Hermes Plugin\r\n\r\nFor immediate experimentation without installing dependencies, you can use the Hermes plugin `fx_lstm_forecast` which provides a simple forecast tool.\r\n\r\n```bash\r\n\u002Fskill fx_lstm_forecast forecast --symbol USDJPY --timeframe H1 --horizon 5\r\n```\r\n\r\nThis plugin tries to fetch real data from Yahoo Finance; if unavailable, it falls back to deterministic mock data so you always get a prediction.\r\n\r\n## Procedure\r\n\r\n### ステップ 1: 環境とデータの準備\r\n\r\n```python\r\n# verify_cuda.py スクリプト実行\r\npython scripts\u002Fverify_cuda.py\r\n# → CUDA利用可・GPU名称・VRAM確認\r\n\r\n# データ取得テスト\r\npython -c \"\r\nimport yfinance as yf\r\ndf = yf.download('USDJPY=X', period='2y', interval='1h')\r\nprint(f'取得バー数: {len(df)}')\r\nprint(f'期間: {df.index[0].date()} ~ {df.index[-1].date()}')\r\n\"\r\n```\r\n\r\n### ステップ 2: 特徴量エンジニアリング\r\n\r\n`src\u002Ffx_engine\u002Ffeatures\u002Ftechnicals.py` によります。以下の指標を計算し、将来のデータを参照しないよう注意：\r\n\r\n```python\r\n# 例: 単純移動平均・RSI・ボリンジャーバンド\r\ndef add_technical_features(df):\r\n    df['sma_5'] = df['Close'].rolling(5).mean()\r\n    df['sma_20'] = df['Close'].rolling(20).mean()\r\n    delta = df['Close'].diff()\r\n    ups = delta.clip(lower=0).rolling(14).mean()\r\n    downs = -delta.clip(upper=0).rolling(14).mean()\r\n    df['rsi'] = 100 - (100 \u002F (1 + ups \u002F downs))\r\n    df['bb_upper'] = df['Close'].rolling(20).mean() + 2 * df['Close'].rolling(20).std()\r\n    df['bb_lower'] = df['Close'].rolling(20).mean() - 2 * df['Close'].rolling(20).std()\r\n    return df\r\n```\r\n\r\n### ステップ 3: データ分割（時系列順）\r\n\r\n```python\r\n# ランダムシャッフル厳禁！\r\ntrain_end = int(len(df) * 0.7)\r\nval_end = int(len(df) * 0.85)\r\ntrain_df, val_df, test_df = df.iloc[:train_end], df.iloc[train_end:val_end], df.iloc[val_end:]\r\n```\r\n\r\n### ステップ 4: LSTMモデル学習\r\n\r\n`src\u002Ffx_engine\u002Fmodels\u002Flstm.py` 参照。AMP (FP16) を使用し、VRAM OOM対策で `max_norm_grad` 等を設定：\r\n\r\n```python\r\n# モデル定義（簡略版）\r\nclass LSTMForecaster(nn.Module):\r\n    def __init__(self, input_size, hidden_size=128, num_layers=2, dropout=0.3):\r\n        super().__init__()\r\n        self.lstm = nn.LSTM(input_size, hidden_size, num_layers, dropout=dropout, batch_first=True)\r\n        self.fc = nn.Linear(hidden_size, 1)  # 1ステップ先リターン予測\r\n\r\n    def forward(self, x):\r\n        out, _ = self.lstm(x)\r\n        out = self.fc(out[:, -1, :])  # 最後のタイムステップのみ使用\r\n        return out\r\n```\r\n\r\n学習時の重要ポイント：\r\n\r\n```python\r\n# 混合精度学習（AMP）の有効化\r\nscaler = torch.cuda.amp.GradScaler()\r\noptimizer = torch.optim.AdamW(model.parameters(), lr=3e-4)\r\n\r\nfor epoch in range(max_epochs):\r\n    model.train()\r\n    for batch in train_loader:\r\n        inputs, targets = batch  # shape: (B, seq_len, features), (B, 1)\r\n\r\n        optimizer.zero_grad()\r\n        with torch.cuda.amp.autocast():\r\n            outputs = model(inputs)\r\n            loss = criterion(outputs, targets)\r\n\r\n        scaler.scale(loss).backward()\r\n        scaler.unscale_(optimizer)\r\n        torch.nn.clip_grad_norm_(model.parameters(), max_norm=1.0)\r\n        scaler.step(optimizer)\r\n        scaler.update()\r\n\r\n    # 検証・早期停止処理...\r\n```\r\n\r\n### ステップ 5: 推論と予測分布\r\n\r\n```python\r\nmodel.eval()\r\nwith torch.no_grad():\r\n    with torch.cuda.amp.autocast():\r\n        pred = model(test_inputs)  # shape: (B, 1)\r\n\r\n    # 予測分布の計算（複数シミュレーションで区間推定）\r\n    n_simulations = 100\r\n    preds = []\r\n    for _ in range(n_simulations):\r\n        # ドロップアウト有効化によるモンテカルロ推定\r\n        pred_i = model(test_inputs)\r\n        preds.append(pred_i.item())\r\n\r\n    quantiles = np.percentile(preds, [10, 50, 90])\r\n    direction_prob = sum(1 for p in preds if p > 0) \u002F n_simulations\r\n```\r\n\r\n### ステップ 6: ウォークフォワード検証\r\n\r\n```python\r\n#  rolling-origin cross-validation\r\nresults = []\r\nfor fold in range(n_folds):\r\n    train = data[fold*step : fold*step + train_len]\r\n    test = data[fold*step + train_len : fold*step + train_len + test_len]\r\n\r\n    # モデル再学習・評価\r\n    model, score = train_and_evaluate(train, test)\r\n    results.append(score)\r\n\r\n# レポートにまとめる\r\nprint(f\"勝率: {sum(1 for s in results if s > 0) \u002F len(results):.2f}\")\r\nprint(f\"平均シャープ: {np.mean([s['sharpe'] for s in results]):.3f}\")\r\n```\r\n\r\n### ステップ 7: レポート生成\r\n\r\n```bash\r\npython -m fx_engine report --output artifacts\u002Freports\u002Flstm-h1-v001.json\r\n```\r\n\r\n## Pitfalls\r\n\r\n1. **CUDAバージョン不一致** → RTX 5060 Ti (sm_120) は必ず `cu128` ビルドのPyTorchでないとカーネルが実行されずエラーになる。常に `torch --version` で確認。\r\n2. **データリーク** → 時系列分割でランダムシャッフルを厳禁。特に技術指標の`shift()`処理をおろそかにすると未来情報が漏れる。\r\n3. **バッチサイズ過大** → 16GB VRAMでも LSTM のバッチサイズ 64 以上だと OOMになることがある。`fp16`・`gradient_accumulation` で調整。\r\n4. **予測 horizon の誤用** → 1本〜5本先まで。それ以上 then モデル不安定になるので実験時は短めに。\r\n5. **特徴量のスケーリング忘れ** → 標準化（StandardScaler）は訓練データのみで fit し、テスト\u002F予測時は transform だけ適用。\r\n\r\n## Verification\r\n\r\n### CUDA 有効確認\r\n\r\n```bash\r\npython -c \"import torch; print('CUDA available:', torch.cuda.is_available()); print('GPU:', torch.cuda.get_device_name(0)); print('VRAM:', torch.cuda.get_device_properties(0).total_memory \u002F 1e9, 'GB')\"\r\n# → True \u002F NVIDIA GeForce RTX 5060 Ti \u002F 16.311 GB\r\n```\r\n\r\n### LSTM 形状チェック\r\n\r\n```python\r\nimport torch\r\nx = torch.randn(4, 10, 5)  # (batch, seq_len, features)\r\nprint(x.shape)  # torch.Size([4, 10, 5])\r\n# モデル forward 実行可能かテスト\r\n```\r\n\r\n### 予測結果の妥当性\r\n\r\n```python\r\n# 予測リターンが極端に外れていないかチェック\r\npred_return = 0.0015  # 0.15% の予測\r\nassert -0.1 \u003C pred_return \u003C 0.1, \"予測リターンが現実的範囲外です\"\r\n```\r\n\r\n### レポート スキーマ検証\r\n\r\n`artifacts\u002Freports\u002F*.json` は以下のキーを必須とします。\r\n\r\n```json\r\n{\r\n  \"symbol\": \"USDJPY\",\r\n  \"timeframe\": \"H1\",\r\n  \"horizon_bars\": 5,\r\n  \"predicted_return\": 0.0012,\r\n  \"quantiles\": {\"p10\": -0.0008, \"p50\": 0.0012, \"p90\": 0.0027},\r\n  \"direction_probability\": 0.64,\r\n  \"model_version\": \"lstm-h1-v001\",\r\n  \"data_timestamp\": \"2026-10-10T12:00:00Z\",\r\n  \"training_history\": {...},\r\n  \"walkforward_results\": [...]\r\n}\r\n```\r\n\r\n## Support Files\r\n\r\nThis skill is accompanied by the following support files in the skill directory:\r\n\r\n- `references\u002Ftechnical-indicators.md` - Detailed technical indicator calculations and shift() warnings\r\n- `scripts\u002Fverify_cuda.py` - CUDA verification script\r\n- `scripts\u002Fcheck_data_leak.py` - Data leakage detection script for time series\r\n\r\nThese files are referenced in the skill's `references\u002F` directory and can be loaded via `skill_view(name='fx-lstm-forecast', file_path='references\u002Ftechnical-indicators.md')` etc.\r\n\r\nASI_ACCEL.",{"name":5,"author":44,"license":15,"version":45,"metadata":46,"platforms":65,"description":7},"Hermes Agent","0.1.0",{"hermes.tags":47,"hermes.config":49,"hermes.category":28,"hermes.related_skills":62},[20,22,21,48,33],"trading",{"data.symbols":50,"execution.mode":51,"gpu.visible_device":52,"model.lstm.dropout":53,"gpu.memory_fraction":54,"risk.max_daily_loss":55,"model.lstm.batch_size":56,"model.lstm.max_epochs":57,"model.lstm.num_layers":58,"model.lstm.hidden_size":59,"risk.max_risk_per_trade":60,"risk.max_consecutive_losses":61},"予測対象シンボル","実行モード（research|paper|demo）","GPUインデックス","ドロップアウト率","VRAM使用率上限","日間最大損失","バッチサイズ","最大エポック数","LSTM層数","LSTM_hidden_size","トレードあたり最大リスク","連続損失上限",[63,64],"cronjob-management","memory-social-sync-patterns",[30,35],"main","0d1434f89f4bc6b07e9d272accd8c1013768820f","archive\u002Fskill-md-reviewed\u002Fsha256\u002Fa3\u002Fa3f993b5a46f2412731b6657446ad8f15e84f731b16c491f0a304259a4745b2c",0,"https:\u002F\u002Fgithub.com\u002Fzapabob\u002FSkills","https:\u002F\u002Fgithub.com\u002Fzapabob","The Open University of JAPAN　2019-now\r\n\r\nTokyo University of Science　2007-2010","2026-10-26 16:29:01",{"source":8,"skillName":5,"commands":75,"prompt":85,"zipAvailable":86},[76,79,82],{"tool":77,"command":78},"npx","npx skills add zapabob\u002FSkills --skill fx-lstm-forecast",{"tool":80,"command":81},"bunx","bunx skills add zapabob\u002FSkills --skill fx-lstm-forecast",{"tool":83,"command":84},"pnpm","pnpm dlx skills add zapabob\u002FSkills --skill fx-lstm-forecast","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fzapabob\u002FSkills\u002Fblob\u002Fmain\u002Farchive\u002Fskill-md-reviewed\u002Fsha256\u002Fa3\u002Fa3f993b5a46f2412731b6657446ad8f15e84f731b16c491f0a304259a4745b2c\u002FSKILL.md",true,[],[89,109,133,157,181,196],{"skillNo":90,"name":91,"nameZh":6,"description":92,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":93,"categories":94,"keywords":95,"publishedAt":39},"01M6GJTE1GESGGF9K028Y7753E","xurl","X\u002FTwitter via xurl CLI: post, search, DM, media, v2 API.","https:\u002F\u002Fgithub.com\u002Fzapabob\u002FSkills\u002Fblob\u002Fmain\u002Fregistry\u002Fskills\u002Fxurl\u002Fvariants\u002Fhermes-agent\u002FSKILL.md",[],[91,96,97,98,99,30,35,100,101,102,103,104,105,31,23,106,66,26,107,108],"openclaw","macos","cli","github","official","search","https","social-media","api","Media","twitter","via","post",{"skillNo":110,"name":111,"nameZh":6,"description":112,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":113,"categories":114,"keywords":115,"publishedAt":39},"01M6GJT8S1PXQ8WPXT1HSNBWH2","writing-plans","Write implementation plans: bite-sized tasks, paths, code.","https:\u002F\u002Fgithub.com\u002Fzapabob\u002FSkills\u002Fblob\u002Fmain\u002Fregistry\u002Fskills\u002Fwriting-plans\u002Fvariants\u002Fhermes-agent\u002FSKILL.md",[],[116,117,118,119,97,120,30,121,35,122,123,124,125,126,127,128,129,130,131,132],"writing","writing plans","plans","design","review","workflow","documentation","tasks","development","code","planning","code-review","subagent","write","superpowers","paths","test-driven-development",{"skillNo":134,"name":135,"nameZh":6,"description":136,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":137,"categories":138,"keywords":139,"publishedAt":39},"01M6GJST0H5X7WHBJ3BZK0DVKH","whisper","OpenAI's general-purpose speech recognition model. Supports 99 languages, transcription, translation to English, and language identification. Six model sizes from tiny (39M params) to large (1550M params). Use for speech-to-text, podcast transcription, or multilingual audio processing. Best for robust, multilingual ASR.","https:\u002F\u002Fgithub.com\u002Fzapabob\u002FSkills\u002Fblob\u002Fmain\u002Fregistry\u002Fskills\u002Fwhisper\u002Fvariants\u002Fhermes-agent-optional\u002FSKILL.md",[],[135,97,30,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156],"openai","speech","multimodal","Transformers","ASR","Audio","text","model","speech recognition","use","general","multilingual","translation","english","identification","processing","Audio Processing",{"skillNo":158,"name":159,"nameZh":6,"description":160,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":161,"categories":162,"keywords":163,"publishedAt":39},"01M6GJSMRQ8EETZTYMG72P70EA","weights-and-biases","W&B: log ML experiments, sweeps, model registry, dashboards.","https:\u002F\u002Fgithub.com\u002Fzapabob\u002FSkills\u002Fblob\u002Fmain\u002Fregistry\u002Fskills\u002Fweights-and-biases\u002Fvariants\u002Fhermes-agent\u002FSKILL.md",[],[164,97,165,166,35,167,168,169,170,171,172,147,173,174,175,176,177,178,179,180],"weights and biases","tensorflow","experiments","pytorch","visualization","registry","real-time","tuning","dashboards","experiment","log","time","Experiment Tracking","Model Registry","Hyperparameter Tuning","WandB","Real-Time Visualization",{"skillNo":182,"name":183,"nameZh":6,"description":184,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":185,"categories":186,"keywords":187,"publishedAt":39},"01M6GJS19KDPRY112JTR326S06","watchers","Poll RSS, JSON APIs, and GitHub with watermark dedup.","https:\u002F\u002Fgithub.com\u002Fzapabob\u002FSkills\u002Fblob\u002Fmain\u002Fregistry\u002Fskills\u002Fwatchers\u002Fvariants\u002Fhermes-agent-optional\u002FSKILL.md",[],[183,97,188,99,30,189,190,191,192,193,194,31,23,28,195],"terminal","automation","http","monitoring","cron","json","rss","with",{"skillNo":197,"name":198,"nameZh":6,"description":199,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":200,"categories":201,"keywords":202,"publishedAt":39},"01M6GJRHJD2A6Q830SWF9W48BC","serving-llms-vllm","vLLM: high-throughput LLM serving, OpenAI API, quantization.","https:\u002F\u002Fgithub.com\u002Fzapabob\u002FSkills\u002Fblob\u002Fmain\u002Fregistry\u002Fskills\u002Fvllm\u002Fvariants\u002Fhermes-agent\u002FSKILL.md",[],[203,204,205,30,37,140,206,207,208,143,209,104,210,211,212,213,214,215,216,217],"llms","vLLM","serving llms vllm","openai api","tensor","Inference Serving","Production","llm serving","High Throughput","PagedAttention","Continuous Batching","Quantization","Tensor Parallelism","high-throughput","throughput"]