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.

 

 

 

Sunday, June 23, 2024

How to Generate Continuous Futures Contracts from NSE Data with nselib

 

In today's world, stock trading has become a common side hustle, and the credit goes to the exponential pace of digitalization, which has made it incredibly easy to step into the fascinating realm of stock trading. As of March 2024, there are close to 15.1 crore Demat Accounts, which is roughly ten percent of the total population. This percentage nearly doubles if we exclude those under 18 and over 60 years of age. 

Nearly 80 percent of global trading volume can be attributed to the volumes in Futures and Options (F&O) from NSE & BSE, a trend that is not entirely mysterious. With the advent of Technology Revolution, primarily fueled by data as the new oil, has introduced High-Frequency Trading (HFT) algorithms, machine learning, and artificial intelligence, ushering in an era of robotic traders into the market.  


Challenges in Data Acquisition 

While we now understand the use of data for informed decision-making, obtaining the right set of data in the right format is not always straightforward. The integration of advanced technologies and the sheer volume of available data can pose challenges for even the most experienced traders and analysts.

Continuing with our discussion on the integration of advanced technologies in stock trading, today we will delve into how to get price volume data for NSE listed stocks using Python. We'll explore the available libraries, their documentation, and, most importantly, how to prepare this data for model building.

To begin with, several libraries can help us fetch and manipulate stock data in Python. Among the most popular are yfinancenselib, nsetools etc. These libraries provide comprehensive documentation and are user-friendly, making them ideal for both beginners and seasoned traders.

Link to Library Documentation

·       nselib Documentation

·       yfinance Documentation

·       nsetools Documentation

 

Installing Required Library

 

We'll start by installing and importing these libraries. The nselib library, for example, can be installed using pip.



Importing Libraries and Fetching Data

 

Once installed, you can easily download the price and volume data from any NSE stock. Here’s a simple example to get started with SBI data.



Example Output: DataFrame Structure 

The output will provide you with a DataFrame containing columns like ‘Open’, ‘High’, ‘Low’, ‘Close’, ‘AveragePrice’ etc.

Embracing Challenge: Creating Continuous Contracts 

Continuing from our previous discussion, so far, so good. But let's suppose I want to build a model using derivative future data. The problem with this is that in our DataFrame, we will have at least three contracts running on any given day. For instance, if you filter the date to 01-05-2024, you will see three rows corresponding to the May, June, and July contracts. This is a common problem encountered by any analyst when attempting to build a model using futures data. 

This issue is also discussed in the book *Technical Analysis of the Financial Markets* by John J. Murphy, who explains how analysts create continuation charts for futures. The technique most commonly employed is to link a number of contracts together to provide continuity. When one contract expires, another one is used. However, this is easier said than done, especially when dealing with a large dataset spanning, say, the last ten years. Manually selecting contracts becomes very difficult, especially when shifting from the current contract to the next. 

For example, in May, the future contract for May expired on the 30th. Therefore, until the 30th of May, the contract to be used is the May expiring contract, but the next trading day will not have May contracts. Thus, the 31st of May has to be tagged to the June contract. Essentially, there are two key tasks that need to be accomplished: 

  1. Creating a continuous price data series using the most recent contract.
  2. Removing all other data that pertains to far-month contracts. 


Approach to Creating Continuous Contracts 

To create a continuous contract DataFrame using the approach described, follow these steps. We'll extract the necessary information from the `TIMESTAMP` and `EXPIRY_DT` columns, perform the required calculations, and filter the data to obtain the continuous futures contracts.

Step-by-Step Approach 

Extracting Months and Years: We extract the month and year from the `TIMESTAMP` and `EXPIRY_DT` columns and create new columns `TIMESTAMP_Year`, `TIMESTAMP_Month`, `EXPIRY_Year`, and `EXPIRY_Month’.


 

Sorting Data: The DataFrame is sorted by `TIMESTAMP` to ensure chronological order.


 

Creating Cumulative Month Columns: We create `TIMESTAMP_Month_Cum` and `EXPIRY_Month_Cum` columns by converting the year and month into a cumulative month count (years multiplied by 12 plus months).


 

Calculating Month Difference: The `Month_diff` column is calculated as the difference between ` EXPIRY_Month_Cum` and ` TIMESTAMP_Month_Cum. Generating Month_diff_list: Month_diff_list` is created by grouping the DataFrame by `TIMESTAMP` and transforming the `Month_diff` values into lists for each date.


 

Creating Near_Month Column: The `Near_Month` column is calculated by subtracting the minimum value of `Month_diff_list` from each value in `Month_diff.


 

Filtering for Continuous Contracts: The DataFrame is filtered to keep only the rows where `Near_Month` is equal to 0, providing the continuous futures contracts.


This approach ensures that the futures data is continuous and suitable for building models, addressing the common challenge of dealing with multiple active contracts for different expiration dates.


Visualization of SBIN Continuous Chart 

Below is the visualization of SBIN's continuous futures contract chart from 2015 to 2024:

Modeling Predictive Analytics 

By employing the logic and techniques discussed, we have successfully created a continuous futures contract DataFrame, which forms a robust foundation for building predictive models. 

In the next phase of this project, I will be using machine learning algorithms such as Random Forest and Artificial Neural Networks (ANN) to predict the next day's price. These models can help in formulating strategies like "buy today, sell tomorrow" or "sell today, buy tomorrow," potentially offering significant trading advantages. 

Stay tuned for detailed insights into the modeling process, including data preprocessing steps, feature engineering, model training, evaluation, and the implementation of these trading strategies. We will also explore the performance metrics of these models and their real-world applicability.

 

Thank you for following along. Make sure to subscribe and keep following the blog for more in-depth analysis and updates on the latest in stock trading and machine learning. Your feedback and questions are always welcome, as they help in refining and enriching the content. Together, let's dive deeper into the fascinating world of stock trading with data science.

 

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 ...