🚀 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!
1# Clone the repository and install requirements
2git clone https://huggingface.co/tradecube/Plasmon-AI
3cd Plasmon-AI
4pip 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.
1# Generate the 156 features from your raw data
2python generate_features.py \
3 --input-dir ./path_to_your_raw_data \
4 --output-dir ./path_to_save_features \
5 --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:
1import pandas as pd
2import torch
3from transformer_model import TradingTransformer
4
5# 1️⃣ Load the processed features
6features_df = pd.read_parquet('./path_to_save_features/your_data_features.parquet')
7
8# 2️⃣ Extract the 156 features into a tensor (dropping non-feature columns like 'Date')
9feature_columns = [col for col in features_df.columns if col not in ['Date', 'Ticker', 'Symbol']]
10X_tensor = torch.tensor(features_df[feature_columns].values, dtype=torch.float32)
11
12# If your model expects [seq_len, batch_size, input_dim], add sequence/batch dimensions:
13# X_tensor = X_tensor.unsqueeze(1) # Example: adds a batch_size of 1 for sequence length n
14
15# 3️⃣ Initialize the Model Architecture
16model = TradingTransformer(
17 input_dim=156, # The number of features in your state space
18 d_model=768, # Hidden dimension
19 num_encoder_layers=12, # Depth of the Transformer
20 nhead=8 # Attention heads
21)
22
23# 4️⃣ Load the Pre-trained Weights
24checkpoint = torch.load("best_model.pt", map_location="cpu")
25
26# Handle standard state_dict or full checkpoint dicts seamlessly
27if isinstance(checkpoint, dict) and 'model_state_dict' in checkpoint:
28 model.load_state_dict(checkpoint['model_state_dict'])
29else:
30 model.load_state_dict(checkpoint)
31
32model.eval() # Set to evaluation mode! 🎯
33
34with torch.no_grad():
35 # ⚡ Run Inference!
36 mean_prediction, log_variance = model(X_tensor)
37
38 # Calculate uncertainty from the log variance
39 uncertainty = torch.exp(log_variance)
40
41 print(f"📈 Predicted Output: {mean_prediction[-1].item():.4f}")
42 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! 🌊
1# 🎲 Run 10 Monte Carlo iterations to measure AI confusion
2mean, aleatoric_unc, epistemic_unc = model.predict_with_uncertainty(obs, n_iter=10)
3
4print(f"🎯 Final Prediction: {mean[0].item():.4f}")
5print(f"📊 Market Noise (Aleatoric): {aleatoric_unc[0].item():.4f}")
6print(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:
1@misc{tradecube_2026,
2 author = { tradecube (Raviteja Chavata) },
3 title = { Plasmon-AI (Revision 8ca359f) },
4 year = 2026,
5 url = { https://huggingface.co/tradecube/Plasmon-AI },
6 doi = { 10.57967/hf/8113 },
7 publisher = { Hugging Face }
8}
9
📄 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.