๐Ÿš€ Indian Stock Trading - Transformer Model

Welcome to the world of quantitative analysis! ๐Ÿ“ˆ This is a Transformer-based AI Trading Model designed to predict market movements with built-in risk awareness.

Unlike traditional models that just guess a direction, this model is built for the real world: it tells you what might happen AND how confident it is. ๐ŸŽฏ


๐ŸŒŸ What Can This Model Do?

  • ๐Ÿ”ฎ Price Forecasting: Predicts future price means based on complex, multi-dimensional time-series data.
  • ๐ŸŽฒ Uncertainty Estimation: It outputs the variance alongside the mean, meaning you get direct insight into market volatility (Aleatoric Uncertainty).
  • ๐Ÿง  Self-Awareness (MC Dropout): By running multiple passive passes (Monte Carlo Dropout), you can measure if the model itself is confused by unseen market conditions (Epistemic Uncertainty).
  • ๐Ÿงฉ Pure PyTorch: No bloated frameworks, no hidden dependencies. It's a clean nn.Module that you can drop into any pipeline.

๐Ÿš€ Quick Start

โš™๏ธ Installation

All you need is standard PyTorch and a few data processing libraries to get started!

# Clone the repository and install requirements
git clone https://huggingface.co/tradecube/Plasmon-AI
cd Plasmon-AI
pip install torch numpy pandas scipy pyarrow

๐Ÿ“Š 1. Generate Required Features

First, use the companion feature generation script to process your raw OHLCV (Open, High, Low, Close, Volume) data. Your data should be in .parquet format.

# Generate the 156 features from your raw data
python generate_features.py \
    --input-dir ./path_to_your_raw_data \
    --output-dir ./path_to_save_features \
    --macro-dir ./path_to_macro_data  # Optional: defaults to ./data/macro

๐Ÿ› ๏ธ 2. Load and Use the Model

Once your features are generated, you can load the model and run predictions. Here is the basic trading loop to get your AI up and running:

import pandas as pd
import torch
from transformer_model import TradingTransformer

# 1๏ธโƒฃ Load the processed features
features_df = pd.read_parquet('./path_to_save_features/your_data_features.parquet')

# 2๏ธโƒฃ Extract the 156 features into a tensor (dropping non-feature columns like 'Date')
feature_columns = [col for col in features_df.columns if col not in ['Date', 'Ticker', 'Symbol']]
X_tensor = torch.tensor(features_df[feature_columns].values, dtype=torch.float32)

# If your model expects [seq_len, batch_size, input_dim], add sequence/batch dimensions:
# X_tensor = X_tensor.unsqueeze(1) # Example: adds a batch_size of 1 for sequence length n

# 3๏ธโƒฃ Initialize the Model Architecture
model = TradingTransformer(
    input_dim=156,         # The number of features in your state space
    d_model=768,           # Hidden dimension
    num_encoder_layers=12, # Depth of the Transformer
    nhead=8                # Attention heads
)

# 4๏ธโƒฃ Load the Pre-trained Weights
checkpoint = torch.load("best_model.pt", map_location="cpu")

# Handle standard state_dict or full checkpoint dicts seamlessly
if isinstance(checkpoint, dict) and 'model_state_dict' in checkpoint:
    model.load_state_dict(checkpoint['model_state_dict'])
else:
    model.load_state_dict(checkpoint)

model.eval() # Set to evaluation mode! ๐ŸŽฏ

with torch.no_grad():
    # โšก Run Inference!
    mean_prediction, log_variance = model(X_tensor)
    
    # Calculate uncertainty from the log variance
    uncertainty = torch.exp(log_variance)
    
    print(f"๐Ÿ“ˆ Predicted Output: {mean_prediction[-1].item():.4f}")
    print(f"๐Ÿ›ก๏ธ Uncertainty Score: {uncertainty[-1].item():.4f}")

๐ŸŽ“ Training Details & Data

The backbone of this model is the ultra-diverse, heavily augmented dataset it was trained on. I didn't just train on one stock; I trained on the most of the Indian market (data until 04 January 2026).

๐Ÿ“Š The Dataset

  • Equities: NIFTY 500 Stocks & Sectoral Indices.
  • Global Macro: S&P 500, FTSE 100, DAX, Nikkei 225 Indices.
  • Commodities & Forex: Gold, Silver, Crude Oil, and major INR pairs (USD, EUR, GBP, JPY).
  • Indicators: VIX, US 10Y Treasury Yields.
  • Timeframes: Daily candles (EOD data), 4hr, 1hr, 30min, 15min data (Intraday data).

โš™๏ธ Model Hyperparameters

  • Architecture: [transformer_model.py]
  • Parameters: ~125M
  • Hidden Dimension: 768
  • Transformer Layers: 12
  • Attention Heads: 8
  • Precision: Mixed Precision (FP16)

๐Ÿ“Š Performance Metrics (Backtest Results)

Tested against rigorous out-of-sample data, the model demonstrates the following performance on the daily timeframe:

  • ๐ŸŽฏ Directional Accuracy (Daily): 51.3%
  • ๐Ÿ“ˆ Sharpe Ratio: 1.8 - 1.9
  • ๐Ÿ† Win Rate: 56% - 57%
  • ๐Ÿ’ฐ Profit Factor: 1.6 - 1.65
  • ๐Ÿ›ก๏ธ Max Drawdown: < 20% (Historical backtests show 5-10% depending on the market regime)

(Note: These metrics do not utilize confidence filtering. Utilizing the model's Epistemic Uncertainty to filter low-confidence trades can boost directional accuracy on executed trades up to 75%+).


๐Ÿง  Advanced Usage: Uncertainty Estimation

Want to know if the AI has seen this exact market pattern before? Use the built-in Monte Carlo Dropout feature to get an Epistemic Uncertainty score! ๐ŸŒŠ

# ๐ŸŽฒ Run 10 Monte Carlo iterations to measure AI confusion
mean, aleatoric_unc, epistemic_unc = model.predict_with_uncertainty(obs, n_iter=10)

print(f"๐ŸŽฏ Final Prediction: {mean[0].item():.4f}")
print(f"๐Ÿ“Š Market Noise (Aleatoric): {aleatoric_unc[0].item():.4f}")
print(f"๐Ÿค” AI Confusion (Epistemic): {epistemic_unc[0].item():.4f}")

๐Ÿ“ Model Files

  • [transformer_model.py]: The clean, standalone PyTorch architecture.
  • best_model.pt: The trained weights ready for deployment.
  • [generate_features.py]: The converter of raw data & feature generator for model input.

โš ๏ธ Important Disclaimers

BEWARE OF TRADING RISKS. This model and its associated code are provided strictly for educational and research purposes only. Financial markets are highly volatile, and algorithmic trading involves a significant risk of monetary loss.

  • Do NOT use this model to make live financial decisions or trade real money.
  • The creator of this model assume absolutely no responsibility for any financial losses incurred from its use.

๐Ÿ“Š Citation

If you use this model in your research, experiments, or academic publications, you must cite it:

@misc{tradecube_2026,
    author       = { tradecube (Raviteja Chavata) },
    title        = { Plasmon-AI (Revision 8ca359f) },
    year         = 2026,
    url          = { https://huggingface.co/tradecube/Plasmon-AI },
    doi          = { 10.57967/hf/8113 },
    publisher    = { Hugging Face }
}

๐Ÿ“„ License & Usage

This model is licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0) license. It is designed to give you control over your intellectual property while allowing the community to learn from it.

  • โœ… You may: Download, study, and test the model in simulated, non-commercial environments for personal education or academic research.
  • โŒ You may not: Use this model for live commercial trading, sell the model, distribute modified derivatives, or integrate it into paid financial products without explicit written permission from the author.
  • ๐Ÿ”— Attribution: If you share results, analyses, or research derived from this model, you must provide proper citation and link back to this repository.

Acknowledgments

Heart felt thanks to @Google-cloud for their free cloud credits that made the model training possible and to my parents for many reasons.

Downloads last month

-

Downloads are not tracked for this model. How to track
Inference Providers NEW
This model isn't deployed by any Inference Provider. ๐Ÿ™‹ Ask for provider support