What I learned building "StockMind" and the maths that powers it. You can use it

Hey everyone,

A few days ago, I shared a post about building StockMind—a cash swing trading engine I coded to escape the F&O trap.

Over more than 200 people of you registered to check it out, and the feedback was a massive reality check. Here is a crisp retrospective on what this project has taught me about math, code, and transaction friction. May be you can incorporate it in your investing journey.

  1. The "Complexity Trap" in Machine Learning

As an ML engineer, my instinct was to throw complex deep learning models (like LSTMs) at price data. It failed. Stock prices are highly non-stationary; deep models just memorize historical noise (overfit) and blow up live.

I threw out the neural networks and went back to four simpler mathematical rules that actually work (At least it worked for me till now):

  • Relative Strength (RS) Sector Rotation: Ranks sector indices against the Nifty 50 in last 2 months . We block all buy signals in the bottom 30% weak sectors.
  • Quality + Momentum Filter:
    • Quality: Filter out high debt (Debt/Equity < 1.5) and target efficiency (ROE > 15%).
    • Momentum: Only enter if the asset is in a macro uptrend (Price > 150-day SMA).
  • Cointegration & Stationarity (For Mean-Reversion):
    • Math: Regresses the change in price spread between two assets against lagged values (ADF test). If p-value<0.05, we reject the unit root (non-stationarity) and trade the mean-reversion using Z-scores.
  • NLP / Event Risk Filtering:
    • Usage: Parses sentiment on the 5 most recent corporate news headlines. If the score falls below -0.3 (signaling lawsuits, fines, or bad earnings), the signal is blocked to avoid sudden gap-downs.

2. The "Friction Shock" is Real

Backtests assume you buy and sell at the exact closing price for free.

  • The Reality: The second you add a flat 0.25% cost per trade (brokerage, GST, STT, and slippage), high-frequency strategies die.
  • The Lesson: Keep holding periods longer (30+ days) to survive transaction costs.

3. Why I Kept 3 Different Strategies

No single strategy wins in every market regime. We run three to balance the portfolio:

  • Pure-Momentum: Captures big breakouts in strong trending bull markets.
  • Quality-DipBuy: Buys strong balance-sheet stocks at temporary discounts during market corrections.
  • Unified-PM-QV: Blends both to smooth out the overall drawdown curve.

4. The Automation Illusion (Zerodha API Chores)

We want to write a cron job and let it run forever. But because Zerodha doesn't support free headless logins, I still have to manually log in to Kite every morning to generate the session token. It's a 30-second reminder that "fully automated" systems usually have a manual starting key. I can automate it but the process would require me to share my credentials inside the script which I don't want.

5. Honesty is a Superpower

I was terrified of sharing this because the win rate is only ~46% and the CAGR isn't 200%. Also it's the first time I was sharing one of the project in public. But people are tired of get-rich-quick scams. The raw stats brought in 150+ folks who visited the website and immediately pointed out math loopholes (like survivorship bias) that are helping me optimise the engine.

Status Update:

  • The dashboard is live on our new domain: https://www.thestockmind.com
  • Next Up: Working to extend the universe till Nifty 100. Analysing its pros and cons. Creating a dedicated community around StockMind where I would be sharing insights and updates. Feel free to join it.

Would love to hear from other builders—what was the biggest gap between your backtest and live execution?

reddit.com
u/WinterSpecial7970 — 18 hours ago

100+ signups in 12 hours ! Pushed some new changes to my app StockMind.

Hey everyone,

Blown away by the response to yesterday’s launch—100+ signups in the first 12 hours!

I just pushed v1.1 with performance updates and user-requested features. Here is what's new:

  • ⚡ Dynamic Caching (Instant Loads):
    • Market Hours: Prices cache for 2 minutes to keep dashboard numbers active.
    • Off-Market / Weekends: Cache extends to 12 hours to stop redundant API requests.
    • Result: Page loads are now instant (0ms price fetches from memory instead of API waits).
  • 💬 Direct Telegram-Notified Feedback:
    • Added a floating feedback button in the bottom-right.
    • Securely locks your email if you're logged in to prevent spam.
    • Submitting feedback instantly pings my phone via a Telegram bot so I can respond/patch bugs in real-time.

Still analysing whether to move from Nifty 50 to Nifty 100 because of below issues. As of now I am keeping the connection with Zerodha a manual process.

  1. API Limits: Doubling the stocks might trigger Zerodha rate limits (429 throttle errors). But can be managed.
  2. Calculation Bottlenecks: Pairs-trading calculations scale quadratically, jumping from 1,225 combinations to 4,950, causing server timeouts.
  3. Friction & Drawdown: Mid-caps introduce wider bid-ask spreads (slippage) and much steeper drawdowns during market corrections.

Check it out:

Drop your thoughts below or hit the feedback button on the site! 🚀

reddit.com
u/WinterSpecial7970 — 1 day ago
▲ 92 r/IndiaAlgoTrading+1 crossposts

I’m an ML Engineer. I got tired of "AI Trading Bot" scams, so I coded my own Cash Swing Trading Engine in public. (No advice, just math)

Hey everyone,

Reuploading it since the previous post was taken down by bot. Honestly I am pretty new to this platform (old school) , I would request moderator to give chance before removing it. Looks like putting telegram link caused the post to get deleted.

Anyway I got lot of messages due to previous post, and most people where curious to see did I started trading with real money. And yes I did. I started putting my real money since last 2 months. Attaching the p&l statement. Some unrealized profits are mainly from previous investment which I did way back. But in short I was able to get decent returns of 6k . I deployed closed to 60k. There might be few bugs here and there because as I said earlier, I am really short on time as most of my time goes in looking after my aging parents, my job , my health and my wife. I don't know where this project will go but I am happy that I built something out of the frustration to help me in my investment journey. Was completely fed with financial gurus. Added few more images of my dashboard. And for god sake don't remove this post.

======================================================================

Old post content

Disclaimer: I am not a financial advisor or a SEBI registered entity. I am an Machine Learning engineer working in industry for more than 8+ years.

Like most developers, I wanted my savings to work for me, but the retail trading space is full of traps:

  1. Overfitted AI Bots: Feeding raw stock prices into LSTM/deep learning models just memorizes noise. They look perfect in backtests, but blow up live.
  2. Lagging Indicators: 1970s charts (RSI/MACD) are lagging averages that get front-run by HFT servers at microsecond speeds.
  3. Shitty performance of current Mutual Funds : 90% of the stocks has given negative return in last 2 years. I was tired of handing over commission to them. Hence decided to try something to build

So, After more than 8 months of struggle, I built StockMind—an automated quant engine focused on Cash Equity Swing Trading.

🚫 Why F&O (Futures & Options) is Excluded

SEBI states that 90% of retail F&O traders lose money. The math is structurally rigged against us:

  • Theta (Time Decay): Options decay to zero on expiry. In cash equity, you have holding power to wait out drawdown cycles.
  • Leverage trap: 5x margin leverage means a small 2% market dip triggers a force liquidation at the absolute bottom.
  • Friction drag: Frequent options trades bleed up to 10-15% of your capital annually in STT, GST, and brokerage fees.

📊 The Math & Modeling Implemented

Instead of predicting price ticks, the engine uses structural probability:

  • Sector Rotation: Ranks sector indices daily using Relative Strength (RS) against the Nifty 50. All buy signals in weak sectors (bottom 30%) are automatically blocked.
  • Quality + Momentum Screen: Excludes high-debt companies (Debt-to-Equity > 1.5) and prioritizes high return (ROE > 15%), filtering only macro uptrends (Price > 150-day SMA).
  • Friction-Adjusted Backtests: Adds a flat 0.25% cost per trade to simulate real-world STT and bid-ask slippage.

📈 Metrics & Performance

Backtested metrics over the last 5 years (adjusted for 0.25% cost per trade):

  • CAGR: [24.5%] | Max DD: [-12.3%] | Sharpe: [1.65]

Here is my current live paper-trading performance. I have started trading with real money as well. Will share the result soon in next post.

Dashboard Image

https://preview.redd.it/v7dwghb6lyah1.png?width=2860&format=png&auto=webp&s=ad317c6934d10e1b210972c58a348e943ad0e521

Paper Trading results

https://preview.redd.it/3ho585pelyah1.png?width=2880&format=png&auto=webp&s=b5becae9615b7067f192035fe49f88d4d6acc811

⚠️ Current Weaknesses

  • Manual Login: Have to log in manually to Zerodha Kite every morning to generate the API session token (no free automated headless login).
  • Daily timeframes only: Runs end-of-day data for swing trading. Not designed for day traders. Its more for medium to long term perspective.

💻 Website Link/Dashboard

Would love to get feedback from other developers and quants on the slippage modeling and sector rotation index.

u/WinterSpecial7970 — 3 days ago

I’m an ML Engineer. I got tired of "AI Trading Bot" scams, so I coded my own Cash Swing Trading Engine in public. (No advice, just math)

Hey everyone,

Disclaimer: I am not a financial advisor or a SEBI registered entity. I am an Machine Learning engineer working in industry for more than 8+ years.

Like most developers, I wanted my savings to work for me, but the retail trading space is full of traps:

  1. Overfitted AI Bots: Feeding raw stock prices into LSTM/deep learning models just memorizes noise. They look perfect in backtests, but blow up live.
  2. Lagging Indicators: 1970s charts (RSI/MACD) are lagging averages that get front-run by HFT servers at microsecond speeds.
  3. Shitty performance of current Mutual Funds : 90% of the stocks has given negative return in last 2 years. I was tired of handing over commission to them. Hence decided to try something to build

So, After more than 8 months of struggle, I built StockMind—an automated quant engine focused on Cash Equity Swing Trading.

🚫 Why F&O (Futures & Options) is Excluded

SEBI states that 90% of retail F&O traders lose money. The math is structurally rigged against us:

  • Theta (Time Decay): Options decay to zero on expiry. In cash equity, you have holding power to wait out drawdown cycles.
  • Leverage trap: 5x margin leverage means a small 2% market dip triggers a force liquidation at the absolute bottom.
  • Friction drag: Frequent options trades bleed up to 10-15% of your capital annually in STT, GST, and brokerage fees.

📊 The Math & Modeling Implemented

Instead of predicting price ticks, the engine uses structural probability:

  • Sector Rotation: Ranks sector indices daily using Relative Strength (RS) against the Nifty 50. All buy signals in weak sectors (bottom 30%) are automatically blocked.
  • Quality + Momentum Screen: Excludes high-debt companies (Debt-to-Equity > 1.5) and prioritizes high return (ROE > 15%), filtering only macro uptrends (Price > 150-day SMA).
  • Friction-Adjusted Backtests: Adds a flat 0.25% cost per trade to simulate real-world STT and bid-ask slippage.

📈 Metrics & Performance

Backtested metrics over the last 5 years (adjusted for 0.25% cost per trade):

  • CAGR: [Insert, e.g., 24.5%] | Max DD: [Insert, e.g., -12.3%] | Sharpe: [Insert, e.g., 1.65]

Here is my current live paper-trading performance. I have started trading with real money as well. Will share the result soon in next post.

Paper Trade performance.

⚠️ Current Weaknesses

  • Manual Login: Have to log in manually to Zerodha Kite every morning to generate the API session token (no free automated headless login).
  • Daily timeframes only: Runs end-of-day data for swing trading. Not designed for day traders. Its more for medium to long term perspective.

💻 Open Source & Dashboard

Would love to get feedback from other developers and quants on the slippage modeling and sector rotation index.

reddit.com
u/WinterSpecial7970 — 3 days ago
▲ 1 r/SaaS

I am an AI Engineer working in this space from past 9 years. The way everyone rushed to create AI applications, I realized one thing. Very few people really thinks about potential vulnerability in there code base. This results in piling up of technical debt.

On top of it most of the existing SAST tools are not designed to capture GenAI / Agentic Logic vulnerabilities. Existing scanners either miss prompt injections entirely, or they flag every single string formatting operation, which makes the alerts useless.

I wanted a tool that actually understands the intent of the data flow.This was the problem statement I started working on it. Lately after hearing so many layoff it put the fuel to fire as well

So, I spent the last 3 months planning ,designing & building RepoInspect.

However I am a builder, an engineer but very bad in marketing and moving a product to profitability.

Anyway let's get back to solution. Repoinspect is a two-pass hybrid engine. It uses a deterministic AST taint tracker to find potential hotspots, then hands the attack path to an autonomous AI agent to verify if the injection is actually exploitable.

End Result: To test it, I pointed it at some of the most popular AI frameworks. Got multiple bugs in those. Attaching the detailed results on github.

The Launch Struggle: I tried to launch on Hacker News yesterday. Because my account is new, I got flagged almost immediately. It was a huge punch in the gut after a month. Same thing happened with most of the reddits accounts. Honestly speaking I have never been to these sites and really doesn't know the rules and regulations around it. I just want my solution to be atleast given chance and heard by AI folks.

But instead of giving up, I spent this weekend adding what the community might like : Local LLM support  so teams can run audits without their code ever leaving their machine.

I've open-sourced the engine and all the forensic reports. I’d love to hear from other founders who have built developer-focused security tools. How do you find your first "Real" users when the automated filters are so aggressive?

GitHub: https://github.com/ritesh-ui/RepoInspect

u/WinterSpecial7970 — 2 months ago

Apparently along with 10th,12th , Graduation , Service Letter they are asking for permissions into our ITR, Bank Statement, EPFO website ?

Is there any law enforcement in this country to stop this shit happening. Murder of our digital privacy and forcing us to be digitally naked.

Highly disappointing and disturbing. Never seen such shit happening in last 9 years of my corporate experience

reddit.com
u/WinterSpecial7970 — 2 months ago
▲ 8 r/aisecurity+1 crossposts

Hey everyone,

I’ve been working on a project to solve a major problem in AI security: Traditional SAST tools (Snyk, SonarQube, etc.) are blind to "Agentic Logic" bugs. They look for bad strings, but they don't understand how user data can hijack an LLM’s instructions.

I built a deterministic engine called RepoInspect that merges AST-aware taint tracking with autonomous AI agents. To test it, I ran it against LangChain, and it flagged 10 high-severity vulnerabilities that had been missed by standard tools.

The most common issue: Instruction Hijacking (LLM01) In several built-in chains (like the LLMMathChain), user input is interpolated directly into a prompt template that tells the model to generate executable Python code (for numexpr).

The Attack Vector: Because the user {input} isn't delimited (no XML tags, no isolation), an attacker can simply "ask" the model to generate malicious system commands instead of a math expression. Since the chain executes that code immediately, it’s a direct path to code execution via a prompt.

Key Findings in the Audit:

  • Prompt Injection: 10+ cases in agents (Self-Ask, JSON Chat) and chains.
  • Excessive Agency: Critical risks in utility wrappers exposing API keys.
  • Insecure Deserialization: Risks in how some vector store adapters handle metadata.

Why I’m sharing this: I’ve open-sourced the engine and the full forensic reports for LangChain, OpenAI, and Dify. I want to help developers move beyond "hope-based security" for their RAG and Agentic pipelines.

I'm curious to hear from other researchers—besides XML delimiters and system message isolation, what "hard" defenses are you using to protect your agents from hijacking?Adding github repo in the comments.

reddit.com
u/WinterSpecial7970 — 2 months ago