Logotipo de Class Imbalance Handling For Rare Signal Events

Class Imbalance Handling For Rare Signal Events

Comunidad
HimanshuJ16
class-imbalance-handling-for-rare-signal-events

Úsalo para predecir sucesos poco frecuentes, como suspensiones de cotización o caídas repentinas, cuando una clase represente menos de unos pocos puntos porcentuales. Incluye ponderación sensible al coste y submuestreo, con el recalibrado de probabilidades que este último hace necesario.

Add to TypingMind

Descripción general

EditorHimanshuJ16
RepositorioAlgo-Trading-Skills
Nombre de la habilidadclass-imbalance-handling-for-rare-signal-events
Estrellas
50
Forks
7
Archivos incluidos
5
LicenciaApache-2.0
Enlaces
  • Instrucciones en Markdown

    Un archivo SKILL.md que el modelo carga cuando lo necesita, de modo que solo consume tokens cuando la petición encaja con la habilidad.

  • Funciona con cualquier LLM

    Las habilidades de IA están en Markdown, no en código específico de un proveedor, por lo que funcionan con GPT, Claude, Gemini, Grok o un modelo local.

  • Archivos incluidos: 5

    Scripts, plantillas y referencias que el modelo puede leer mientras trabaja. Los archivos son de solo lectura y nunca se ejecutan.

  • Código abierto

    Publicada por HimanshuJ16 en GitHub. Revisa el contenido original antes de instalarla.

Instalación

Instala la habilidad de IA Class Imbalance Handling For Rare Signal Events en TypingMind para usarla con cualquier LLM, o añádela a otro agente que lea SKILL.md.

1

Instalar en TypingMind

TypingMind instala una habilidad directamente desde su carpeta de GitHub: lee SKILL.md, empaqueta los archivos de recursos y guarda el resultado localmente.

  1. Abre la aplicación y ve a Plugins → Habilidades.
  2. Elige «Instalar desde GitHub».
  3. Pega la URL de la carpeta de la habilidad que se muestra a continuación y confirma.
    https://github.com/HimanshuJ16/Algo-Trading-Skills/tree/main/skills/class-imbalance-handling-for-rare-signal-events
  4. Activa la habilidad en cada chat en el que quieras tenerla disponible.
Plugins → Habilidades → Añadir habilidad → URL de GitHub; después, pega la URL de la carpeta y pulsa Continuar.
2

Instalar en otro agente

Cualquier agente que lea el formato Agent Skills puede usar esta habilidad: copia la carpeta en el directorio de habilidades de ese 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/class-imbalance-handling-for-rare-signal-events .claude/skills/class-imbalance-handling-for-rare-signal-events
Reinicia Claude Code después de copiarla para que detecte la nueva habilidad.

Úsala en TypingMind

Activa Class Imbalance Handling For Rare Signal Events en cualquier chat de TypingMind y el modelo se encargará del resto. Su nombre y descripción se incluyen en el prompt del sistema y, en cuanto una petición encaja con la habilidad, el modelo carga las instrucciones completas por sí solo. No tienes que invocarla manualmente y no consume tokens hasta que se utiliza.

El modelo carga Class Imbalance Handling For Rare Signal Events automáticamente en cuanto una petición es relevante para esa habilidad.

Funciona con cualquier modelo de IA

Las habilidades de IA son instrucciones en Markdown, no código específico de un proveedor, por lo que Class Imbalance Handling For Rare Signal Events no está vinculada al modelo para el que se creó. Instálala una sola vez en TypingMind y úsala con GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama o un modelo local que ejecutes tú, todo con tus propias claves API.

  • Se carga solo cuando se necesita

    El prompt del sistema solo incluye el nombre y la descripción. Las instrucciones se cargan con la primera petición que encaja con la habilidad, por lo que una habilidad que no se usa no supone ningún coste.

  • Cambia de modelo durante el chat

    Como la habilidad contiene instrucciones y no código, cambiar de modelo no impide que funcione: el nuevo modelo lee el mismo archivo SKILL.md.

Instrucciones de la habilidad

Este es el contenido de SKILL.md que carga el modelo. Léelo antes de instalar la habilidad: contiene instrucciones que tu modelo seguirá.

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

Archivos incluidos

El modelo los lee según los necesita mientras la habilidad está cargada. Son archivos de solo lectura y nunca se ejecutan.

Preguntas frecuentes

¿Qué hace la habilidad de IA Class Imbalance Handling For Rare Signal Events?

Úsalo para predecir sucesos poco frecuentes, como suspensiones de cotización o caídas repentinas, cuando una clase represente menos de unos pocos puntos porcentuales. Incluye ponderación sensible al coste y submuestreo, con el recalibrado de probabilidades que este último hace necesario.

¿Por qué usar Class Imbalance Handling For Rare Signal Events en TypingMind?

Porque la instalas una vez y la usas con cualquier modelo. Class Imbalance Handling For Rare Signal Events está escrita en Markdown, no en código específico de un proveedor, por lo que la misma habilidad funciona con GPT-5, Claude, Gemini, Grok o un modelo local, y puedes cambiar de modelo en mitad del chat sin que deje de funcionar. TypingMind utiliza tus propias claves API, de modo que pagas directamente a los proveedores en lugar de pagar una suscripción por puesto, y tus habilidades y chats permanecen en tu propio almacenamiento.

¿Cómo instalo Class Imbalance Handling For Rare Signal Events en TypingMind?

Abre Plugins → Habilidades → Instalar desde GitHub en TypingMind y pega https://github.com/HimanshuJ16/Algo-Trading-Skills/tree/main/skills/class-imbalance-handling-for-rare-signal-events. TypingMind lee el archivo SKILL.md de esa carpeta, empaqueta los archivos de la carpeta e instala el conjunto como una habilidad que puedes activar en cada chat.

¿Qué modelos de IA pueden usar Class Imbalance Handling For Rare Signal Events?

Cualquier modelo que conectes en TypingMind. Las habilidades de IA son instrucciones en Markdown, no código específico de un proveedor, por lo que GPT, Claude, Gemini, Grok y los modelos locales pueden cargar esta habilidad cuando una solicitud se corresponda con ella.

¿Con cuántos modelos de IA puedo usar Class Imbalance Handling For Rare Signal Events?

Con tantos como quieras. Siempre que un modelo admita habilidades, puedes usar Class Imbalance Handling For Rare Signal Events con él: GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama y muchos más, todos en TypingMind con tus propias claves API.

¿Es gratuita la habilidad de IA Class Imbalance Handling For Rare Signal Events?

Sí. HimanshuJ16 la ha publicado en GitHub bajo la licencia Apache-2.0. Solo pagas a tu proveedor de IA por los tokens que utilizas.

¿Qué son las habilidades de IA?

Una habilidad de IA es un conjunto de instrucciones reutilizables que enseña a un modelo de IA a realizar una tarea concreta. Sigue el formato abierto Agent Skills: un archivo SKILL.md con un nombre y una descripción, además de los scripts, plantillas o archivos de referencia que pueda necesitar el modelo. El modelo solo lee las instrucciones cuando tu solicitud se corresponde con la habilidad, por lo que una habilidad instalada no supone ningún coste hasta que se utiliza.

¿En qué se diferencian las habilidades de IA de los plugins o los servidores MCP?

Un plugin o un servidor MCP proporciona al modelo nuevas herramientas que puede invocar: código que se ejecuta en algún lugar y devuelve un resultado. En cambio, una habilidad de IA aporta conocimientos y procedimientos al modelo: cómo abordar una tarea, qué pasos seguir y qué se considera un buen resultado. Las habilidades son instrucciones en Markdown, por lo que no necesitan servidor, clave API ni entorno de ejecución, y funcionan con cualquier modelo.

Ver el directorio

Crea ya tu propio espacio de trabajo con IA

Suscríbete a nuestro boletín para recibir avisos sobre nuevas funciones y próximos sorteos 👇