Class Imbalance Handling For Rare Signal Eventsのロゴ

Class Imbalance Handling For Rare Signal Events

コミュニティ
HimanshuJ16
class-imbalance-handling-for-rare-signal-events

取引停止やフラッシュクラッシュなど、あるクラスの割合が数パーセント未満となるまれな事象を予測する場合に使用します。コスト重み付けとアンダーサンプリングに加え、アンダーサンプリングに伴い必要となる確率の再較正を行います。

Add to TypingMind

概要

公開者HimanshuJ16
リポジトリAlgo-Trading-Skills
スキル名class-imbalance-handling-for-rare-signal-events
スター
50
フォーク
7
同梱ファイル
5
ライセンスApache-2.0
リンク
  • Markdown形式の指示

    モデルが必要に応じて読み込むSKILL.mdファイルです。関連するリクエストがあったときだけトークンを消費します。

  • どのLLMでも利用可能

    AIスキルはプロバイダー固有のコードではなく、通常のMarkdownなので、GPT、Claude、Gemini、Grok、ローカルモデルで利用できます。

  • 5個の同梱ファイル

    モデルが作業中に読み取れるスクリプト、テンプレート、参考資料です。ファイルは読み取り専用で、実行されることはありません。

  • オープンソース

    HimanshuJ16がGitHubで公開しています。インストールする前にソースを確認してください。

インストール

AIスキル「Class Imbalance Handling For Rare Signal Events」をTypingMindにインストールすれば、どのLLMでも利用できます。SKILL.mdを読み取れる別のAIエージェントに追加することもできます。

1

TypingMindにインストール

TypingMindはGitHubフォルダから直接スキルをインストールします。SKILL.mdを読み取り、リソースファイルをまとめてローカルに保存します。

  1. アプリを開き、「プラグイン」→「スキル」に移動します。
  2. 「GitHubからインストール」を選択します。
  3. 以下のスキルフォルダのURLを貼り付けて確定します。
    https://github.com/HimanshuJ16/Algo-Trading-Skills/tree/main/skills/class-imbalance-handling-for-rare-signal-events
  4. スキルを利用したいチャットごとに、そのスキルを有効にしてください。
「プラグイン」→「スキル」→「スキルを追加」→「GitHubのURLから」を選択し、フォルダのURLを貼り付けて「続行」を押します。
2

別のAIエージェントにインストール

Agent Skills形式を読み取れるAIエージェントなら、このスキルを利用できます。フォルダをそのAIエージェントのスキルディレクトリにコピーしてください。

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/class-imbalance-handling-for-rare-signal-events .claude/skills/class-imbalance-handling-for-rare-signal-events
コピー後、新しいスキルを読み込むためにClaude Codeを再起動してください。

TypingMindで使用

TypingMindのチャットでClass Imbalance Handling For Rare Signal Eventsを有効にするだけで、あとはモデルが対応します。名前と説明がシステムプロンプトに含まれ、関連するリクエストがあると、モデルが指示の全文を自動で読み込みます。手動で呼び出す必要はなく、実際に使用されるまでトークンを消費しません。

関連するリクエストがあるとすぐに、モデルが自動的にClass Imbalance Handling For Rare Signal Eventsを読み込みます。

どのAIモデルでも利用可能

AIスキルはプロバイダー固有のコードではなく、通常のMarkdownで書かれた指示です。そのため、Class Imbalance Handling For Rare Signal Eventsは作成時に想定されたモデルに縛られません。TypingMindに一度インストールすれば、ご自身のAPIキーを使って、GPT-5、Claude、Gemini、Grok、DeepSeek、Mistral、Llama、またはご自身で実行するローカルモデルで利用できます。

  • 必要なときだけ読み込み

    システムプロンプトには名前と説明だけが含まれます。関連するリクエストが初めてあったときに指示を取得するため、スキルを使わない間は指示の読み込みにトークンを消費しません。

  • チャットの途中でモデルを切り替え

    スキルはコードではなく指示なので、モデルを切り替えてもそのまま使えます。次のモデルも同じSKILL.mdを読み込みます。

スキルの指示

モデルが読み込むSKILL.mdの内容です。スキルはモデルが従う指示なので、インストールする前に確認してください。

When to Use

Use this skill when building quantitative models to predict highly asymmetric, rare events (e.g., flash crashes, limit-up/limit-down halts, or rare alpha signals). Financial datasets for rare events are often 99% noise and 1% signal. Standard models trained on this data will optimize for "Accuracy" by predicting 0 (noise) every time, completely ignoring the signal. This utility enforces class balancing to force the model to learn the minority class.

When NOT to Use

  • The classes are only mildly imbalanced (say, better than 1:4). Reweighting and undersampling both distort the class prior; below a real imbalance problem they cost calibration and buy nothing.
  • The model's probability output feeds expected-value sizing and you will not recalibrate. Both weighting and undersampling shift predicted probabilities away from the true event rate. If you cannot apply correct_undersampling_bias (or an equivalent calibration step), leave the prior alone and move the decision threshold instead.
  • The minority class is small in absolute terms, not just in proportion. With a few dozen positive examples, rebalancing amplifies noise; the constraint is sample count, not class ratio.
  • You are balancing a validation or test split. Out-of-sample data must retain the market's real event rate — see Common Pitfalls.

Prerequisites

  • A binary or multi-class integer target array (y) representing the rare event. compute_class_weights handles multi-class; random_undersample and compute_scale_pos_weight are binary-only.
  • A feature matrix (X) whose rows align with y along the first axis.
  • NumPy >= 1.21 (repository requirements.txt); no scikit-learn or imbalanced-learn dependency is required by the helper itself.

Workflow

  1. Evaluation Setup: Before attempting to balance the data, set validation metrics to Precision-Recall AUC (PR-AUC) or F1-Score. ROC-AUC and Accuracy are misleading under heavy imbalance because the large true-negative count keeps the false-positive rate small even when precision is poor.
  2. Split First, Balance Second: Perform the time-aware train/validation split before touching the class distribution. Balancing is a training-set-only transformation.
  3. Cost-Sensitive Learning (Recommended): This approach discards no data. Match the helper to the estimator's parameter shape:
    • scikit-learn estimators taking a class_weight mapping (e.g. RandomForestClassifier, LogisticRegression): pass ImbalanceHandler.compute_class_weights(y_train).
    • Gradient-boosting libraries taking the scalar scale_pos_weight (XGBoost, LightGBM): pass ImbalanceHandler.compute_scale_pos_weight(y_train). This is negatives / positives, a different quantity from the weight dict — the two are not interchangeable.
  4. Undersampling (Alternative): If the dataset is too large to train on, use ImbalanceHandler.random_undersample(X_train, y_train, majority_ratio=...) to reduce the majority class to a chosen multiple of the minority count (1.0 = parity). Record beta = kept_majority / original_majority from the log line — step 5 needs it.
  5. Recalibrate Probabilities Before Trading On Them: A model trained on undersampled data reports probabilities inflated towards the minority class. Pass predict_proba output through ImbalanceHandler.correct_undersampling_bias(p, beta) before it drives position sizing, expected value, or any absolute probability threshold. Ranking metrics (PR-AUC, ROC-AUC) are unaffected by the correction; monetary decisions are not.
  6. Score on the Untouched Split: Predict on the unmodified validation set, which still carries the market's real event rate, and evaluate with Precision, Recall, F1, and the confusion matrix.

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

Common Pitfalls

  • Data Leakage via Resampling Validation: Applying SMOTE or Undersampling to the entire dataset before doing a train-test split. This severely biases validation results because the validation set is no longer representative of the true market distribution.
  • Using Accuracy as a Metric: A model predicting "No Crash" every day achieves 99.9% accuracy but is completely useless for trading.
  • Overusing Oversampling (SMOTE) in Finance: Financial data is incredibly noisy. Generating synthetic financial samples via interpolation (SMOTE) often creates unrealistic market states that confuse the model.
  • Confusing the Weight Dict With scale_pos_weight: compute_class_weights returns {label: weight} for scikit-learn's class_weight; XGBoost's scale_pos_weight is a single scalar (negatives / positives). Passing the dict where a scalar is expected fails loudly; passing the minority weight n / (2 * minority_count) as a scale_pos_weight fails silently with a different, incorrect amount of upweighting.
  • Trading On Uncalibrated Post-Balancing Probabilities: After 1:1 undersampling of a 1% event, a model that has learned nothing beyond the base rate outputs ~0.5. Treating that as "50% chance of a crash" oversizes positions by two orders of magnitude. Correct for the retention rate before any probability is spent as money.
  • Reseeding the Global RNG: A resampling helper that calls np.random.seed() silently reseeds the caller's process-wide generator, making later splits, model initialisation, and Monte Carlo runs deterministic functions of the resampler's seed. random_undersample uses a local np.random.default_rng for this reason.
  • Balancing Across the Purge/Embargo Boundary: Undersampling picks majority rows at random, so it does not remove overlapping-label leakage. Purge and embargo first, then balance what survives.

Verification

  • Generate an imbalanced dataset (99% class 0, 1% class 1). compute_class_weights must return {0: n/(2*990...), 1: n/(2*10...)} with the class-1 weight ~99x the class-0 weight, and the per-sample weights must sum back to n_samples. compute_scale_pos_weight must return 99.0 for the same array.
  • Run random_undersample and verify a 50/50 distribution, that returned rows stay in the original chronological order, and that np.random.get_state() is unchanged afterwards.
  • Feed an already-balanced array (equal class counts) to random_undersample and verify both classes survive intact.
  • correct_undersampling_bias(0.5, beta) with beta = minority/majority must return the original event rate.
  • Run python -m unittest discover -s skills/class-imbalance-handling-for-rare-signal-events/scripts (33 tests), or python tools/run_all_tests.py for the full repository suite.

Related Skills

  • walk-forward-optimization-window-management
  • cross-sectional-vs-time-series-model-design
  • sample-weighting-for-overlapping-labels
  • label-noise-estimation-in-financial-targets

同梱ファイル

スキルが読み込まれている間、モデルは必要に応じてこれらを読み取ります。読み取り可能なファイルとして提供され、実行されることはありません。

よくある質問

AIスキル「Class Imbalance Handling For Rare Signal Events」では何ができますか?

取引停止やフラッシュクラッシュなど、あるクラスの割合が数パーセント未満となるまれな事象を予測する場合に使用します。コスト重み付けとアンダーサンプリングに加え、アンダーサンプリングに伴い必要となる確率の再較正を行います。

TypingMindでClass Imbalance Handling For Rare Signal Eventsを使うメリットは何ですか?

一度インストールすれば、どのモデルでも使えるからです。Class Imbalance Handling For Rare Signal Eventsはプロバイダー固有のコードではなく、通常のMarkdownで記述されているため、同じスキルをGPT-5、Claude、Gemini、Grok、ローカルモデルで利用できます。チャットの途中でモデルを切り替えても、そのまま使い続けられます。TypingMindは自分のAPIキーで動作するため、シート単位のサブスクリプションではなく、プロバイダーに直接料金を支払います。スキルとチャットは自分のストレージに保持されます。

TypingMindにClass Imbalance Handling For Rare Signal Eventsをインストールするにはどうすればよいですか?

TypingMindで「プラグイン」→「スキル」→「GitHubからインストール」を開き、https://github.com/HimanshuJ16/Algo-Trading-Skills/tree/main/skills/class-imbalance-handling-for-rare-signal-eventsを貼り付けてください。TypingMindがSKILL.mdを読み込み、関連ファイルをまとめて、チャットごとに有効にできるスキルとしてインストールします。

Class Imbalance Handling For Rare Signal Eventsを使えるAIモデルはどれですか?

TypingMindに接続したどのモデルでも利用できます。AIスキルはプロバイダー固有のコードではなく、通常のMarkdownで書かれた指示です。そのため、GPT、Claude、Gemini、Grok、ローカルモデルのいずれも、リクエストの内容がこのスキルの用途に合ったときに、このスキルを読み込めます。

Class Imbalance Handling For Rare Signal Eventsで使えるAIモデルの数に制限はありますか?

数に制限はありません。スキルに対応したモデルであれば、GPT、Claude、Gemini、Grok、DeepSeek、Mistral、Llamaなど、どのモデルでもClass Imbalance Handling For Rare Signal Eventsを利用できます。すべてTypingMind上で、自分のAPIキーを使って利用できます。

AIスキル「Class Imbalance Handling For Rare Signal Events」は無料ですか?

はい。HimanshuJ16がApache-2.0ライセンスのもとでGitHubに公開しています。ご利用のAIプロバイダーに支払うのは、使用したトークンの料金だけです。

AIスキルとは何ですか?

AIスキルは、特定のタスクの実行方法をAIモデルに教える、再利用可能な指示のセットです。オープンなAgent Skills形式に従い、名前と説明を含むSKILL.mdファイルに加え、モデルが必要とするスクリプト、テンプレート、参照ファイルで構成されます。モデルはリクエストがスキルに合致したときだけ指示を読み込むため、インストール済みのスキルも、使うまでは費用がかかりません。

AIスキルは、プラグインやMCPサーバーとどう違いますか?

プラグインやMCPサーバーは、モデルが呼び出せる新しいツールを提供します。ツールとは、どこかで実行され、結果を返すコードです。一方、AIスキルは、タスクへの取り組み方、従うべき手順、望ましい出力の例といった知識や進め方をモデルに伝えます。スキルは通常のMarkdownで記述されているため、サーバー、APIキー、実行環境は不要で、どのモデルでも利用できます。

すべて見る

今すぐ自分専用のAIワークスペースを作成

ニュースレターに登録すると、新機能や今後のプレゼント企画のお知らせが届きます👇