algo-trading
БесплатноБез исполняемых скриптовНе проверенBuild algorithmic trading systems — backtesting, strategy development, live execution, and risk management. Use when tasks involve backtesting trading…
Об этом скилле
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 (auto-adjusted prices)."""
df = yf.download(ticker, period=period, interval=interval, auto_adjust=True)
# yfinance 1.x returns MultiIndex columns (Price, Ticker) even for one ticker;
# flatten and lowercase them so calculate_signals() finds df['close']
df.columns = [c.lower() for c in df.columns.get_level_values(0)] # 'Close' -> 'close'
return df
For real-time data, use WebSocket feeds. CCXT Pro ships with the ccxt package as ccxt.pro:
import asyncio
import ccxt.pro as ccxtpro
async def stream_orderbook(symbol: str = 'BTC/USDT', updates: int = 100):
exchange = ccxtpro.binance()
try:
for _ in range(updates):
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}%")
finally:
await exchange.close() # always close the WebSocket connection
asyncio.run(stream_orderbook())
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
from dataclasses import dataclass
@dataclass(frozen=True)
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'
Установить algo-trading в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл algo-trading?
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.
Как установить скилл algo-trading?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл algo-trading запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
skill-creator
Create new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an…
от Anthropicdiscernment-nudge
After you give a substantive answer or draft that the user may act on — advice or recommendations, drafted artifacts such as goals, plans, pitches, proposals…
от Anthropicdata-consolidate
Joins the plant's scheduled exports and connector data into one working dataset — ERP items (NetSuite or Infor M3), sales orders, production work orders…
от Anthropicinspection-to-capa
Runs the quality chain end to end: writes the nonconformance against the requirement it violates, searches history at the moment of writing to say whether…
от Anthropic