<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Rashmin Bhanderi on Medium]]></title>
        <description><![CDATA[Stories by Rashmin Bhanderi on Medium]]></description>
        <link>https://medium.com/@rashmin31?source=rss-25ce420537f1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Rashmin Bhanderi on Medium</title>
            <link>https://medium.com/@rashmin31?source=rss-25ce420537f1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 23:22:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rashmin31/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Before Building Any Trading Strategy, I Built a Risk Engine (With Python & Real Market Data)]]></title>
            <link>https://rashmin31.medium.com/before-building-any-trading-strategy-i-built-a-risk-engine-with-python-real-market-data-c8f081758296?source=rss-25ce420537f1------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8f081758296</guid>
            <category><![CDATA[quantitative-finance]]></category>
            <category><![CDATA[options-trading]]></category>
            <category><![CDATA[algorithmic-trading]]></category>
            <category><![CDATA[risk-management]]></category>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[Rashmin Bhanderi]]></dc:creator>
            <pubDate>Sat, 27 Dec 2025 20:41:13 GMT</pubDate>
            <atom:updated>2025-12-27T20:47:34.586Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Most traders ask which strategy makes money.<br> I first asked when <strong>not</strong> to trade.</blockquote><p>This blog documents the <strong>first phase of my quant trading learning journey</strong> — not a strategy, not machine learning, not fancy mathematics — but something far more important:</p><blockquote><strong><em>Understanding market risk before deploying any trading strategy.</em></strong></blockquote><p>If you are someone who:</p><ul><li>feels lost when people say <em>quant</em>, <em>volatility</em>, <em>regimes</em></li><li>watches trading videos but doesn’t know how to <em>apply</em> concepts</li><li>wants to build algorithmic trading systems <strong>step by step</strong></li></ul><p>this blog is for you.</p><h3>🧒 Explaining like to a 5 year old kid:</h3><p>Before going outside to play, parents check:</p><ul><li>Is it raining?</li><li>Is the road slippery?</li><li>Is it safe?</li></ul><p>Trading works the same way.</p><p>Before trading options, I wanted to know:</p><ul><li>When is the market calm?</li><li>When is it noisy?</li><li>When is it <strong>dangerous</strong>?</li></ul><p>So instead of starting with a trading strategy,<br>I started by building a <strong>risk engine</strong> that tells me:</p><ul><li>✅ Trade allowed</li><li>❌ Don’t trade</li></ul><h3>🚦 Real-world analogy</h3><p>Even if you are a very good driver:</p><ul><li>you don’t drive fast during heavy rain</li><li>you don’t speed during peak traffic</li></ul><p>Markets also have:</p><ul><li>calm periods</li><li>noisy periods</li><li><strong>high-risk periods</strong></li></ul><p>My goal was to <strong>identify those high-risk periods using data</strong>.</p><h3>🇮🇳 Practical Indian trading context</h3><p>Many traders in India lose money in weekly options not because their strategy is bad, but because:</p><ul><li>volatility suddenly increases</li><li>rare but extreme weeks hit their positions</li><li>they ignore market risk conditions</li></ul><p>So before touching <strong>weekly options</strong>, I decided to answer a simple question:</p><blockquote><em>“Historically, when is the market dangerous?”</em></blockquote><h3>What I built (high level)</h3><p>I built a <strong>market risk analysis pipeline</strong> that works on:</p><ul><li>Daily data</li><li>Weekly data</li><li>Monthly data</li></ul><p>For:</p><ul><li><strong>NIFTY 50</strong></li><li><strong>SENSEX</strong></li></ul><p>The output is intentionally simple:</p><ul><li>trade_allowed = True / False</li><li>reason = HIGH_VOL_REGIME</li></ul><p>No prediction. No forecasting. No ML.<br>Just <strong>risk awareness</strong>.</p><h3>Project structure (important for learners)</h3><pre>quant-risk-engine/<br>│<br>├── run.py<br>├── src/<br>│   ├── market_analysis.py<br>│   ├── data_loader.py<br>│   ├── statistics.py<br>│   ├── report.py<br>│   └── __init__.py<br>│<br>├── config/<br>│   └── settings.py<br>│<br>├── data/<br>│   ├── raw/<br>│   └── processed/<br>│<br>└── outputs/<br>    └── reports/</pre><p>This is <strong>not notebook-style coding</strong>.<br>This is how <strong>real systems</strong> are built.</p><h3>Step-by-step: What we did, why we did it, how we did it</h3><h3>1️⃣ Market data</h3><h3>What?</h3><p>Historical price data for NIFTY and SENSEX.</p><h3>Why?</h3><p>Options depend on <strong>how prices move</strong>, not just price levels.</p><h3>How?</h3><p>Using Yahoo Finance with Python.</p><pre>class YahooDataLoader:<br>    def fetch(self, ticker, start, end):<br>        import yfinance as yf<br>        df = yf.download(ticker, start=start, end=end, progress=False)<br>        return df</pre><h3>2️⃣ Data cleaning (non-negotiable)</h3><h3>Why?</h3><p>Market data is messy. Blind trust creates silent bugs.</p><pre>class DataCleaner:<br>    def clean(self, df):<br>        price_col = &quot;Adj Close&quot; if &quot;Adj Close&quot; in df.columns else &quot;Close&quot;<br>        df = df[[price_col]].dropna()<br>        df.columns = [&quot;close&quot;]<br>        return df</pre><h3>3️⃣ Returns (core quant concept)</h3><h3>What is a return?</h3><pre>Return = (Today − Yesterday) / Yesterday</pre><p>Options risk depends on <strong>returns</strong>, not prices.</p><pre>df[&quot;ret&quot;] = df[&quot;close&quot;].pct_change()<br>df[&quot;log_ret&quot;] = np.log(df[&quot;close&quot;] / df[&quot;close&quot;].shift(1))</pre><h3>4️⃣ Volatility (the real enemy)</h3><h3>What is volatility?</h3><p>How violently returns move.</p><p>High volatility = market is unstable.</p><pre>df[&quot;roll_vol&quot;] = (<br>    df[&quot;log_ret&quot;]<br>    .rolling(window)<br>    .std()<br>    * np.sqrt(annualization_factor)<br>)</pre><h3>5️⃣ Descriptive statistics (understanding behaviour)</h3><p>We calculated:</p><ul><li>Mean</li><li>Standard deviation</li><li>5% worst returns</li><li>95% best returns</li><li>Skew</li><li>Kurtosis</li><li>Max drawdown</li></ul><pre>class DescriptiveStatistics:<br>    def summarize_returns(self, r):<br>        return {<br>            &quot;mean&quot;: r.mean(),<br>            &quot;std&quot;: r.std(),<br>            &quot;p05&quot;: r.quantile(0.05),<br>            &quot;p95&quot;: r.quantile(0.95),<br>            &quot;skew&quot;: r.skew(),<br>            &quot;kurtosis&quot;: r.kurtosis(),<br>        }</pre><h3>6️⃣ Drawdown (survival metric)</h3><h3>What is drawdown?</h3><p>Worst fall from peak to trough.</p><pre>equity = np.exp(df[&quot;log_ret&quot;].fillna(0).cumsum())<br>df[&quot;drawdown&quot;] = equity / equity.cummax() - 1</pre><p>Strategies don’t fail because of low win rate.<br>They fail because of <strong>large drawdowns</strong>.</p><h3>7️⃣ Timeframe transformation (daily → weekly → monthly)</h3><p>Weekly options depend on <strong>weekly behaviour</strong>, not daily noise.</p><pre>weekly = daily.resample(&quot;W-FRI&quot;).last()<br>monthly = daily.resample(&quot;M&quot;).last()</pre><p>Same logic. Different perspective.</p><h3>8️⃣ Volatility regimes (market states)</h3><p>Markets have different moods:</p><ul><li>LOW → calm</li><li>MID → noisy</li><li>HIGH → dangerous</li></ul><pre>class VolRegimeClassifier:<br>    def label(self, vol):<br>        q33 = vol.quantile(0.33)<br>        q66 = vol.quantile(0.66)</pre><pre>        if vol &lt;= q33:<br>            return &quot;LOW&quot;<br>        elif vol &lt;= q66:<br>            return &quot;MID&quot;<br>        else:<br>            return &quot;HIGH&quot;</pre><h3>9️⃣ Trade filter (most important part)</h3><h3>Simple rule:</h3><pre>IF volatility regime == HIGH<br>→ DO NOT TRADE<br>ELSE<br>→ Trade allowed</pre><pre>class TradeFilter:<br>    def apply(self, df):<br>        df[&quot;trade_allowed&quot;] = df[&quot;vol_regime&quot;] != &quot;HIGH&quot;<br>        df[&quot;trade_reason&quot;] = df[&quot;vol_regime&quot;].apply(<br>            lambda x: &quot;HIGH_VOL_REGIME&quot; if x == &quot;HIGH&quot; else &quot;OK&quot;<br>        )<br>        return df</pre><h3>🔍 What the data showed (real results)</h3><p>After running this on <strong>NIFTY and SENSEX</strong>:</p><ul><li>~30–35% of periods were flagged as <strong>NO TRADE</strong></li><li>Results were consistent across:</li><li>daily</li><li>weekly</li><li>monthly</li></ul><p>This indicates the system is <strong>stable</strong>, not random.</p><h3>🧠 What this system is (and is not)</h3><h3>✅ It IS:</h3><ul><li>a risk engine</li><li>a survival filter</li><li>strategy-agnostic</li><li>explainable</li></ul><h3>❌ It is NOT:</h3><ul><li>a prediction model</li><li>a trading strategy</li><li>machine learning magic</li></ul><h3>🎯 Why I did this BEFORE any strategy</h3><p>Most retail traders ask:</p><blockquote><em>“Which strategy works?”</em></blockquote><p>Professional system builders ask:</p><blockquote><em>“When should </em><strong><em>no strategy</em></strong><em> run?”</em></blockquote><p>This project answers the second question.</p><h3>🚀 What comes next</h3><p>In the next part of this series, I will:</p><ul><li>design <strong>defined-risk weekly option structures</strong></li><li>run them <strong>only when trade_allowed = True</strong></li><li>compare performance with and without the risk filter</li></ul><p>That’s where actual strategy logic begins.</p><h3>🧠 Final takeaway</h3><p>If you remember only one thing:</p><blockquote><strong><em>Not trading during risky periods is itself a strategy.</em></strong></blockquote><h3>End of Part 1 — My Quant Trading Learning Journey</h3><h3>If this helped you</h3><p>If you are also learning quantitative or algorithmic trading and feel overwhelmed, you’re not alone. I’m documenting my journey so others can learn <strong>slowly, clearly, and practically</strong>.</p><p>More posts coming soon.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8f081758296" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 1: Introduction to Algo Trading with Kite Connect: Automating Login Process]]></title>
            <link>https://rashmin31.medium.com/part-1-introduction-to-algo-trading-with-kite-connect-automating-login-process-11c961b1ab8d?source=rss-25ce420537f1------2</link>
            <guid isPermaLink="false">https://medium.com/p/11c961b1ab8d</guid>
            <category><![CDATA[zerodha]]></category>
            <category><![CDATA[trading-strategies-course]]></category>
            <category><![CDATA[automate-login]]></category>
            <category><![CDATA[algorithmic-trading]]></category>
            <category><![CDATA[two-factor-authentication]]></category>
            <dc:creator><![CDATA[Rashmin Bhanderi]]></dc:creator>
            <pubDate>Fri, 31 May 2024 20:51:28 GMT</pubDate>
            <atom:updated>2024-05-31T20:51:28.730Z</atom:updated>
            <content:encoded><![CDATA[<p>Algorithmic trading involves using computer programs to execute trading strategies at high speed and volume. Zerodha’s Kite Connect API is a popular choice for algo traders in India due to its robust features and extensive documentation.</p><p>In this article, we will walk through a Python script that automates the login process to the Zerodha trading platform using the Kite Connect API. This script performs two-factor authentication and retrieves an access token, which can be used for further trading activities.</p><h4>Required Files</h4><p>We have two separate files: credentials_zerodha for storing sensitive login credentials, and api_urls for storing API endpoints.</p><p>Below is the credentials_zerodha.py file:</p><pre>USERNAME = &#39;&#39;<br>PASSWORD = &#39;&#39;<br>API_SECRET = &#39;&#39;<br>API_KEY = &#39;&#39;<br>TOTP_TOKEN = &#39;&#39;<br>TOTP_TOKEN_1 = &#39;&#39;</pre><ul><li>USERNAME: Your Zerodha account username.</li><li>PASSWORD: Your Zerodha account password.</li><li>API_SECRET: Your Kite Connect API secret.</li><li>API_KEY: Your Kite Connect API key.</li><li>TOTP_TOKEN: Your TOTP (Time-based One-Time Password) token for two-factor authentication.</li><li>TOTP_TOKEN_1: An additional TOTP token (if required).</li></ul><p>api_urls.py file:</p><pre>BASE_URL = &quot;https://kite.zerodha.com&quot;<br>LOGIN_URL = BASE_URL + &quot;/api/login&quot;<br>TWOFA_URL = BASE_URL + &quot;/api/twofa&quot;<br>INSTRUMENTS_URL = &quot;https://api.kite.trade/instruments&quot;</pre><ul><li>BASE_URL: The base URL for Zerodha Kite.</li><li>LOGIN_URL: The endpoint for the login API.</li><li>TWOFA_URL: The endpoint for the two-factor authentication API.</li><li>INSTRUMENTS_URL: The endpoint for accessing instrument details (not used in this script but useful for other API calls).</li></ul><h3><strong>The Auto Login Script</strong></h3><p>Now, let’s dive into the main script that automates the login process.</p><p><strong>Importing Required Libraries</strong></p><pre>import pyotp<br>import json<br>import requests<br>from kiteconnect import KiteConnect<br>from credentials_zerodha import USERNAME, PASSWORD, API_SECRET, API_KEY, TOTP_TOKEN<br>from api_urls import LOGIN_URL, TWOFA_URL</pre><ul><li>pyotp: A library to generate Time-based One-Time Passwords (TOTP) used for two-factor authentication.</li><li>json: To handle JSON data.</li><li>requests: To make HTTP requests.</li><li>KiteConnect: The Kite Connect API client.</li><li>credentials_zerodha: A separate file where we store sensitive login credentials.</li><li>api_urls: A separate file where we store the URLs for the login and two-factor authentication endpoints.</li></ul><p><strong>Defining the Auto Login Function</strong></p><pre>def autologin_zerodha():<br>    # Create a session<br>    session = requests.Session()</pre><p>Here, we define a function autologin_zerodha() that initiates a new session using the requests library. This session will be used to maintain the login state.</p><p><strong>Step 1: Initial Login Request</strong></p><pre>    # Get request id in response<br>    response = session.post(LOGIN_URL, data={&#39;user_id&#39;: USERNAME, &#39;password&#39;: PASSWORD})<br>    request_id = json.loads(response.text)[&#39;data&#39;][&#39;request_id&#39;]</pre><p>We send a POST request to the LOGIN_URL with the user&#39;s USERNAME and PASSWORD. The response contains a request_id, which is required for the next step.</p><p><strong>Step 2: Two-Factor Authentication (2FA)</strong></p><pre>    # Two factor authentication<br>    twofa_pin = pyotp.TOTP(TOTP_TOKEN).now()<br>    response_1 = session.post(TWOFA_URL, data={&#39;user_id&#39;: USERNAME, &#39;request_id&#39;: request_id, &#39;twofa_value&#39;: twofa_pin, &#39;twofa_type&#39;: &#39;totp&#39;})</pre><p>For 2FA, we generate a TOTP using the pyotp library with the user&#39;s TOTP_TOKEN. This TOTP is then sent along with the request_id to the TWOFA_URL endpoint.</p><p><strong>Step 3: Initialize KiteConnect and Generate Login URL</strong></p><pre>    kite = KiteConnect(api_key=API_KEY)<br>    kite_url = kite.login_url()<br>    print(kite_url)</pre><p>We initialize the KiteConnect object with the API_KEY. The kite.login_url() method generates a login URL, which we print out for debugging purposes.</p><p><strong>Step 4: Handle the Request Token and Generate Access Token</strong></p><pre>    try:<br>        session.get(kite_url)<br>    except Exception as e:<br>        e_msg = str(e)<br>        request_token = e_msg.split(&#39;request_token=&#39;)[1].split(&#39; &#39;)[0].split(&#39;&amp;action&#39;)[0]<br>        print(&#39;Successful Login with Request Token:{}&#39;.format(request_token))<br>        access_token = kite.generate_session(request_token, API_SECRET)[&#39;access_token&#39;]<br>        return kite, access_token</pre><p>We make a GET request to the kite_url to initiate the login process. If an exception occurs, we extract the request_token from the exception message. This request_token is then used to generate an access_token by calling kite.generate_session(request_token, API_SECRET). The access_token is necessary for authenticated API calls.</p><h3>Conclusion</h3><p>This script automates the login process to Zerodha’s trading platform, handling both the initial login and the two-factor authentication. By automating this step, traders can save time and ensure their trading algorithms can run uninterrupted.</p><p>The retrieved access_token can be used for making further API calls to place orders, retrieve market data, and manage portfolios.</p><p>Understanding this script provides a foundation for building more complex trading strategies and automating your trades with the Kite Connect API.</p><p>In the next part of this series, we will delve deeper into utilizing the Kite Connect API for advanced trading strategies, including placing orders, fetching market data, and managing portfolios.</p><p>Feel free to let me know if you need further assistance or adjustments!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11c961b1ab8d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>