Logo de Backtest Outlier And Bad Tick Filtering

Backtest Outlier And Bad Tick Filtering

Comunidade
HimanshuJ16
backtest-outlier-and-bad-tick-filtering

Use ao importar arquivos brutos de ticks ou barras que contenham registros causados por erro de digitação, mensagens de teste, preços zerados e ticks fora de sequência, para que um registro incorreto não gere um sinal fantasma. Cada remoção também exclui um preço que poderia ter acionado legitimamente um stop.

Visão geral

Publicado porHimanshuJ16
RepositórioAlgo-Trading-Skills
Nome da habilidadebacktest-outlier-and-bad-tick-filtering
Estrelas
50
Forks
7
Arquivos incluídos
5
LicençaApache-2.0
Links
  • Instruções em Markdown

    Um arquivo SKILL.md que o modelo carrega sob demanda, consumindo tokens apenas quando uma solicitação é realmente relevante para a habilidade.

  • Funciona com qualquer LLM

    As habilidades de IA são escritas em Markdown simples, não em código específico de um provedor. Por isso, funcionam com GPT, Claude, Gemini, Grok ou um modelo local.

  • Arquivos incluídos: 5

    Scripts, templates e referências que o modelo pode ler enquanto trabalha. Os arquivos são somente para leitura e nunca são executados.

  • Código aberto

    Publicada por HimanshuJ16 no GitHub. Leia os arquivos da habilidade antes de instalá-la.

Instalação

Instale a habilidade de IA Backtest Outlier And Bad Tick Filtering no TypingMind para usá-la com qualquer LLM ou adicione-a a outro agente que leia SKILL.md.

1

Instalar no TypingMind

O TypingMind instala uma habilidade diretamente da pasta dela no GitHub — lê o arquivo SKILL.md, reúne os arquivos de recursos em um pacote e armazena o resultado localmente.

  1. Abra o app e vá para Plugins → Habilidades.
  2. Escolha "Instalar do GitHub".
  3. Cole a URL abaixo, que aponta para a pasta da habilidade, e confirme.
    https://github.com/HimanshuJ16/Algo-Trading-Skills/tree/main/skills/backtest-outlier-and-bad-tick-filtering
  4. Ative a habilidade em cada chat em que quiser disponibilizá-la.
Plugins → Habilidades → Adicionar habilidade → Via URL do GitHub. Depois, cole a URL da pasta e pressione Continuar.
2

Instalar em outro agente

Qualquer agente que leia o formato Agent Skills pode usar esta habilidade — copie a pasta para o diretório de habilidades desse agente.

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/backtest-outlier-and-bad-tick-filtering .claude/skills/backtest-outlier-and-bad-tick-filtering
Reinicie Claude Code após copiar para que a nova habilidade seja reconhecida.

Use no TypingMind

Ative Backtest Outlier And Bad Tick Filtering em qualquer chat do TypingMind e o modelo cuida do resto. O nome e a descrição da habilidade ficam no prompt do sistema e, assim que uma solicitação relevante aparece, o modelo carrega as instruções completas automaticamente — sem precisar de acionamento manual e sem consumir tokens até que ela seja realmente usada.

O modelo carrega Backtest Outlier And Bad Tick Filtering automaticamente assim que uma solicitação é relevante para essa habilidade.

Funciona com qualquer modelo de IA

Habilidades de IA são instruções em Markdown simples, não código específico de um provedor. Por isso, Backtest Outlier And Bad Tick Filtering não fica vinculada ao modelo para o qual foi criada. Instale-a uma vez no TypingMind e use-a com GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama ou um modelo local executado por conta própria — tudo com suas próprias chaves de API.

  • Carregada apenas quando necessário

    O prompt do sistema contém apenas o nome e a descrição. As instruções são buscadas na primeira solicitação relevante, então uma habilidade sem uso não gera custo.

  • Troque de modelo durante a conversa

    Como a habilidade é composta de instruções, não de código, trocar de modelo não afeta seu funcionamento — o próximo modelo lê o mesmo arquivo SKILL.md.

Instruções da habilidade

Este é o conteúdo de SKILL.md que o modelo carrega. Leia antes de instalar — uma habilidade é um conjunto de instruções que seu modelo seguirá.

When to Use

Invoke this skill during data ingestion prior to backtesting. Raw exchange tick files frequently contain anomalous data points: fat-finger bad prints ($10.00$ on a $100.00$ stock), test messages, corrupt quotes during opening auction, or zero-price trades. If unfiltered, a single erroneous low print can trigger a false $+900%$ momentum signal or hit a stop loss in backtest simulation that could never occur in reality.

When NOT to Use

  • Not for stop-loss, liquidation, or margin-call realism. Every purge deletes a price the backtest will never see. If a print was genuinely executable, removing it means your simulated stop never fires — the mirror image of the bias this skill exists to prevent. Filter the signal series, keep the raw series for execution modelling.
  • Not a substitute for the venue's own erroneous-trade record. Exchanges break clearly erroneous trades and publish the list. Where that record exists it is authoritative; a statistical filter is a fallback for data you cannot reconcile.
  • Not for detecting stale or out-of-sequence ticks. Despite the description's wording, this implementation reads prices only. It has no timestamps, so it cannot detect a repeated stale quote, a sequence gap, or an out-of-order print. Use sequence-number-gap-detection-for-feeds and clock-skew-correction-for-tick-timestamps.
  • Not for low-frequency bar series. A rolling window of 21 daily bars spans a month; the median will not track a trend, and legitimate moves get flagged. This is a tick and high-frequency-bar tool.
  • Not a returns-based test. It measures deviation from a rolling level, so a fast directional move drifts away from the trailing median and produces a low but non-zero false-positive rate. Measure that rate on a known-clean segment before trusting the settings.

Prerequisites

  • Raw price time series (ticks or high-frequency bars), chronologically ordered.
  • Rolling window size $W$ (e.g., 21 ticks) and outlier threshold $Z_{\text{max}}$ (e.g., 5.0 MAD deviations).
  • The instrument's minimum price variation (tick size), for the min_deviation floor.
  • Any array parallel to the prices — timestamps, volumes, venue codes — that must be realigned after filtering using report.kept_indices.

Workflow

  1. Compute Rolling Median & Median Absolute Deviation (MAD) over a strictly trailing window of already-accepted prices, so the decision for tick $i$ never reads tick $i+1$: $$\text{MAD} = \text{median}(|P_i - \text{median}(P)|)$$

  2. Evaluate Modified Z-Score (Iglewicz–Hoaglin, per NIST §1.3.5.17): $$Z_i = \frac{0.6745 \cdot |P_i - \text{median}(P)|}{\text{MAD}}$$

  3. Filter Outliers: Purge non-positive prices, non-finite prices, single-tick jumps beyond $\Delta_{\text{max}}%$, and prices where $Z_i > Z_{\text{max}}$. The test is applied in price units with an additive floor, $|P_i - \text{median}| > Z_{\text{max}} \cdot \text{MAD}/0.6745 + \gamma$, following Brownlees & Gallo (2006). Set $\gamma$ (min_deviation) to the tick size — at $\gamma = 0$ the MAD test is skipped entirely whenever MAD is zero, which is every flat window, and report.mad_test_skipped_count tells you how often that happened.

  4. Decide Whether a Run of Outliers Is a Level Shift: After max_consecutive_drops consecutive flags, the run is reinterpreted as a genuine gap (split, news, halt reopen) rather than bad prints. The prints purged on the way in are then restored, because the evidence says they were real, and the MAD window restarts at the new level. Set restore_ticks_on_regime_change=False for a strictly causal pass matching a live streaming filter — at the cost of permanently losing the ticks at each shift.

  5. Generate Data Cleanliness Report: Report total raw ticks, bad ticks purged, and percent dataset sanitized. Realign every parallel array with report.kept_indices before using the cleaned series.

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

Common Pitfalls

  • Using Mean/StdDev Instead of Median/MAD: Outliers heavily distort mean and standard deviation, masking subsequent bad prints.
  • Over-filtering Real Volatility Spikes: Setting $Z_{\text{max}}$ too low (e.g. 2.0) and truncating genuine flash crash price moves.
  • NaN Passing Every Test: Every comparison against NaN is False, so an unguarded filter accepts it, and one NaN then corrupts every subsequent median. Non-finite values must be rejected explicitly, before any comparison.
  • Trusting a Flat Window: When more than half a window shares one value, MAD is exactly zero and the modified Z-score is undefined. Skipping the test there silently leaves quiet stretches unscreened; dividing anyway raises ZeroDivisionError. Use the $\gamma$ floor.
  • A Bad First Print Anchoring the File: A trailing filter has no history before the first tick, so an erroneous opening print is accepted and becomes the reference for the jump test. Validate the first $W$ ticks against an external reference, or discard the warm-up.
  • Deleting Real Data at Every Genuine Gap: A naive consecutive-drop rule purges the leading ticks of every split or news gap. Worse, if the rolling window is not restarted at the new level it stays contaminated for $W$ more ticks and keeps re-flagging good prints — measured at 22 real ticks lost from a single level shift before this was fixed.
  • Losing Timestamp Alignment: The function returns bare prices. Reusing the original timestamp array against the cleaned series silently shifts every observation. Use kept_indices.
  • Treating 20% as a Standard: It is this implementation's default, not a published threshold. For US OTC equity securities FINRA's clearly-erroneous guidelines run from 20% (sub-$1) down to 3% ($1,000+), and LULD bands for NMS stocks above $3.00 are 5% (Tier 1) or 10% (Tier 2). A flat 20% is far too loose for a liquid equity. See references/standards.md.

Verification

  • Inject bad tick ($P=10.0$ into $100.0$ series), verify bad tick detection and removal.
  • Inject float("nan") and float("inf") and assert neither appears in the cleaned series.
  • Feed a permanent level shift and assert no genuine tick is lost and exactly one regime change is reported.
  • Assert the hand-computed MAD boundary: window $[10,11,12,13,14]$ has median $12$ and MAD $1$, so with $Z_{\text{max}}=5$ the limit is $5/0.6745 = 7.4129$; $19.42$ must be purged and $19.41$ kept.
  • Run the filter over a segment known to be clean and confirm the purge rate is acceptably low.
  • Run python -m unittest discover -s skills/backtest-outlier-and-bad-tick-filtering/scripts and confirm 100% pass rate.

Related Skills

  • data-vendor-cross-validation-for-backtests
  • backtest-determinism-and-reproducibility
  • multi-source-price-reconciliation-tie-breaking
  • sequence-number-gap-detection-for-feeds

Arquivos incluídos

O modelo lê esses arquivos sob demanda enquanto a habilidade está carregada. Eles são disponibilizados para leitura e nunca são executados.

Perguntas frequentes

O que a habilidade de IA Backtest Outlier And Bad Tick Filtering faz?

Use ao importar arquivos brutos de ticks ou barras que contenham registros causados por erro de digitação, mensagens de teste, preços zerados e ticks fora de sequência, para que um registro incorreto não gere um sinal fantasma. Cada remoção também exclui um preço que poderia ter acionado legitimamente um stop.

Por que usar Backtest Outlier And Bad Tick Filtering no TypingMind?

Porque basta instalar uma vez para usar com qualquer modelo. A habilidade Backtest Outlier And Bad Tick Filtering é escrita em Markdown simples, e não em código específico de um provedor, então a mesma habilidade funciona com GPT-5, Claude, Gemini, Grok ou um modelo local — e é possível trocar de modelo no meio do chat sem que ela deixe de funcionar. No TypingMind, você usa suas próprias chaves de API e paga diretamente aos provedores, em vez de pagar uma assinatura por licença de usuário. Suas habilidades e chats permanecem no seu próprio armazenamento.

Como instalar Backtest Outlier And Bad Tick Filtering no TypingMind?

Abra Plugins → Habilidades → Instalar do GitHub no TypingMind e cole https://github.com/HimanshuJ16/Algo-Trading-Skills/tree/main/skills/backtest-outlier-and-bad-tick-filtering. O TypingMind lê o arquivo SKILL.md, reúne os arquivos da habilidade e a instala para que possa ser ativada em cada chat.

Quais modelos de IA podem usar Backtest Outlier And Bad Tick Filtering?

Qualquer modelo conectado no TypingMind. As habilidades de IA são instruções em Markdown simples, e não código específico de um provedor. Assim, GPT, Claude, Gemini, Grok e modelos locais podem carregar esta habilidade quando uma solicitação corresponder a ela.

Quantos modelos de IA posso usar com Backtest Outlier And Bad Tick Filtering?

Quantos quiser. Desde que o modelo ofereça suporte a habilidades, é possível usar Backtest Outlier And Bad Tick Filtering com ele — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama e outros — tudo no TypingMind com suas próprias chaves de API.

A habilidade de IA Backtest Outlier And Bad Tick Filtering é gratuita?

Sim. A habilidade é publicada no GitHub por HimanshuJ16 sob a licença Apache-2.0. O pagamento é feito apenas ao seu provedor de IA pelos tokens usados.

O que são habilidades de IA?

Uma habilidade de IA é um conjunto reutilizável de instruções que ensina um modelo de IA a realizar uma tarefa específica. Ela segue o formato aberto Agent Skills: um arquivo SKILL.md com nome e descrição, além de scripts, templates ou arquivos de referência de que o modelo possa precisar. O modelo lê as instruções apenas quando sua solicitação corresponde à habilidade, então uma habilidade instalada não gera custos até ser usada.

Qual é a diferença entre habilidades de IA e plugins ou servidores MCP?

Um plugin ou servidor MCP oferece ao modelo novas ferramentas que ele pode acionar — código que é executado em algum lugar e retorna um resultado. Já uma habilidade de IA dá ao modelo o conhecimento e as orientações de que ele precisa: como abordar uma tarefa, quais etapas seguir e como deve ser um bom resultado. As habilidades são escritas em Markdown simples, por isso não precisam de servidor, chave de API nem ambiente de execução, e funcionam com qualquer modelo.

Ver lista completa

Crie seu próprio espaço de trabalho com IA agora

Inscreva-se na nossa newsletter para receber avisos sobre novos recursos e futuros sorteios 👇