jpskill.com
🛠️ 開発・MCP コミュニティ

algo-trading

アルゴリズム取引システムを構築し、過去データでの検証や戦略開発、実際の取引実行、リスク管理などを行い、暗号資産と伝統的市場の両方で取引ボットを構築するSkill。

📜 元の英語説明(参考)

Build algorithmic trading systems — backtesting, strategy development, live execution, and risk management. Use when tasks involve backtesting trading strategies, connecting to exchange APIs (Binance, Alpaca, Interactive Brokers), implementing technical indicators, portfolio optimization, order execution, risk management rules, market data processing, or building trading bots. Covers both crypto and traditional markets.

🇯🇵 日本人クリエイター向け解説

一言でいうと

アルゴリズム取引システムを構築し、過去データでの検証や戦略開発、実際の取引実行、リスク管理などを行い、暗号資産と伝統的市場の両方で取引ボットを構築するSkill。

※ jpskill.com 編集部が日本のビジネス現場向けに補足した解説です。Skill本体の挙動とは独立した参考情報です。

⚡ おすすめ: コマンド1行でインストール(60秒)

下記のコマンドをコピーしてターミナル(Mac/Linux)または PowerShell(Windows)に貼り付けてください。 ダウンロード → 解凍 → 配置まで全自動。

🍎 Mac / 🐧 Linux
mkdir -p ~/.claude/skills && cd ~/.claude/skills && curl -L -o algo-trading.zip https://jpskill.com/download/14625.zip && unzip -o algo-trading.zip && rm algo-trading.zip
🪟 Windows (PowerShell)
$d = "$env:USERPROFILE\.claude\skills"; ni -Force -ItemType Directory $d | Out-Null; iwr https://jpskill.com/download/14625.zip -OutFile "$d\algo-trading.zip"; Expand-Archive "$d\algo-trading.zip" -DestinationPath $d -Force; ri "$d\algo-trading.zip"

完了後、Claude Code を再起動 → 普通に「動画プロンプト作って」のように話しかけるだけで自動発動します。

💾 手動でダウンロードしたい(コマンドが難しい人向け)
  1. 1. 下の青いボタンを押して algo-trading.zip をダウンロード
  2. 2. ZIPファイルをダブルクリックで解凍 → algo-trading フォルダができる
  3. 3. そのフォルダを C:\Users\あなたの名前\.claude\skills\(Win)または ~/.claude/skills/(Mac)へ移動
  4. 4. Claude Code を再起動

⚠️ ダウンロード・利用は自己責任でお願いします。当サイトは内容・動作・安全性について責任を負いません。

🎯 このSkillでできること

下記の説明文を読むと、このSkillがあなたに何をしてくれるかが分かります。Claudeにこの分野の依頼をすると、自動で発動します。

📦 インストール方法 (3ステップ)

  1. 1. 上の「ダウンロード」ボタンを押して .skill ファイルを取得
  2. 2. ファイル名の拡張子を .skill から .zip に変えて展開(macは自動展開可)
  3. 3. 展開してできたフォルダを、ホームフォルダの .claude/skills/ に置く
    • · macOS / Linux: ~/.claude/skills/
    • · Windows: %USERPROFILE%\.claude\skills\

Claude Code を再起動すれば完了。「このSkillを使って…」と話しかけなくても、関連する依頼で自動的に呼び出されます。

詳しい使い方ガイドを見る →
最終更新
2026-05-18
取得日時
2026-05-18
同梱ファイル
1

📖 Skill本文(日本語訳)

※ 原文(英語/中国語)を Gemini で日本語化したものです。Claude 自身は原文を読みます。誤訳がある場合は原文をご確認ください。

アルゴリズム取引

概要

アルゴリズム取引戦略の構築、バックテスト、およびデプロイを行います。市場データの取り込み、戦略開発、現実的な仮定に基づいたバックテスト、リスク管理、およびライブ実行について説明します。

手順

アーキテクチャ

Market Data → Data Pipeline → Strategy Engine → Risk Manager → Order Executor → Exchange
     ↑                              ↓                                    ↓
     └──────────── Performance Monitor ←────── Position Tracker ←────────┘

データパイプライン

# data_fetcher.py — 過去のOHLCVデータの取得

import ccxt
import yfinance as yf

def fetch_crypto_ohlcv(symbol: str, timeframe: str, since: str) -> list:
    """Binanceからローソク足を取得します。[timestamp, O, H, L, C, V]を返します。"""
    exchange = ccxt.binance()
    ohlcv = exchange.fetch_ohlcv(symbol, timeframe,
                                  since=exchange.parse8601(since), limit=1000)
    return ohlcv

def fetch_stock_data(ticker: str, period: str = '2y', interval: str = '1d'):
    """Yahoo Financeから株価のOHLCVを取得します。"""
    return yf.download(ticker, period=period, interval=interval)

リアルタイムデータには、WebSocketフィード(ccxt.pro)を使用します。

async def stream_orderbook(symbol: str = 'BTC/USDT'):
    exchange = ccxtpro.binance()
    while True:
        ob = await exchange.watch_order_book(symbol)
        spread = (ob['asks'][0][0] - ob['bids'][0][0]) / ob['bids'][0][0] * 100
        print(f"{symbol} Spread: {spread:.4f}%")

戦略開発

一般的なタイプ: モメンタム/トレンドフォロー(MA、RSI、MACD)、平均回帰(z-スコア、Bollinger Bands)、統計的裁定取引(ペア取引、クロスエクスチェンジ)、マーケットメイク(スプレッドキャプチャ)。

# strategy.py — RSIフィルター付きデュアル移動平均クロスオーバー

import pandas as pd

def calculate_signals(df: pd.DataFrame, fast=20, slow=50, rsi_period=14):
    """OHLCVデータから取引シグナルを生成します。"""
    df['sma_fast'] = df['close'].rolling(window=fast).mean()
    df['sma_slow'] = df['close'].rolling(window=slow).mean()

    delta = df['close'].diff()
    gain = delta.where(delta > 0, 0).rolling(window=rsi_period).mean()
    loss = (-delta.where(delta < 0, 0)).rolling(window=rsi_period).mean()
    df['rsi'] = 100 - (100 / (1 + gain / loss))

    df['signal'] = 0
    df.loc[(df['sma_fast'] > df['sma_slow']) &
           (df['sma_fast'].shift(1) <= df['sma_slow'].shift(1)) &
           (df['rsi'] < 70), 'signal'] = 1   # 買い
    df.loc[(df['sma_fast'] < df['sma_slow']) &
           (df['sma_fast'].shift(1) >= df['sma_slow'].shift(1)) &
           (df['rsi'] > 30), 'signal'] = -1  # 売り
    return df

バックテスト

バックテストでは、手数料、スリッページ、ストップロスなど、実際の状況をモデル化する必要があります。

# backtester.py — 現実的な仮定に基づいたベクトル化されたバックテスター

class BacktestConfig:
    commission: float = 0.001     # 1取引あたり0.1%
    slippage: float = 0.0005      # 推定0.05%
    initial_capital: float = 10000
    position_size: float = 0.1    # 1取引あたりポートフォリオの10%
    stop_loss: float = 0.02       # 2%ストップロス
    take_profit: float = 0.06     # 6%テイクプロフィット(3:1 R/R)

主要な指標:

RETURNS: Total Return, Annualized Return, Alpha (vs buy-and-hold)
RISK: Max Drawdown (<15%), Sharpe Ratio (>1.0 good, >2.0 excellent), Sortino, Calmar
TRADING: Win Rate (>45% for trend, >55% for mean reversion), Profit Factor (>1.5)

リスク管理

ポジションサイジング: 固定フラクショナル(1取引あたりX%)またはKelly Criterion(f = (bp - q) / b、安全のためハーフケリーを使用)。

# risk_manager.py — すべての注文の前にリスクルールを適用

RISK_RULES = {
    'max_position_pct': 0.10,       # 1ポジションあたり最大10%
    'max_portfolio_risk': 0.02,     # 1取引あたり最大2%のリスク
    'max_daily_loss': 0.05,         # 1日の損失が5%を超えたら停止
    'max_drawdown': 0.15,           # ドローダウンが15%を超えたら停止
    'max_correlation': 0.7,         # 相関のあるポジションは不可
}

ライブ実行

# executor.py — 安全チェック付きのライブ注文

def place_order(exchange, symbol, side, amount, order_type='limit', price=None):
    ticker = exchange.fetch_ticker(symbol)
    if order_type == 'market':
        spread = (ticker['ask'] - ticker['bid']) / ticker['bid'] * 100
        if spread > 0.5:
            raise ValueError(f"Spread too wide: {spread:.2f}%")
    if order_type == 'limit' and price:
        deviation = abs(price - ticker['last']) / ticker['last'] * 100
        if deviation > 2.0:
            raise ValueError(f"Limit price {deviation:.1f}% from market")
    return exchange.create_order(symbol, order_type, side, amount, price)

常に最初にペーパートレードを行ってください:Alpaca(組み込み)、Binance Testnet、Interactive Brokers(TWS)。ライブ資金の前に、最低1か月または100回の取引を実行してください。

暗号通貨のモメンタム戦略を構築する

BinanceでBTC/USDTのモメンタム取引戦略を構築します。ボリューム確認とRSIフィルターを使用して、EMAクロスオーバー(12/26)を使用します。現実的な手数料(0.1%テイカー)で2年間の時間足データをバックテストし、シャープレシオと最大ドローダウンを計算し、バイ・アンド・ホールドと比較します。2%のストップロスと6%のテイクプロフィットを含めます。

ペア取引システムを作成する

相関のある株式ペアを取引する統計的裁定取引システムを構築します。コインテグレーションテストを使用してS&P 500からペアを見つけ、z-スコア平均回帰戦略を実装し、取引コストでバックテストします。ペア選択プロセス、エントリー/エグジットルール、およびリスク管理を含めます。

リスク管理を備えたライブ取引ボットを設定する

米国株のAlpacaにライブ取引ボットをデプロイします。20の流動性の高いETFのユニバースで単純なモメンタム戦略を実行し、指値注文で実行し、ポジションサイズ制限(1保有あたり最大10%)を適用し、1日の損失が2%を超えた場合は取引を停止する必要があります。Telegram経由の監視、ロギング、およびアラートを含めます。

ガイドライン

  • 常に現実的な手数料、スリッページ、ストップロスでバックテストしてください。非現実的なバックテストは無意味です。
  • Neve

(原文がここで切り詰められています)

📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開

Algorithmic Trading

Overview

Build, backtest, and deploy algorithmic trading strategies. Cover market data ingestion, strategy development, backtesting with realistic assumptions, risk management, and live execution.

Instructions

Architecture

Market Data → Data Pipeline → Strategy Engine → Risk Manager → Order Executor → Exchange
     ↑                              ↓                                    ↓
     └──────────── Performance Monitor ←────── Position Tracker ←────────┘

Data pipeline

# data_fetcher.py — Fetch historical OHLCV data

import ccxt
import yfinance as yf

def fetch_crypto_ohlcv(symbol: str, timeframe: str, since: str) -> list:
    """Fetch candles from Binance. Returns [timestamp, O, H, L, C, V]."""
    exchange = ccxt.binance()
    ohlcv = exchange.fetch_ohlcv(symbol, timeframe,
                                  since=exchange.parse8601(since), limit=1000)
    return ohlcv

def fetch_stock_data(ticker: str, period: str = '2y', interval: str = '1d'):
    """Fetch stock OHLCV from Yahoo Finance."""
    return yf.download(ticker, period=period, interval=interval)

For real-time data, use WebSocket feeds (ccxt.pro):

async def stream_orderbook(symbol: str = 'BTC/USDT'):
    exchange = ccxtpro.binance()
    while True:
        ob = await exchange.watch_order_book(symbol)
        spread = (ob['asks'][0][0] - ob['bids'][0][0]) / ob['bids'][0][0] * 100
        print(f"{symbol} Spread: {spread:.4f}%")

Strategy development

Common types: Momentum/trend following (MAs, RSI, MACD), mean reversion (z-scores, Bollinger Bands), statistical arbitrage (pairs trading, cross-exchange), market making (spread capture).

# strategy.py — Dual Moving Average Crossover with RSI filter

import pandas as pd

def calculate_signals(df: pd.DataFrame, fast=20, slow=50, rsi_period=14):
    """Generate trading signals from OHLCV data."""
    df['sma_fast'] = df['close'].rolling(window=fast).mean()
    df['sma_slow'] = df['close'].rolling(window=slow).mean()

    delta = df['close'].diff()
    gain = delta.where(delta > 0, 0).rolling(window=rsi_period).mean()
    loss = (-delta.where(delta < 0, 0)).rolling(window=rsi_period).mean()
    df['rsi'] = 100 - (100 / (1 + gain / loss))

    df['signal'] = 0
    df.loc[(df['sma_fast'] > df['sma_slow']) &
           (df['sma_fast'].shift(1) <= df['sma_slow'].shift(1)) &
           (df['rsi'] < 70), 'signal'] = 1   # Buy
    df.loc[(df['sma_fast'] < df['sma_slow']) &
           (df['sma_fast'].shift(1) >= df['sma_slow'].shift(1)) &
           (df['rsi'] > 30), 'signal'] = -1  # Sell
    return df

Backtesting

A backtest must model real conditions — fees, slippage, and stop-losses:

# backtester.py — Vectorized backtester with realistic assumptions

class BacktestConfig:
    commission: float = 0.001     # 0.1% per trade
    slippage: float = 0.0005      # 0.05% estimated
    initial_capital: float = 10000
    position_size: float = 0.1    # 10% of portfolio per trade
    stop_loss: float = 0.02       # 2% stop-loss
    take_profit: float = 0.06     # 6% take-profit (3:1 R/R)

Key metrics:

RETURNS: Total Return, Annualized Return, Alpha (vs buy-and-hold)
RISK: Max Drawdown (<15%), Sharpe Ratio (>1.0 good, >2.0 excellent), Sortino, Calmar
TRADING: Win Rate (>45% for trend, >55% for mean reversion), Profit Factor (>1.5)

Risk management

Position sizing: Fixed fractional (X% per trade) or Kelly Criterion (f = (bp - q) / b, use half-Kelly for safety).

# risk_manager.py — Enforce risk rules before every order

RISK_RULES = {
    'max_position_pct': 0.10,       # Max 10% per position
    'max_portfolio_risk': 0.02,     # Max 2% risk per trade
    'max_daily_loss': 0.05,         # Stop after 5% daily loss
    'max_drawdown': 0.15,           # Stop after 15% drawdown
    'max_correlation': 0.7,         # No correlated positions
}

Live execution

# executor.py — Live orders with safety checks

def place_order(exchange, symbol, side, amount, order_type='limit', price=None):
    ticker = exchange.fetch_ticker(symbol)
    if order_type == 'market':
        spread = (ticker['ask'] - ticker['bid']) / ticker['bid'] * 100
        if spread > 0.5:
            raise ValueError(f"Spread too wide: {spread:.2f}%")
    if order_type == 'limit' and price:
        deviation = abs(price - ticker['last']) / ticker['last'] * 100
        if deviation > 2.0:
            raise ValueError(f"Limit price {deviation:.1f}% from market")
    return exchange.create_order(symbol, order_type, side, amount, price)

Always paper trade first: Alpaca (built-in), Binance Testnet, Interactive Brokers (TWS). Run 1 month or 100 trades minimum before live capital.

Examples

Build a crypto momentum strategy

Build a momentum trading strategy for BTC/USDT on Binance. Use EMA crossover (12/26) with volume confirmation and RSI filter. Backtest on 2 years of hourly data with realistic fees (0.1% taker), calculate Sharpe ratio and max drawdown, and compare against buy-and-hold. Include stop-loss at 2% and take-profit at 6%.

Create a pairs trading system

Build a statistical arbitrage system that trades correlated stock pairs. Use cointegration testing to find pairs from the S&P 500, implement a z-score mean reversion strategy, and backtest with transaction costs. Include the pair selection process, entry/exit rules, and risk management.

Set up a live trading bot with risk management

Deploy a live trading bot on Alpaca for US stocks. It should run a simple momentum strategy on a universe of 20 liquid ETFs, execute via limit orders, enforce position size limits (max 10% per holding), and stop trading if daily loss exceeds 2%. Include monitoring, logging, and alerting via Telegram.

Guidelines

  • Always backtest with realistic fees, slippage, and stop-losses — unrealistic backtests are worthless
  • Never skip paper trading — run for at least 1 month or 100 trades before deploying live capital
  • Use half-Kelly criterion for position sizing to add a safety margin
  • Implement hard daily loss limits and max drawdown circuit breakers
  • Check spread width before market orders — never market-order into thin books
  • Compare every strategy against buy-and-hold; if it underperforms, it's not worth the complexity
  • Log every order, signal, and risk check for post-mortem analysis