Monday, October 20, 2025

Automating Trading Using Python and Understanding Market Direction with Put-Call Ratio Automating Trading Using Python and Understanding Market Direction with Put-Call Ratio

🚀 Automating Trading Using Python and Understanding Market Direction with Put-Call Ratio

In today’s fast-moving trading environment, every second counts. Successful traders are increasingly relying on automation to gain an edge — not just to execute trades faster, but also to process complex data in real time. In this blog, I will share how Python can be used for automating trades and how the Put-Call Ratio (PCR) can be leveraged to predict market direction.

Automation in trading is no longer just for institutions; with Python and open APIs, individual traders can also build efficient, data-driven trading systems without spending heavily on commercial tools or subscriptions.


Introducing My Last Blog on Put-Call Parity

In my last blog, I explained in detail about Open Interest (OI). If you have not read it, please read it at my blog:
👉 https://manishbansal3003.blogspot.com/2024/07/amazing-insights-how-open-interest-can.html.

I will not go into detail again here, but just to recap — OI is a powerful tool to predict market direction. It is not based on sentiment, but on actual positions that retail and institutional traders currently hold. In my previous article, I explained what open interest is, how changes in open interest occur, and how to analyze those changes.

All these are great from a textbook point of view, but when it comes to trading, theory must translate into practice. Unless we can apply our understanding effectively, all these technical terms make no real sense.


How to Use It Practically to Predict Market Movement

Open Interest represents all open contracts in futures and options. We can use options data to understand the market’s directional expectation. To do this effectively, we must understand the option chain.

An option chain displays all the option contracts for a given underlying, starting from the at-the-money (ATM) option, followed by calls and puts above and below that strike.

In a normal market scenario, contracts at or near the money are the most active, while maximum open interest is often seen in deep out-of-the-money (OTM) contracts. Therefore, to use open interest data meaningfully, we need to leverage both the option chain and changes in OI happening across strikes.

Let’s try to understand this with an example:
Suppose Nifty (NSE Index) is trading at 25,000. We will take 20 strike prices above and below to do our analysis — that is, all calls and puts from 24,000 to 26,000.

Let’s assume total open interest for calls (24,000–26,000) is 60,00,000, and for puts it is 80,00,000. After 15 minutes, the data changes to 70,00,000 for calls and 81,00,000 for puts.

So, the change in open interest for calls = 10,00,000, and for puts = 1,00,000. The ratio is 0.1, which means calls have increased 10 times faster than puts.

Usually, this reflects net buying activity from retailers (who are typically net buyers of options). Hence, it’s safer to assume that the market might go down, as large positions are being taken on calls rather than puts.

I will not take credit for this strategy — this concept has been explained by many experienced analysts on various platforms.

My purpose here is to help readers understand how they can apply this strategy without subscribing to expensive platforms.
I am not here to propose any trading strategy for profit-making — my sole purpose is to demonstrate the application of Python for trade automation. (Disclaimer)

However, while this analysis is easy to explain, executing it in real-time is a challenge. Most platforms show OI data but do not provide real-time analysis of OI changes in the option chain.


Using Python on Real-Time Prices to Calculate Change in Open Interest

Let’s now dive into how Python can be used to automate this analysis step by step.

We will use Jupyter Notebook to write this code.

Step 1: Connect to the Broker’s API

First, we need to connect to the broker’s API to get real-time quotes. Most brokers today offer free APIs and documentation, which makes this easy.

Step 2: Get the ATM Strike

Below is a function to get the ATM strike whenever called. This code might vary slightly depending on your broker’s API documentation, but it’s easy to edit. In case of any issue, feel free to contact me via email.

def get_ATM():
    ATM_Strike = round(int(float(client.quotes(instrument_tokens = [{'instrument_token': 53001, 'exchange_segment': 'nse_fo'}], quote_type = "ltp")[0]['ltp'])))
    ATM_Strike = int(round(ATM_Strike/50)*50)
    return ATM_Strike

Step 3: Build the Option Chain

Once we have the ATM strike, we need to get symbols for all the strikes to build the option chain.

# Get list of CE/PE symbols for ±10 strikes around ATM
def get_option_symbols(df_fo, strike_range=20):
    atm = get_ATM()
    prefix = get_next_tuesday_symbol_prefix()

    symbols = []
    for i in range(-strike_range, strike_range + 1):
        strike = atm + (i * 50)
        ce_key = f"{prefix}{strike}.00CE"
        pe_key = f"{prefix}{strike}.00PE"

        try:
            ce_symbol = df_fo[df_fo['pScripRefKey'] == ce_key]['pSymbol'].iloc[0]
            pe_symbol = df_fo[df_fo['pScripRefKey'] == pe_key]['pSymbol'].iloc[0]
            symbols.append({"strike": strike, "CE": ce_symbol, "PE": pe_symbol})
        except IndexError:
            continue

    return symbols
Screenshot

Step 4: Fetch and Resample Real-Time Data

In the next step, we fetch real-time quotes for all option chain contracts and store them in a dataframe.
Quotes usually come in JSON format, so they need to be converted first. I am not going into that detail here, but I can help anyone who wants to build this strategy and customize it to run seamlessly.

Once the quotes are in a dataframe, we can resample them to 5-minute or 15-minute data for analysis.

def dfResample15min(df):
    if not (df.index.name == 'timestamp' and pd.api.types.is_datetime64_any_dtype(df.index)):
        df['timestamp'] = pd.to_datetime(df['timestamp'])
        df.set_index('timestamp', inplace=True)
        df.sort_index(inplace=True)

    df["strike"] = df["strike"].fillna(0)

    results = []
    resample_rule = '15min'

    for (sym, strike, opt_type), group in df.groupby(["symbol", "strike", "option_type"]):
        ohlc = group['ltp'].resample(resample_rule, label='right', closed='right').ohlc()
        oi_last = group['open_int'].resample(resample_rule, label='right', closed='right').last()
        oi_open = group['open_int'].resample(resample_rule, label='right', closed='right').first()

        oi_change = oi_last.diff()
        oi_change.iloc[0] = oi_last.iloc[0] - oi_open.iloc[0]

        vol_last = group['last_volume'].resample(resample_rule, label='right', closed='right').last()
        vol_open = group['last_volume'].resample(resample_rule, label='right', closed='right').first()

        vol_change = vol_last.diff()
        vol_change.iloc[0] = vol_last.iloc[0] - vol_open.iloc[0]

        res = pd.concat([ohlc, oi_last.rename('open_int'), vol_last.rename('volume'), oi_change.rename('oi_change'), vol_change.rename('volume_change')], axis=1)

        res["symbol"] = sym
        res["strike"] = strike
        res["option_type"] = opt_type
        results.append(res.reset_index())

    return pd.concat(results, ignore_index=True)
Screenshot

Step 5: Build Total Cumulative OI Change and PCR

We can now calculate cumulative OI change for calls and puts and derive the Put-Call Ratio.

def build_total_oi_change_cumulative(df_15):
    df_15 = df_15.sort_values("timestamp")

    call_df = (
        df_15[df_15["option_type"] == "CE"]
        .groupby("timestamp")["oi_change"]
        .sum()
        .cumsum()
        .rename("call_oi_cum")
    )

    put_df = (
        df_15[df_15["option_type"] == "PE"]
        .groupby("timestamp")["oi_change"]
        .sum()
        .cumsum()
        .rename("put_oi_cum")
    )

    total_df = pd.concat([call_df, put_df], axis=1).fillna(0)
    total_df["PCR"] = abs(total_df["put_oi_cum"]) / abs(total_df["call_oi_cum"]).replace(0, np.nan)
    total_df["PCR"] = total_df["PCR"].replace([np.inf, -np.inf, np.nan], 0)

    return total_df.reset_index()
Screenshot

Step 6: Building an Automated Trading System

By integrating this logic with trade-entry and exit rules, you can create a fully automated trading system.
Though I have not shared all the broker-specific code here (since it varies), I have covered the core logic that forms the foundation of a PCR-based strategy.

In the build_total_oi_change_cumulative(df_15) function, notice how the code sorts timestamps, groups data by option type, calculates cumulative OI change, and computes PCR as the ratio of cumulative put OI to cumulative call OI.

This is just one simple strategy to demonstrate how powerful Python is as a tool for automating trading.
Similarly, we can use real-time data to calculate Option Greeks, manage delta-neutral portfolios, or design multi-indicator strategies.

In fact, I have already built one strategy where I take a position and dynamically manage it to stay delta-neutral using multiple indicators — but I will cover that in my next blog, where I’ll explain how to use Option Greeks in Python.


🔍 Conclusion: Why You Should Start Automating Trades with Python

Python is a game-changer for modern traders. It bridges the gap between financial theory and real-world execution. With a few lines of code, you can collect, analyze, and act on live market data in real time — all without relying on costly subscriptions or platforms.

By automating your strategy, you reduce human error, gain consistency, and ensure disciplined execution. Whether it’s through the Put-Call Ratio, Option Greeks, or custom technical indicators, Python empowers you to take full control of your trading process.

If you’ve ever thought that trading automation is only for tech experts — think again. With Python, even non-programmers can start small, automate parts of their strategy, and grow steadily.


Take Control of Your Finances Today!

If you want to plan your finances effectively and take actionable steps that lead to real, measurable results, I can help. From budgeting and accounting to evaluating the feasibility of your financial plans, we’ll work together to set clear goals and achieve them.

📧 Email: bansalmanish30003@gmail.com
📞 Call: 7003426212

Let’s turn your financial goals into reality—reach out and get started!

About the Author:
Manish is a Chartered Accountant by profession and a passionate writer who loves exploring human behavior, finance, and the intersection of professional life with personal growth. Through his blogs, he shares practical insights drawn from real-world experience to inspire working professionals toward financial and personal independence.
© 2025 Manish Bansal | All Rights Reserved

⚠️ Disclaimer

I am not providing any trading advice or tips in this blog.
My sole purpose is to demonstrate how Python can be leveraged as a powerful tool for trade automation and to inspire traders to explore automation responsibly.

Tuesday, October 7, 2025

Discipline Your Finances, Design Your Future: A Guide to True Financial Independence

Discipline Your Finances, Design Your Future: A Guide to True Financial Independence

We often hear people talk about leading a disciplined life. Usually, it means maintaining daily habits like waking up early, exercising, and eating healthy. These habits undoubtedly have a profound impact on our physical and mental well-being.

However, in today’s fast-changing world, discipline should not be limited to lifestyle alone — it must extend to financial discipline as well. In fact, both types of discipline are deeply interrelated.

A person with strong lifestyle discipline but weak financial habits will constantly face money-related stress, which ultimately affects health. Conversely, someone with excellent financial habits but a careless lifestyle may suffer health issues that drain wealth through medical expenses.

Hence, it’s crucial to strike a balance between both — lifestyle discipline and financial discipline.

In this article, we’ll explore why financial discipline is important and how to develop it in practical ways.

Why Is Financial Discipline Important?

1. The First Step Toward Financial Independence

Discipline — whether in lifestyle or finance — always has a positive impact. Just as daily discipline leads to a healthy life, financial discipline is the first step toward financial independence.

Financial independence, simply put, is a state where your assets generate enough income to sustain your lifestyle without depending on anyone else. It is when your money starts working for you — not the other way around.

2. Reduces Debt and Creates Wealth

With wise financial decisions and consistent discipline, you stay conscious of your income, expenses, and liabilities.

Think of it like a water tank — one pipe fills it (income), and another drains it (expenses). If the outflow is faster than the inflow, the tank will always remain empty.

Similarly, if your expenses exceed your income, you’ll always struggle financially. The first rule of discipline is ensuring your outflow never exceeds your inflow.

Once you control expenses, you begin to accumulate savings. These savings become the foundation for wealth creation — through investments in FDs, bonds, shares, or real estate.

A common mistake people make is committing to fixed monthly expenses without realizing how toxic they can be. For example, a fixed expense of ₹20,000 per month is far more harmful than a one-time expense of ₹2.4 lakhs. You’ll think a hundred times before spending ₹2.4 lakhs at once, but may ignore a small monthly EMI that quietly drains your wealth. That’s why EMIs and credit cards can be dangerous traps if not used wisely.

3. Boosts Confidence

Have you ever noticed how confidence often stems from achievement or preparedness?

Imagine a Class 5 student who doesn’t know the answer to a question versus one who does. The confidence level of the latter is naturally higher.

Similarly, a financially independent person approaches every financial decision — negotiations, risks, investments — with much more confidence. They know they have a cushion and can take calculated risks. That self-assurance often leads to better outcomes.

How to Achieve Financial Discipline

1. Reality Check

Start with an honest assessment of your current financial situation — income, expenses, savings, and liabilities.

Many people avoid this because they fear discovering that their finances aren’t as strong as they thought. Others only check whether their salary is credited but never track where it goes.

Avoiding reality doesn’t change it. Awareness — even if uncomfortable — is the first step toward improvement. Once you know your true position, you can make informed decisions.

2. Risk Analysis

Another often-overlooked area is risk assessment.

For instance, many people still don’t have health insurance. Over time, as they age, premiums become unaffordable. The uncertainty of medical emergencies itself creates stress.

Similarly, risks such as job loss, outdated skills, or approaching retirement must be acknowledged and planned for. Continuous risk analysis and mitigation are essential components of long-term financial discipline and peace of mind.

3. Understanding Necessity vs. Luxury

This is one of the most critical distinctions for financial discipline.

Knowing the difference between needs and wants helps you make smarter financial choices.

For example, I’ve met people obsessed with buying expensive phones through EMIs that consume half their salary — even though a regular phone would do the same job.

Unless your profession demands it (like media, marketing, or creative work), such purchases are luxuries, not necessities. The same logic applies to owning a car, renting vs. buying a home, and other lifestyle choices.

4. Budgeting and Planning

Budgeting isn’t just a financial exercise — it’s a mindset.

Many people start budgeting but quit when they don’t see immediate results. However, consistent budgeting makes you more aware and mindful of where every rupee goes.

For example, if you’ve subscribed to an OTT platform for ₹500 per month but your broadband now includes it for free, you’ll notice the duplicate expense only through budgeting. Canceling such unnecessary subscriptions helps you feel in control and reinforces the value of money.

Budgeting builds awareness, accountability, and mindfulness — the three pillars of financial discipline.

5. Measuring and Analyzing Wealth Regularly

Once you start budgeting, the next step is to analyze your progress.

Compare your actual spending with your planned budget. If your expenses exceed expectations, find out why. If they align well, reward yourself with self-appreciation — it motivates you to stay disciplined.

Then, assess your surplus funds and how efficiently they’re earning returns. Money lying idle in a savings account earns 3–4% interest, while FDs, bonds, or equity can yield higher returns — provided they align with your goals and risk appetite.

6. Understanding Assets vs. Expenses

From a financial discipline perspective, not everything that looks like an asset truly is one.

For example, your residential property gives you a sense of security, but if you live in it, it doesn’t generate cash flow. You pay maintenance, taxes, and interest, making it a non-income-generating asset.

However, if you rent it out, it becomes a true asset that covers costs and earns income.

Similarly, buying gold jewelry is an expense; buying gold bullion is an investment. The mindset shift from owning things to creating income-generating assets is what builds true wealth.

A great book that beautifully explains this is “Rich Dad Poor Dad” by Robert T. Kiyosaki — Buy Rich Dad Poor Dad: What the Rich Teach Their Kids About Money That the Poor and Middle Class Do Not!

7. Celebrating Success and Learning from Failures

Becoming financially disciplined and independent deserves celebration — but within reason.

Equally important is learning from mistakes. Everyone makes financial errors; what matters is not repeating them.

A wise person learns from past mistakes, while a fool keeps repeating them. People often say others are “lucky” in financial matters, but in reality, they’ve just learned to avoid their previous mistakes.

Financial wisdom doesn’t come from books alone — it comes from reflection, correction, and persistence.

Conclusion: Discipline Today, Freedom Tomorrow

Financial discipline isn’t about restricting yourself — it’s about creating freedom and security.

  • Avoid unnecessary stress and debt.
  • Build sustainable wealth.
  • Gain confidence in your decisions.
  • Create a future where money works for you.

Just like physical discipline keeps your body fit, financial discipline keeps your life stable and future-ready. Start small, stay consistent, and remember — discipline is the bridge between goals and achievement.

Take Control of Your Finances Today!

If you want to plan your finances effectively and take actionable steps that lead to real, measurable results, I can help. From budgeting and accounting to evaluating the feasibility of your financial plans, we’ll work together to set clear goals and achieve them.

📧 Email: bansalmanish30003@gmail.com
📞 Call: 7003426212

Let’s turn your financial goals into reality—reach out and get started!

About the Author:
Manish is a Chartered Accountant by profession and a passionate writer who loves exploring human behavior, finance, and the intersection of professional life with personal growth. Through his blogs, he shares practical insights drawn from real-world experience to inspire working professionals toward financial and personal independence.
© 2025 Manish Bansal | All Rights Reserved

Saturday, October 4, 2025

The Secret Blueprint for Salaried Employees to Build a Business Without Risk

The Secret Blueprint for Salaried Employees to Build a Business Without Risk

Today, I am writing about one of the most common and chronic challenges faced by many 9-to-5 corporate soldiers — the struggle of starting a parallel business while managing a full-time job.

The dynamics have changed drastically post-COVID. With the rise of work-from-home and flexible work hours, professionals have gained some control over their schedules. However, this flexibility has a darker side — the clock has quietly shifted from 9 to 5 to 9 to 9, or even longer when required.

Despite this, the new work culture has given professionals the opportunity to manage a side gig and generate an additional source of income. Yet, several challenges still persist — obstacles that most salaried individuals face the moment they start thinking about entrepreneurship.

Let’s discuss these challenges stage by stage. I would love to hear your thoughts in the comment section below.

Stage One: The Active vs Passive Income Dilemma

The first and foremost challenge for most professionals looking for a side gig is understanding the difference between active and passive income.

Even those who know the theory often fail to apply it in practice. I won’t go into textbook definitions (there’s already plenty of material online), but to put it simply — a passive source of income should not require the same level of time and effort as your active source of income.

For a salaried individual, the active source is their job. Unless you devote your time and effort, you won’t earn your salary. On the other hand, a passive source of income is something that earns money for you with minimal effort — your money works instead of you.

For example, earning interest from a Fixed Deposit (FD) is a passive income. Suppose someone invests ₹10 lakhs in an FD — within a few clicks, the FD is booked, and they start earning around ₹60,000 a year, effortlessly. But yes — ₹60,000 or even less is hardly lucrative at today’s FD rates! Check Latest FD Interest Rates - October 2025

And this is where the premium for risk and time begins.

Let’s say you decide to invest in shares instead. Either you hire a professional portfolio manager who charges fees (and you might earn around 12% annually), or you invest time and effort in your own analysis.

Whatever route you take, once your money is invested wisely, it continues to work for you — that’s the essence of passive income.

There are other traditional options like bonds, REITs, T-bills, corporate FDs, IPOs, etc., which I won’t detail here since there’s ample information online.

But this Stage One applies mostly to professionals who already have some savings and a stable income. Unfortunately, the returns from these traditional passive sources are so low that they hardly make a difference — unless you already have a large corpus (around ₹1 crore or more).

And here lies the biggest dilemma — for most first-generation professionals, the real struggle is to reach that first crore.

Stage Two: The Leap of Faith

After going through Stage One, professionals soon realize that traditional passive income sources don’t create real wealth. So they look for something riskier but with higher returns.

At this point, they often forget the active vs passive principle. They enter the build and operate mode — and that’s where the biggest mistake happens.

Now they aim to build something that needs an investment of ₹50,000 but expect to earn ₹5,00,000 a year from it. With such unrealistic targets, demotivation sets in quickly after initial failures.

This new breed of entrepreneurs — the salaried investors — are used to the stability of monthly salary credits and are psychologically conditioned for consistency and certainty. When faced with the uncertainty and inconsistency of early-stage business revenues, they tend to withdraw quickly.

Since their salaries come as a result of their time and effort, not monetary investment, they try to replicate that mindset in business. Instead of hiring people for basic operations, they end up doing everything themselves — replying to customer messages, handling operations, and eventually burning out.

This often leads to frustration and, ultimately, quitting.

Let’s take an analogy to understand this.

Suppose I want to build a resort, but I don’t have enough money right now. I decide to start small — say, a two-star hotel. But instead of hiring labourers, I buy sand, cement, and stone chips myself and begin learning civil engineering to build it on my own.

Does that make sense? Of course not.

Then how can the same approach work when building a business? That’s the biggest mistake early-stage entrepreneurs make.

So, What’s the Solution?

First, ask yourself — Are you truly ready to invest money?

In our analogy, if a two-star hotel costs ₹10 lakhs but you only want to risk ₹2 lakhs, then start smaller. But whatever you decide, ensure you have the resources to execute immediately, without depending solely on your time and effort.

Next, comes the most important step — testing your assumptions.

Every business idea is based on certain assumptions. If those assumptions are wrong, the entire business plan collapses — just like a building with a weak foundation.

Your idea might seem perfect in theory — a product or service you believe people will love. But that’s just an assumption until validated.

Instead of building the full product first, use part of your initial investment to test the idea.

  • If the feedback is positive, go ahead and build or deliver the product/service.
  • If not, it’s time to rethink and realign your assumptions.

This is where most first-generation entrepreneurs or salaried professionals aspiring for a side gig go wrong.

Remember — business success depends more on common sense and practical thinking than on fancy technical skills.

As we’ve seen, success in business or side ventures isn’t reserved for the highly technical or the overly analytical — it’s about aligning your skills, mindset, and resources in the right direction. Once you start viewing opportunities through a lens of practicality rather than perfection, every idea begins to make more sense and every step feels more achievable. This mindset shift is the real starting point for any financial or entrepreneurial journey.

One book that truly changed my perspective is “The Lean Startup” by Eric Ries — an excellent read for anyone wanting to understand how startups should actually be approached.

As a finance professional, I often interact with aspiring investors exploring new avenues for income, and I believe this article can help clear some of the clouds so the sun of clarity can shine through.

Final Thoughts

If you’re facing a similar dilemma and need someone to talk to, feel free to email me at bansalmanish30003@gmail.com.

Follow my blog to stay updated — my next article will discuss the “Starter’s Dilemma” — how to choose the right product or service, and how to identify your own incoherent skills and strengths before starting out.

Disclaimer

I do not provide investment advice for stocks, shares, or bonds. My purpose is purely educational — to share experiences, help individuals identify mistakes, take corrective action, and realign their strategies to achieve long-term success.

Take Control of Your Finances Today!

If you want to plan your finances effectively and take actionable steps that lead to real, measurable results, I can help. From budgeting and accounting to evaluating the feasibility of your financial plans, we’ll work together to set clear goals and achieve them.

📧 Email: bansalmanish30003@gmail.com
📞 Call/WhatsApp: 7003426212

Let’s turn your financial goals into reality—reach out and get started!

About the Author:
Manish is a Chartered Accountant by profession and a passionate writer who loves exploring human behavior, finance, and the intersection of professional life with personal growth. Through his blogs, he shares practical insights drawn from real-world experience to inspire working professionals toward financial and personal independence.
© 2025 Manish. All rights reserved.

Saturday, September 20, 2025

Automating Trades with a Simple Moving Average Strategy

Automating Trades with a Simple Moving Average Strategy

Share trading is fast emerging as one of the most sought-after alternatives for generating passive income. While many believe that trading requires full-time commitment, advancements in technology have changed this perception. With the rise of automation and scripting languages like Python, even part-time traders can automate their strategies efficiently.

In fact, most brokerage houses now encourage automation. It reduces emotional decision-making and ensures that trades are executed purely on predefined logic and indicators. To support this, brokers provide APIs with real-time quotes, along with detailed documentation that allows traders to build their own automated systems.

Today, we’ll walk through a very simple and crude trading strategy based on moving averages. We’ll also look at how Python can be used to automate buy, sell, and exit decisions, along with a visualization of the signals.


Step 1: Fetching Data from Broker API

Data from broker APIs usually comes in a complex dictionary or JSON format. This raw data needs to be transformed into a structured format like a DataFrame (using pandas) or written into a CSV file for further calculations.

import pandas as pd

# Example API response (simplified)
data = [
    {"timestamp": "2025-09-21 09:15:00", "price": 24500},
    {"timestamp": "2025-09-21 09:16:00", "price": 24520},
    {"timestamp": "2025-09-21 09:17:00", "price": 24480}
]

# Convert to DataFrame
df = pd.DataFrame(data)
df["timestamp"] = pd.to_datetime(df["timestamp"])
df.set_index("timestamp", inplace=True)

print(df.head())

Step 2: Calculating Moving Averages

For this strategy, we’ll calculate two moving averages:

  • 30-period Moving Average (fast MA)
  • 50-period Moving Average (slow MA)

When the 30-period MA crosses above the 50-period MA, we take a buy position. When the 30-period MA falls below the 50-period MA, we take a sell position.

# Calculate moving averages
df["MA30"] = df["price"].rolling(window=30).mean()
df["MA50"] = df["price"].rolling(window=50).mean()

# Generate signals
df["signal"] = 0
df.loc[df["MA30"] > df["MA50"], "signal"] = 1  # Buy
df.loc[df["MA30"] < df["MA50"], "signal"] = -1 # Sell

Step 3: Visualizing Buy/Sell Signals

A chart makes it easier to see where the strategy would buy and sell.

import matplotlib.pyplot as plt

plt.figure(figsize=(12,6))

# Plot price and moving averages
plt.plot(df.index, df["price"], label="Price", alpha=0.7)
plt.plot(df.index, df["MA30"], label="30-period MA", color="green")
plt.plot(df.index, df["MA50"], label="50-period MA", color="red")

# Mark buy signals
plt.scatter(df.index[df["signal"] == 1],
            df["price"][df["signal"] == 1],
            label="Buy", marker="^", color="blue", s=100)

# Mark sell signals
plt.scatter(df.index[df["signal"] == -1],
            df["price"][df["signal"] == -1],
            label="Sell", marker="v", color="black", s=100)

plt.title("Moving Average Strategy - Buy/Sell Signals")
plt.xlabel("Time")
plt.ylabel("Price")
plt.legend()
plt.grid(True)
plt.show()

Step 4: Trade Management

Once we have signals, we need to manage open trades:

  • Stop Loss Check: If price hits the stop loss, exit immediately.
  • Profit Booking: If price meets target profit, square off the trade.
  • End of Day Exit: At 03:20 PM (10 minutes before market close), exit all open trades to avoid overnight risk.

This ensures that the system runs independently without manual intervention.


Step 5: Testing the Strategy

It is always advisable to start with paper trading before deploying the strategy live. Paper trading allows you to validate your logic, fine-tune stop loss/profit rules, and check if the signals align with your expectations. Once tested, the system can be connected to broker APIs for live trading.


Conclusion

This was a basic introduction to moving average-based trade automation. The aim here is not to build the perfect strategy, but to kickstart our series on trading automation.

In upcoming posts, we’ll move towards more advanced strategies such as calculating Option Greeks in Python and using them for decision-making in options trading.

If you’d like to get your trades automated or need guidance in building your own trading strategy, feel free to reach out at 7003426212 for support.

Tuesday, July 1, 2025

Understanding Put-Call Parity: The Most Ignored Yet Powerful Concept in Option Pricing

Understanding Put-Call Parity

Well! Today’s topic of discussion is put-call parity, and I know many of you landing on this page would have heard or known about it earlier. You might be wondering what good it will bring to spend the next 10 minutes on this article—but believe me, starting from the definition (which, if you are already aware of, feel free to skip), this article is going to cover:

  • How to use this parity to estimate the direction of the stock,
  • How to apply it when making trading decisions,
  • And clear some of the fundamental misconceptions people have about option pricing and the economics that work behind it.

So, let’s try to understand this powerful, yet highly ignored, concept in a few simple steps.

First Things First…

What is a Call and Put?

(For the newborns who want to understand the basics; for the fathers and grandfathers—feel free to scroll past.)

A call option is a financial contract that gives the buyer the right to buy an underlying asset (like a stock) at a specific price (strike price) on or before a certain date (expiration date). Essentially, it's a bet that the price of the asset will increase. It is like booking a pre-order by paying a certain amount (premium in this case) to secure a contract at a future date.

A put option is a contract that gives the buyer the right to sell an underlying asset (like a stock) at a predetermined price (the strike price) on or before a specific date (the expiration date). It is similar to the insurance we pay to protect ourselves from future losses.

I am not going into more details about call and put options. Let me know if you want me to write a more detailed explanation of the fundamentals. Although there is a lot of material online, I am happy to write one if needed.

Next, Let’s Understand What Put-Call Parity Is

Mathematically, put-call parity is defined as:

C + PV(SP) = P + S (for European options & non-dividend-paying stocks)

Where:

  • C = Call value
  • PV(SP) = Present value of the strike price
  • P = Put value
  • S = Stock price

Let’s try to validate a very important fact check over here related to the price of call and put. Let's consider an ATM call and put of a stock with a 1-year expiration and a current price of x.

We know that the present value of x will be less than x by the factor of the interest rate i.e. PV(SP) < S for ATM options. Therefore, to balance the equation, call premium will always be higher than put premium.

Most traders have a misconception that puts trade higher than calls—but fundamentally, that’s incorrect, as the call always bears the weight of interest, the most ignored Greek in option pricing: Rho.

Let’s understand this with an example:

Consider a stock with a current price of INR 1000. Let’s take the 1-year expiration call and put at ATM (i.e., strike price = 1000).

Let’s assume the present value of strike price INR 1000 = INR 900, so now the equation becomes:

C + 900 = P + 1000
=> C - P = 1000 - 900
=> C - P = 100

Therefore, we can see that the price of the call will always be higher than the put by the factor of interest (Rho).

Let’s consider a trader who anticipates that the stock will rise in one year. To hold the stock, he would have to invest INR 1000 for one year. His interest cost on capital, let’s say at 10%, would be INR 100. Since he is not investing INR 1000 now but still getting the same right as that of a buyer, his notional interest cost is 100, which gets added to the call, and that’s the reason why the call is priced higher by 100 in comparison to the put.

Now Let’s Derive a Simplified Equation (with Interest Component)

Call + Strike = Put + Stock + Interest
=> Call = Stock – Strike + Put + Interest
(So, in our example above where stock and strike for ATM call are same: Call = Put + Interest)

=> Put = Strike – Stock + Call – Interest

I don’t want to confuse you—but if you want to be a pro, then you should also know how the price reacts with dividends.

Dividends are payments made to the holder of the stock on the record date. Option holders do not receive dividends, so for a dividend-paying stock, the amount of the dividend must be adjusted from the stock price. So, the new equation for call becomes:

Call = (Stock – Dividend) - Strike + Put + Interest
Put = Strike – (Stock – Dividend) + Call – Interest

Now the Real Kick: How to Use This Parity to Predict Stock Movement

Below is the table for a stock of an Indian company listed on NSE. The first column is the strike price with 1-month expiry starting from 1490 to 1560, and the current price is 1528.80. This includes all three types of calls: ITM, ATM, and OTM.

Strike Price Stock Price Call Value Put Value Interest Rate (7.3%/12) Theoretical Call Price (put-call parity) Theoretical Put Price (put-call parity) Difference from Actual Price (Call)
14901528.856.7514.90.613%63.068.5910%
15001528.849.6517.750.613%55.9111.4911%
15101528.843.0520.950.613%49.1114.8912%
15201528.836.924.750.613%42.9118.7414%
15301528.831.329.10.613%37.2623.1416%
15401528.826.2534.000.613%32.1628.0918%
15501528.821.839.40.613%27.5633.6421%
15601528.817.845.40.613%23.5639.6424%

Column 3 and 4 have actual values of call and put at the end of the day. Column 5 shows the risk-free interest rate, which is 7.35% annually. Converting it to monthly (as the options are expiring in 30 days), we get the monthly rate:
Interest Rate = (7.35% / 12) = 0.613%

Columns 6 and 7 show the theoretical call and put prices using put-call parity. Let’s calculate the first one for example:

Call = (Stock – Dividend) - Strike + Put + Interest 
     = (1528.80 - 0) – 1490 + 14.90 + (1528.80 * 0.613%) 
     = 63.06

Therefore, the theoretical call price based on put-call parity is 63.06, whereas the actual call price is 56.75, i.e., 10% lower than the theoretical price.

Similar calculation for the put price in column 7 shows that the actual put price is trading higher than the theoretical price.

We can see the difference in actual and theoretical call price in column 8, which shows that the actual price is trading lower than the theoretical price. The price difference increases as the option moves from ITM to OTM, ranging from 10% to 24%.

Hence, we can anticipate that the market is not expecting the stock price to move upward, and hence, calls are trading at a discount from theoretical prices.

Python Code to Scrape NSE Option Chain Data


import requests
import pandas as pd

url = "https://www.nseindia.com/api/option-chain-indices?symbol=NIFTY"
headers = {
    "User-Agent": "Mozilla/5.0"
}

session = requests.Session()
session.headers.update(headers)
session.get("https://www.nseindia.com")

response = session.get(url)
data = response.json()
underlying = data['records']['underlyingValue']
interest_rate = 0.00613  # Monthly rate

records = []
for item in data['records']['data']:
    if item.get('CE') and item.get('PE'):
        strike = item['strikePrice']
        call_price = item['CE']['lastPrice']
        put_price = item['PE']['lastPrice']
        theo_call = underlying - strike + put_price + (underlying * interest_rate)
        theo_put = strike - underlying + call_price - (underlying * interest_rate)
        records.append({
            "Strike Price": strike,
            "Call Price": call_price,
            "Put Price": put_price,
            "Theoretical Call": round(theo_call, 2),
            "Theoretical Put": round(theo_put, 2)
        })

df = pd.DataFrame(records)
print(df.head())

Conclusion

Put-call parity is one of the most powerful tools in options trading, and yet it remains underused and often misunderstood. Understanding this parity helps you spot mispriced options, predict market sentiment, and avoid costly misconceptions, like assuming puts always cost more than calls.

Disclaimer

This article is purely for educational purposes and does not constitute investment advice or a recommendation to trade. Options trading involves substantial risk, and it is important to consult a financial advisor before making any trading decisions.

Sunday, August 4, 2024

Predicting Stock Prices: The Surprising Accuracy and Hidden Power of Linear Regression

Introduction to Linear Regression

Linear regression is one of the most fundamental and widely used statistical techniques in data analysis and machine learning. At its core, linear regression aims to model the relationship between a dependent variable and one or more independent variables by fitting a linear equation to observed data.

Mathematically, a simple linear regression model can be represented as:

y = β0 + β1x + ε

Where:

·       y is the dependent variable.

·       x is the independent variable.

·       β0 is the y-intercept.

·       β1 is the slope of the line.

·       ε is the error term.

In a multiple linear regression scenario, the equation expands to:

y = β0 + β1x1 + β2x2 + .......... + βnxn + ε

Where x1, x2, ..., xn are multiple independent variables.

The goal of linear regression is to determine the values of β0 and β1 (or β1, β2, ..., βn in the case of multiple regression) that minimize the sum of squared errors between the predicted values and the actual values.

 

Applications of Linear Regression

Linear regression is a versatile tool used in various fields to predict outcomes and analyze trends. Some of the key areas where linear regression is applied include:

1. Economics: Forecasting economic indicators such as GDP, unemployment rates, and inflation.

2. Finance: Modeling relationships between financial metrics, such as risk and return.

3. Healthcare: Predicting patient outcomes based on medical histories and other factors.

4. Marketing: Estimating the impact of advertising spend on sales.

5. Real Estate: Valuing properties based on features like location, size, and age.

6. Environmental Science: Assessing the impact of environmental variables on climate change.

 

Linear Regression in Stock Market Analysis

In the realm of stock market analysis, linear regression is a powerful tool for predicting stock prices and understanding market trends. Analysts use historical price data and various financial indicators to build regression models that can forecast future stock prices.

 

How Linear Regression is Used in the Stock Market

1. Trend Analysis: By examining the relationship between time and stock prices, analysts can identify long-term trends and potential turning points.

2. Price Prediction: Using historical data, analysts can predict future stock prices by modeling the relationship between a stock's past performance and various market factors.

3. Risk Management: Linear regression helps in assessing the volatility of stock returns, aiding in the development of risk management strategies.

4. Portfolio Optimization: By analyzing the relationships between different stocks, investors can optimize their portfolios for better returns.


Example: Using Python to Predict Stock Prices with Linear Regression

Let's dive into a practical example where we pull data from the National Stock Exchange (NSE) of India and use linear regression to predict stock prices.


Conclusion

Linear regression is an invaluable tool for predicting stock prices and analyzing market trends. It provides a straightforward yet powerful approach to understanding the relationships between various market factors and stock performance. While time series analysis is a widely used method in predicting stock prices, we cannot overlook the importance of other machine learning models, which offer diverse perspectives and can enhance predictive accuracy.

Moreover, linear regression can be applied to momentum indicators such as moving averages and relative strength indices (RSI) to forecast stock prices further. These indicators help identify the strength and direction of market trends, providing additional insights into future price movements.

In the ever-evolving landscape of stock market analysis, machine learning has brought new momentum and perspective, enabling analysts to make more informed decisions and optimize their investment strategies.

 

Thank you for taking the time to read this post. If you enjoyed the content and found it useful, please share it with others and follow my blog for more insightful articles on data analysis and machine learning. Happy investing🤑💲🤑!


Sunday, July 7, 2024

Amazing Insights: How Open Interest Can Wow Your Stock Market Moves

With the growing number of participants in the stock market, not just in India and the US but globally, there is an urgent need for investors and traders to make informed decisions promptly. This is especially important for retail investors, whose investment decisions are often influenced by unreliable tips based on loose sentiments. Therefore, it is crucial to validate these tips using fundamental and technical analysis.

Today, we will discuss using open interest to understand price trends, a topic many traders and investors find challenging. We will explore what open interest is, how it can be used in daily trading, and provide real-time examples to illustrate its application.

Firstly, open interest can be utilized by both equity and futures traders to predict underlying price trends. Although it primarily applies to futures markets, its insights are valuable to all traders. Open interest provides a third dimension to forecasts, complementing price and volume analysis.


What is Open Interest?
Open interest is the total number of outstanding or unliquidated contracts at the end of the day. Each contract involves both a buyer and a seller, who together create the contract. Open interest represents these outstanding contracts held by market participants. An increase or decrease in open interest indicates a corresponding increase or decrease in the number of contracts, reflecting the market's activity.


How change in Open Interest happens?
Every time a trade happens in the market, the open interest is affected in one of three ways: it increases, decreases, or remains unchanged. These scenarios can be summarized in the table below:

Buyer

Seller

Change in Open Interest

Enters new long

Enters new short

Increases

Enters new long

Exits old long

No change

Exits old short

Enters new short

No change

Exits old short

Exits old short

Decreases

Increase in Open Interest: Both the buyer and seller are initiating new contracts, leading to an increase in open interest.

No Change in Open Interest: One party (either the buyer or seller) is entering a new contract while the other is exiting an old position, resulting in no net change in the number of contracts.

Decrease in Open Interest: Both the buyer and seller are exiting their old positions, causing open interest to decrease.

To summarize:
- If both the buyer and seller initiate a new contract, open interest will increase.
- If both the buyer and seller liquidate an old position, open interest will decline.
- If one party initiates a new position while the other liquidates an old position, open interest will remain unchanged.



How to read or analyze change in Open Interest?
Although open interest can be used in isolation with price, analysts usually incorporate volume with open interest to analyze the market. Below is a table that outlines different scenarios and the resulting market moves:

Price

Volume

Open Interest

Market

Increasing

Increasing

Increasing

Continues increasing

Increasing

Declining

Declining

Reversal i.e. market to decline

Declining

Increasing

Increasing

Continues declining

Declining

Declining

Declining

Reversal i.e. market to rise

 

If both open interest and volume increase, it indicates the continuation of the current trend. If both open interest and volume decline, it indicates a reversal of the current trend.

Below is the Nifty 50 daily close price vs Open Interest chart. Nifty 50 is plotted through a line chart of the right axis and Open Interest as a bar chart on the left axis.

In the below chart we can see that the price of Nifty increased from 22700 to 23400 between 31st May and 3rd June but Open Interest bar shows light green color i.e. short covering and not long buildup. This indicates the second scenario in the above table. The market declined on the very next day to 22000 with fresh shorts being building up. However, the markets started recovering and we can see short covering on the next day. On 6th there is strong long buildup i.e. first scenario from the above table. As we can see from the chart that market continues to trend in the upward direction after that.

Courtesy: https://web.sensibull.com/open-interest/fut-oi-vs-time?tradingsymbol=NIFTY

Below is the chart of Bitcoin/TetherUS, we can see that on May 5th (marked using arrow) the price declined with increasing volume and increasing Open Interest i.e. third scenario from the above table indicating continuation of declining trend and that is what happened in subsequent trading session.

Similarly, we can also see that price on May 10 and with increasing volume and open interest leading a slight uptrend in the underlying.

Courtesy: https://web.sensibull.com/open-interest/fut-oi-vs-time?tradingsymbol=NIFTY

So, to conclude this is how we can use Open Interest with volume and price to predict market trend. Analysts complement open interest with some momentum indicators like RSI & Stochastics to get an understand of oversold or overbought position of the underlying but for now I will reserve this topic for a later discussion.

 

 

 

How a Chartered Accountant Built a Manufacturing ERP with AI

Skip to article BUILDING A MANUFACTURING ERP WITH AI · PART 1 OF 15 How I Built a Manufacturing ERP with AI—One Weekend at a Time ...