Логотип Corporate Action Adjusted Backtesting

Corporate Action Adjusted Backtesting

Сообщество
HimanshuJ16
corporate-action-adjusted-backtesting

Используйте, когда дробление или обратное дробление акций либо денежный дивиденд создают искусственные разрывы в истории цен бэктеста и порождают ложные сигналы. Навык строит скорректированный задним числом ряд по правилам CRSP для генерации сигналов, отдельно учитывая денежные дивиденды.

Add to TypingMind

Обзор

ИздательHimanshuJ16
РепозиторийAlgo-Trading-Skills
Название навыкаcorporate-action-adjusted-backtesting
Звёзды
50
Форки
7
Файлы в комплекте
5
ЛицензияApache-2.0
Ссылки
  • Инструкции в формате Markdown

    Модель загружает файл SKILL.md по мере необходимости, поэтому токены расходуются только при подходящем запросе.

  • Работает с любой большой языковой моделью

    Навыки ИИ — это обычный Markdown, а не код для конкретного поставщика, поэтому они работают с GPT, Claude, Gemini, Grok и локальными моделями.

  • Файлы в комплекте: 5

    Скрипты, шаблоны и справочные материалы, которые модель может читать во время работы. Файлы доступны только для чтения и никогда не выполняются.

  • Открытый исходный код

    Издатель навыка на GitHub — HimanshuJ16. Перед установкой изучите исходные материалы.

Установка

Установите навык ИИ Corporate Action Adjusted Backtesting в TypingMind, чтобы использовать его с любой LLM, или добавьте его в другой агент, который умеет читать SKILL.md.

1

Установка в TypingMind

TypingMind устанавливает навык прямо из его папки на GitHub: читает SKILL.md, собирает файлы ресурсов и сохраняет результат локально.

  1. Откройте приложение и перейдите в раздел «Плагины → Навыки».
  2. Выберите «Установить из GitHub».
  3. Вставьте указанную ниже ссылку на папку навыка и подтвердите установку.
    https://github.com/HimanshuJ16/Algo-Trading-Skills/tree/main/skills/corporate-action-adjusted-backtesting
  4. Включите навык в каждом чате, где хотите его использовать.
Плагины → Навыки → Добавить навык → По ссылке GitHub, затем вставьте ссылку на папку и нажмите «Продолжить».
2

Установка в другом агенте

Любой агент с поддержкой формата Agent Skills может использовать этот навык — скопируйте папку в каталог навыков этого агента.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/HimanshuJ16/Algo-Trading-Skills.git /tmp/Algo-Trading-Skills
mkdir -p .claude/skills
cp -r /tmp/Algo-Trading-Skills/skills/corporate-action-adjusted-backtesting .claude/skills/corporate-action-adjusted-backtesting
После копирования перезапустите Claude Code, чтобы загрузить новый навык.

Использование в TypingMind

Включите навык Corporate Action Adjusted Backtesting в любом чате TypingMind, и дальше модель всё сделает сама. Его название и описание хранятся в системном промпте, а при появлении подходящего запроса модель сама загружает полные инструкции. Вам не нужно вызывать навык вручную, и до фактического использования он не расходует токены.

Модель сама загружает навык Corporate Action Adjusted Backtesting, как только появляется подходящий для него запрос.

Работает с любой моделью ИИ

Навыки ИИ — это обычные инструкции в Markdown, а не код для конкретного поставщика, поэтому навык Corporate Action Adjusted Backtesting не привязан к модели, для которой он был создан. Установите его один раз в TypingMind и используйте с GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama или локальной моделью, которую запускаете самостоятельно, — со своими ключами API.

  • Загружается только при необходимости

    Системный промпт содержит только название и описание. Инструкции загружаются при первом подходящем запросе, поэтому неиспользуемый навык не расходует токены.

  • Меняйте модели прямо в чате

    Навык состоит из инструкций, а не кода, поэтому смена модели не нарушает его работу: новая модель читает тот же файл SKILL.md.

Инструкции навыка

Это содержимое файла SKILL.md, которое загружает модель. Прочитайте его перед установкой: навык — это инструкции, которым будет следовать ваша модель.

When to Use

Use this skill when a backtest reads historical equity or ETF prices over a window that contains a stock split, reverse split, or cash dividend. Raw venue prices contain artificial gaps at every such event — a 4-for-1 split prints as a 75% overnight crash — so technical indicators computed on them (SMA crossovers, RSI, Bollinger bands, any return series) fire false signals. Adjusted prices fix the signal side and break the execution side: they are not the prices anyone traded at, so sizing orders or debiting cash from them corrupts the portfolio's share count and cash balance.

CorporateActionAdjuster resolves that by carrying both series on every bar. Each AdjustedBarData exposes the raw OHLCV as printed by the venue, plus an adjusted OHLCV and the two factors that produced it:

  • caf — the price factor. CAF_t = prod(alpha_E) over every event with ex-date E > t, anchored so the most recent bar has caf == 1.0.
  • volume_caf — the share-count factor, built from split events only.

When NOT to Use

  • You need a total-return series. Multiplying prices by 1 - D/P removes the ex-date price drop; it does not credit the cash. Dividend PnL must be credited separately, from the raw close and the position held on the ex-date. Using this module's adjusted prices as a return series and also crediting dividends double-counts them.
  • You are building a continuous futures series. Rolling contracts stitch on a ratio or difference basis at the roll date, not on a corporate action calendar. See synthetic-continuous-futures-contract-construction.
  • The event is a spin-off, merger, rights issue or return of capital. Only splits, reverse splits and ordinary cash dividends are modelled. A spin-off's factor depends on the when-issued value of the distributed security and must be supplied out of band.
  • You need the corporate action data itself. Ingestion, vendor parity and the declaration/ex/record/pay lifecycle belong to corporate-action-event-calendar-integration.
  • You are reconciling two vendors' already-adjusted series. Vendors differ on dividend treatment and rounding; see vendor-specific-adjustment-methodology-reconciliation.

Prerequisites

  • A corporate action log with, per event: ex-date (not the declaration, record or pay date), type, and value. value is the share multiplier for splits (2.0 for 2-for-1, 1.1 for a 10% stock dividend, 5.0 on a REVERSE_SPLIT for 1-for-5) and the per-share cash amount for dividends.
  • A raw, unadjusted OHLCV series. Feeding an already-adjusted vendor series in and adjusting it again applies every factor twice.
  • The bar preceding each dividend ex-date must be present in the series — that close is the factor's denominator.

Workflow

  1. Load raw bars and events. Both BarData and CorporateActionEvent validate on construction: non-finite or negative fields, non-date dates, unknown event types and non-positive split ratios raise CorporateActionError rather than being coerced. An unrecognised event_type is a hard failure by design — silently skipping it leaves the split gap sitting inside a series labelled "adjusted".
  2. Decide the vantage point. If the series feeds a point-in-time research loop, pass as_of=<simulation date>. Bars after it and events with a later ex-date are both excluded, reproducing the series as it stood that day. Omit as_of only for present-day analysis where the whole event history is legitimately known.
  3. Compute the factors with adjust_bars(bars, as_of=...):
    • Split, ratio R: alpha = 1/R. Reverse split, ratio R: alpha = R.
    • Cash dividend D: alpha = 1 - D / P_close(last bar strictly before ex-date). Not the ex-date close — that couples the factor to the day's market move.
    • Each alpha multiplies every bar with dt < ex_date. Events are keyed by date, not matched to a bar, so an ex-date on a holiday or halt still applies.
  4. Route the two series to the two consumers.
    • Signals, indicators, returns, correlations → adj_open/high/low/close.
    • Order quantity, cash debit/credit, commission, tick rounding, margin → raw_open/high/low/close.
    • ADV and liquidity screens → adj_volume, which is raw_volume / volume_caf and is therefore untouched by cash dividends.
  5. Credit dividend cash separately. On each dividend ex-date, cash += shares_held * D, taken from the event log and the raw position — never inferred from the adjusted price series.
  6. Handle the rejections. A CorporateActionError for a dividend at or above its reference close means either bad vendor data or a special/liquidating distribution that needs an explicitly supplied factor. Do not clamp it — investigate the event.

Full procedure: see references/workflows.md. Standards reference: see references/standards.md. Printable pre-flight checklist: see assets/checklist.md.

Common Pitfalls

  • Referencing the dividend to the ex-date close. The CRSP convention that Yahoo Finance and MATLAB's adjustedClosingPrices both implement divides by the last close preceding the ex-date. A $2 dividend on a stock that also fell from $100 to $90 that session yields 0.9778 under the wrong reference and 0.98 under the right one — and the error grows without bound as the ex-date close approaches zero.
  • Adjusting volume by the price factor. A cash dividend changes the price basis and leaves the share count alone. Folding it into the volume factor inflates historical share volume by the dividend yield, so every ADV-based liquidity or capacity check reads high on exactly the names that pay dividends. CRSP keeps these as two separate fields; so does this module.
  • Applying an event only when a bar matches its ex-date. Ex-dates land on exchange holidays, on halted sessions, before the start of a truncated series, and on days a vendor's calendar disagrees with yours. Matching event.ex_date == bar.dt drops those events without a word.
  • Look-ahead through the adjusted series. A fully adjusted modern series encodes every future split and dividend into today's price. A signal computed over it at simulated date T has seen events that had not been announced at T. Use as_of.
  • Executing at adjusted prices. Sizing an order off an adjusted price buys the wrong number of shares and debits the wrong cash; the discrepancy compounds silently across the backtest and only surfaces as an unexplained PnL gap against live.
  • Double-adjusting. Most retail data APIs return adjusted closes by default. Confirm which series you fetched before adjusting it again.
  • Pre-applying an announced-but-not-yet-ex event. An event with an ex-date after the last bar has not occurred within the sample; applying it rescales the whole series and breaks the caf == 1.0 anchor on the newest bar. This module ignores such events and logs the reason at DEBUG.

Verification

  • 2-for-1 split: ex-date 2025-01-03, raw close $100 → $50. Assert caf == 0.5 and adj_close == 50.0 on Days 1–2, caf == 1.0 on and after the ex-date, and adj_volume doubled before the ex-date.
  • Dividend reference price: $2.00 dividend ex-date 2025-01-02 with a $100 close on 01-01 and a $90 close on 01-02. Assert caf == 0.98, not 0.9778.
  • Volume/price separation: after that same dividend, assert volume_caf == 1.0 and adj_volume == raw_volume.
  • Point-in-time: with a split on 2025-01-03, adjust_bars(bars, as_of=date(2025,1,1)) must return one bar with caf == 1.0; the same call without as_of must return caf == 0.5 for that bar.
  • Anchor invariant: for any event set, the last bar's caf, volume_caf are 1.0 and adj_close == raw_close.
  • Run python -m unittest discover -s skills/corporate-action-adjusted-backtesting/scripts.

Related Skills

  • corporate-action-event-calendar-integration
  • adjusted-vs-unadjusted-price-series-pitfalls
  • vendor-specific-adjustment-methodology-reconciliation
  • lookahead-bias-elimination
  • point-in-time-fundamentals-data-joins
  • synthetic-continuous-futures-contract-construction

Файлы в комплекте

Модель читает эти файлы по мере необходимости, пока навык загружен. Они доступны только для чтения и никогда не выполняются.

Часто задаваемые вопросы

Что делает навык ИИ Corporate Action Adjusted Backtesting?

Используйте, когда дробление или обратное дробление акций либо денежный дивиденд создают искусственные разрывы в истории цен бэктеста и порождают ложные сигналы. Навык строит скорректированный задним числом ряд по правилам CRSP для генерации сигналов, отдельно учитывая денежные дивиденды.

Зачем использовать Corporate Action Adjusted Backtesting в TypingMind?

Потому что вы устанавливаете навык один раз и используете его с любой моделью. Corporate Action Adjusted Backtesting — это обычный текст в формате Markdown, а не код для конкретного поставщика, поэтому один и тот же навык работает с GPT-5, Claude, Gemini, Grok или локальной моделью. Вы можете менять модель прямо во время чата, и навык продолжит работать. TypingMind использует ваши собственные ключи API, поэтому вы платите поставщикам напрямую, а не оформляете подписку с оплатой за каждое место. Ваши навыки и чаты остаются в вашем собственном хранилище.

Как установить Corporate Action Adjusted Backtesting в TypingMind?

В TypingMind откройте «Плагины → Навыки → Установить из GitHub» и вставьте https://github.com/HimanshuJ16/Algo-Trading-Skills/tree/main/skills/corporate-action-adjusted-backtesting. TypingMind прочитает файл SKILL.md, включит сопутствующие файлы в пакет и установит навык, который можно включать отдельно для каждого чата.

Какие модели ИИ могут использовать Corporate Action Adjusted Backtesting?

Любая модель, которую вы подключите в TypingMind. Навыки ИИ — это обычные инструкции в формате Markdown, а не код для конкретного поставщика, поэтому GPT, Claude, Gemini, Grok и локальные модели могут загружать этот навык, когда запрос ему соответствует.

Со сколькими моделями ИИ можно использовать Corporate Action Adjusted Backtesting?

С любым количеством. В TypingMind вы можете использовать Corporate Action Adjusted Backtesting с любой моделью, которая поддерживает навыки, в том числе с GPT, Claude, Gemini, Grok, DeepSeek, Mistral и Llama. Для этого вы используете собственные ключи API.

Бесплатен ли навык ИИ Corporate Action Adjusted Backtesting?

Да. Навык опубликован на GitHub по лицензии Apache-2.0. Издатель — HimanshuJ16. Вы платите только своему поставщику ИИ за использованные токены.

Что такое навыки ИИ?

Навык ИИ — это набор инструкций, которыми модель ИИ может пользоваться каждый раз, когда ей нужно выполнить конкретную задачу. Он соответствует открытому формату Agent Skills: файл SKILL.md с названием и описанием, а также любые скрипты, шаблоны или справочные файлы, которые могут понадобиться модели. Модель читает инструкции, только когда ваш запрос соответствует навыку, поэтому установленный навык ничего не стоит, пока не используется.

Чем навыки ИИ отличаются от плагинов и серверов MCP?

Плагин или сервер MCP даёт модели новые инструменты, которые она может вызывать: при вызове где-то выполняется код и возвращает результат. Навык ИИ, напротив, даёт модели знания и описывает порядок действий: как подойти к задаче, какие шаги выполнить и каким должен быть хороший результат. Навыки — это обычный текст в формате Markdown, поэтому им не нужны сервер, ключ API или среда выполнения, и они работают с любой моделью.

Все
Логотип openclaw

Apple Reminders

openclaw
ОрганизацияПопулярный

Просматривайте, добавляйте, редактируйте, отмечайте как выполненные и удаляйте напоминания Apple Reminders и списки напоминаний с помощью remindctl.

82.2K
391K
Инструкции
Открыть
Логотип openclaw

Clawhub

openclaw
ОрганизацияПопулярный

Ищите навыки в ClawHub, если нужная возможность ещё недоступна; устанавливайте, проверяйте, обновляйте, удаляйте, публикуйте навыки и синхронизируйте их.

82.2K
391K
Инструкции
Открыть
Логотип obra

Diagnosing Superpowers

obra
СообществоПопулярный

Используйте этот навык, если сессия superpowers пошла не так и ваш партнёр-человек хочет понять почему: повторяющаяся работа, игнорирование планов, ошибки, плохие результаты, не сработавший навык, «это заняло слишком много времени», «почему это так…

26.3K
293.5K
Файлы: 19
Открыть
Логотип obra

Brainstorming

obra
СообществоПопулярный

ОБЯЗАТЕЛЬНО используйте этот навык перед любой творческой работой: созданием функций, разработкой компонентов, добавлением возможностей или изменением поведения. Перед реализацией он помогает разобраться в намерениях пользователя, требованиях и дизайне.

25.8K
288.1K
Файлы: 7
Открыть

Создайте своё рабочее пространство с ИИ прямо сейчас

Подпишитесь на нашу рассылку, чтобы узнавать о новых функциях и предстоящих розыгрышах 👇