Friday, August 7, 2026

How a Chartered Accountant Built a Manufacturing ERP with AI

BUILDING A MANUFACTURING ERP WITH AI · PART 1 OF 15

How I Built a Manufacturing ERP with AI—One Weekend at a Time

I am a Chartered Accountant, not a professional software engineer. What began as a weekend learning project gradually became an extensive Flask ERP covering production, inventory, labour, sales, receivables, costing, dashboards, security and audit-oriented controls.

AI for Accountants Manufacturing ERP Flask & Python Business Process Design
How I built a manufacturing ERP with AI as a weekend learning project
A weekend learning project that combined accounting knowledge, business-process design and AI-assisted development.
The honest version of this story: AI helped me write, explain and debug a large amount of code. It did not understand my business automatically, make every architectural decision correctly, or remove my responsibility to test the system. I remained responsible for the process logic, the data, the controls and the final integration.

A few months ago, I did not sit down with a plan to build a full manufacturing ERP. I simply wanted to learn how modern AI tools could help me convert business knowledge into working software. I started experimenting on weekends, one feature at a time. The project was initially meant to be a practical learning exercise. Then it refused to remain small.

A basic item master led to inventory. Inventory led to purchase receipts. Purchase receipts raised questions about valuation. Production required recipes, bills of material, material consumption, finished-goods output and reversals. Sales required customer purchase orders, dispatches and invoices. Invoices were not enough, because real collection tracking also needed receiving notes, bill submissions, deductions, cash receipts and outstanding balances.

Labour introduced another layer: daily wages, piece-rate work, contractor billing, production posting and cost analysis. As more transactions became connected, dashboards became necessary. Once different users could access the application, login alone was insufficient; the ERP needed roles, permissions, protected actions, safe error handling and an audit-friendly design.

What began as a weekend experiment eventually grew into an extensive, production-oriented business application. The current predeployment build contains roughly 20,000 lines of Python, more than 100 HTML templates, 55 database migrations and dozens of connected business tables. Those numbers do not prove that software is good, but they show how far the project travelled from its modest beginning.

A Weekend Learning Project That Kept Growing

I built the ERP alongside my regular professional responsibilities. Most of the work happened during weekends and spare hours. That shaped the way I developed it. I could not disappear for six months to study computer science first and begin the project only after I felt “ready.” I had to learn the concepts when the application demanded them.

When I needed to store related records, I learned database relationships. When changing the database structure became risky, I learned migrations. When route files became difficult to manage, I learned about blueprints and services. When one user should not be able to perform another user’s work, I learned role-based access control. When the application moved closer to deployment, I had to think about environment variables, secure cookies, CSRF protection, error logs, WSGI servers and backups.

This was not the clean, linear path described in many programming courses. I learned in loops: build, fail, understand, correct, test and rebuild. Sometimes AI gave me a useful implementation immediately. At other times, it produced code that looked convincing but did not fit the existing data model or failed under a real business condition.

Early BOM and recipe screen from the manufacturing ERP
An early recipe screen used to define input materials, quantities, units and scrap while I was learning Flask.
I did not wait until I had learned everything required to build an ERP. I allowed the ERP to show me what I needed to learn next.

The Advantage I Already Had Was Not Coding

I began with limited programming knowledge, but I was not starting from zero in the area that matters most for business software: understanding processes, records, controls and decisions.

As a Chartered Accountant, I am trained to ask questions such as:

  • What is the source document for this transaction?
  • When should the transaction be recognised?
  • What changes in quantity, value, cost or liability?
  • Who can create, approve, reverse or cancel it?
  • What information will management need later?
  • How can the transaction be reconciled?
  • What happens when the normal process fails?

These questions are as relevant to ERP design as they are to accounting and audit. A developer can build a technically correct form, but someone must still define what the form means, which data it should capture, how it affects other records and what decisions should eventually emerge from it.

Finance professionals often underestimate how much system-design knowledge they already possess. We understand document flows, approvals, reconciliations, exception reporting, costing, cash flow, ageing, audit trails and management information. We may not initially know how to express those concepts through Python classes or database relationships, but we understand why the concepts exist.

A principle that guided the project

Data should not be collected merely because a form can capture it. Every important field should support a transaction, a control, a reconciliation, an analysis or a future decision.

Why I Chose to Learn Through a Manufacturing ERP

I could have learned Flask by building a to-do list or a simple expense tracker. Those are useful exercises, but they would not have tested the skill I was most interested in: turning interconnected business processes into one reliable flow of data.

Manufacturing is a particularly rich problem because the same transaction can affect many parts of the business. Receiving raw material changes stock quantity and inventory value. Production consumes multiple inputs and creates one or more outputs. Labour adds cost and operational context. Dispatch reduces finished-goods stock and begins a customer collection cycle. A payment may include tax deducted at source, liquidated damages or other deductions rather than a simple one-to-one settlement.

The real challenge is not creating a separate page for each activity. It is ensuring that all those activities describe the same business reality.

That made an ERP the ideal learning project. It forced me to combine accounting logic, operational logic, database design, user experience, security and analytics. Each new module exposed an assumption in an earlier module. The application became a practical lesson in how a business is connected.

What the Project Eventually Became

The ERP now records and connects a broad set of manufacturing and financial activities. The exact details will be explained throughout this series, but the current application includes the following major areas.

Masters & Setup

Items, finished goods, recipes, production stages, locations, vendors, customers, transporters, destinations, labourers, contractors and piece rates.

Inventory

Opening stock, purchase receipts, stock adjustments, inventory ledger, quantity drill-downs, weighted-average costing and material movement.

Production

BOM-driven material consumption, finished-goods output, by-products or scrap, production entries, costing and reversal controls.

Order to Cash

Customer purchase orders, dispatch and sales invoices, receiving notes, bill submissions, payment receipts and outstanding receivables.

Labour

Daily-wage sheets, hours worked, piece-rate production, approvals, contractor billing, payment controls and labour analytics.

Job Work

Material issued outside the factory, vendor-held balances, partial receipts, conversion charges, scrap return and job-work ledgers.

Dashboards

Receivables, labour cost, raw-material consumption, production, inventory value, pending orders and management alerts.

Controls & Security

Authentication, password controls, user management, role-based access, protected actions, logging, safe errors and production hardening.

Recipe Master with highlighted modular ERP sidebar
The Recipe Master and highlighted sidebar show how the project grew from a single form into a modular ERP.

I describe it as production-oriented rather than declaring it “perfect” or “finished.” A serious business application is never complete merely because its screens work. Deployment, backup, recovery, monitoring, security review, user training, data migration and continuous maintenance are separate responsibilities. This project is reaching that stage now.

How AI Became My Development Partner

I used AI tools such as ChatGPT and Kimi K3, along with other coding assistants where useful. Their biggest contribution was not one magical prompt that generated an ERP. Their value came from thousands of smaller interactions.

AI helped me:

  • translate a business rule into a possible database and route design;
  • explain unfamiliar Flask, SQLAlchemy, HTML, JavaScript and deployment concepts;
  • generate a first version of repetitive code;
  • trace errors across models, routes, templates and services;
  • compare implementation alternatives;
  • write migrations and tests;
  • review code for missing validations or unsafe actions; and
  • help me understand why a solution failed.

But AI did not act like an autonomous software company. It did not retain perfect knowledge of the entire project. It sometimes invented field names, assumed relationships that did not exist, duplicated logic, placed code in the wrong layer or solved the visible error while creating a hidden accounting problem.

The quality of the result depended heavily on the quality of the context I provided. A vague request such as “build a labour module” was far less useful than a structured explanation of worker types, wage rules, approval stages, piece-rate allocation, production impact, cancellation behaviour and billing restrictions.

1

Define

Write the business rule and exceptions in plain language.

2

Generate

Ask AI for a focused change using the actual surrounding code.

3

Test

Run the feature and inspect both the screen and database impact.

4

Refine

Correct assumptions, retest edge cases and integrate safely.

What AI generated versus what I owned

AI often generated: code drafts, explanations, queries, migrations, templates, debugging hypotheses and test structures.

I remained responsible for: the business meaning, process design, data relationships, acceptance criteria, testing, integration, security decisions and whether the result was fit to use.

Over time, the relationship changed. In the beginning, I mainly asked AI to write code. Later, I increasingly used it to challenge a design, review a workflow, identify missing edge cases and explain trade-offs. I was not only getting more code; I was learning how to ask better technical questions.

Why the Real Purpose Was Always Data and Decisions

An ERP is often described as software that records transactions. That description is incomplete. Recording is only the first layer. The real value comes when correctly structured data can be converted into timely information and then into action.

1. RecordWhat happened?
2. ReconcileIs the record complete and consistent?
3. AnalyseWhat pattern or exception does it reveal?
4. DecideWhat should management do?
5. PlanWhat is likely to happen next?

This thinking influenced the design of the ERP. Inventory records should not merely show how many units are available; they should support valuation, movement analysis, shortage identification and production planning. Receivables should not merely list invoices; they should account for bill submission, cash received, TDS, liquidated damages, other deductions and ageing. Labour data should not stop at attendance; it should connect hours, production quantities, piece rates, contractor bills and product-level cost analysis.

Dashboards were therefore not added only to make the application look modern. They were created to answer management questions. Which receivables need follow-up? Where is working capital blocked? Is labour cost rising relative to billed value? Which material is not moving? Which orders are delayed? Where could better planning reduce cost or avoid a penalty?

Receivables labour and raw material dashboard collage
Receivables, labour and raw-material dashboards turn transaction records into management information.

This is where I believe finance professionals can make a distinctive contribution to technology. We are used to looking beyond a number and asking where it came from, whether it is reliable, how it should be interpreted and what decision it should influence.

The Difficult Parts Were Not the Screens

A screen can look complete while the underlying business logic is wrong. Some of the hardest questions appeared only after a feature seemed to be working.

Inventory quantity versus inventory value

It was not enough to add and subtract quantities. Purchase receipts, opening stock, production, scrap and adjustments had to affect cost consistently and in the correct sequence.

Production reversal

Deleting an incorrect production record could not simply remove a row. The system had to reverse input consumption and output creation without damaging the audit trail.

Receivable calculation

The unpaid amount was not always invoice value minus cash. TDS, damages and other deductions needed separate treatment and visibility.

Material outside the factory

Job-work material may still belong to the business even when it is physically held by a vendor. Ownership, location, quantity and value needed to remain distinguishable.

Labour and production

An approved labour sheet could create production, but cancellation needed to reverse production while preserving wage and attendance history.

Access and accountability

A login page did not answer who could approve, cancel, delete or administer. Permissions and status-based locks had to reflect responsibilities.

These issues taught me an important lesson: software does not become reliable because the code runs without an error. It becomes reliable when the transaction behaves correctly in normal cases, exceptional cases and reversal cases—and when someone can later understand what happened.

The ERP Records the Past—My Next Goal Is to Help It Plan the Future

The present model focuses on recording and connecting production, inventory, dispatch, billing, receipts, labour and management dashboards. My longer-term interest is to move from transaction processing toward planning and decision support.

The following features are part of the roadmap; they are planned and not presented as completed functionality:

Production Planning

Use customer orders, delivery dates, BOM requirements, available material, current production and capacity constraints to suggest priorities and material needs.

Receivables Forecasting

Apply machine learning to historical customer, invoice, bill-submission and payment patterns to estimate likely receipt dates and collection risk.

AI Insight Assistant

Create a controlled chatbot that can answer authorised business questions, explain dashboard movements and help users explore the data without writing queries.

Forward-Looking Alerts

Move beyond showing what has already happened toward identifying likely shortages, delayed collections, cost pressure and operational bottlenecks.

AI and machine learning can create significant value, but only when the underlying records are sufficiently complete, consistent and meaningful. A forecasting model cannot repair poor transaction discipline. A chatbot cannot produce trustworthy insight if permissions, definitions and source data are unclear.

That is another reason I started with the ERP foundation. Before asking software to predict the future, I wanted it to represent the present accurately.

What This Journey Has Already Taught Me

01

Domain knowledge is a technical asset

Understanding a business process is not separate from software design. It shapes the data model, workflow, validations, reports and controls.

02

AI reduces the entry barrier, not the responsibility

It can accelerate learning and implementation, but the person using the software must still understand what can go wrong.

03

Small, testable changes outperform giant prompts

The project advanced most reliably when I defined one focused rule, supplied the surrounding context and tested the result before continuing.

04

Data design matters more than visual polish

A beautiful dashboard cannot compensate for incomplete, duplicated or incorrectly connected transactions.

05

Reversals reveal whether a process is truly designed

Creating a transaction is usually easier than cancelling or correcting it while preserving quantities, values and history.

06

Security arrives earlier than expected

As soon as more than one person uses a system, identity, authority, safe errors, logs and protected actions become business requirements.

07

Learning through a real problem changes the motivation

Every new technical concept had an immediate purpose. I was not learning migrations, services or permissions for an examination; I needed them to solve a visible problem.

What This 15-Part Series Will Cover

This article is the beginning, not a victory lap. In the remaining parts, I will document the architecture, business rules, mistakes and trade-offs behind the application. I will explain what AI generated, what I had to understand, what failed and what I would design differently today.

  1. Part 1: How I built a manufacturing ERP with AI—one weekend at a time
  2. Part 2: Why I chose a custom ERP as my learning project
  3. Part 3: My practical AI-assisted development workflow
  4. Part 4: Learning Flask through blueprints, services and migrations
  5. Part 5: Designing masters, transactions and ledgers
  6. Part 6: BOM, production and weighted-average inventory costing
  7. Part 7: Customer PO to payment and receivables
  8. Part 8: Job work, partial receipts and vendor-held inventory
  9. Part 9: Daily wages, piece rates and labour-linked production
  10. Part 10: Dashboards that support management decisions
  11. Part 11: Debugging, migrations, testing and technical debt
  12. Part 12: Roles, permissions, security and audit controls
  13. Part 13: Preparing the Flask ERP for production deployment
  14. Part 14: What AI could not decide without business judgement
  15. Part 15: Can non-programmers build serious software with AI?

Key Takeaways

  • I started the ERP as a weekend learning project, not as a claim that I could replace a software team.
  • My Chartered Accountancy background helped me define processes, controls, reconciliations, costs and management information.
  • AI accelerated coding, explanation and debugging, but it frequently needed context, correction and verification.
  • The project grew into connected modules for inventory, production, sales, receivables, job work, labour, dashboards and access control.
  • The next phase is intended to add production planning, receivables forecasting and an authorised AI insight assistant.
  • The most important lesson is that business software begins with clear business meaning—not with code.

Frequently Asked Questions

Did AI build the entire ERP automatically?

No. AI generated and explained a significant amount of code, but I defined the business rules, supplied project context, integrated the changes, tested workflows, corrected assumptions and remained responsible for the result.

Were you already a software developer?

No. I began with basic programming knowledge. I learned Flask, SQLAlchemy, templates, database migrations, testing, permissions and deployment concepts while solving problems in the project.

Is the ERP already a commercial product?

No. It is an extensive learning project and production-oriented application approaching deployment. It still requires the same disciplines that any serious system needs, including security review, backup and recovery, monitoring, maintenance and controlled user adoption.

Can another finance professional build software with AI?

Yes, a finance professional can use AI to learn and build useful applications, especially when the problem is closely related to their domain. The practical scope should match the risk, and critical systems still require proper testing, security, maintenance and professional technical review.

A question for finance and business professionals

Which process in your work still depends on disconnected spreadsheets and repeated manual follow-up?

Map that process before thinking about software: identify the source data, the approvals, the exceptions, the outputs and the decisions it should support. That exercise alone often reveals where automation can create real value.

Editorial disclosure: This article documents a personal learning and development journey. AI tools assisted with coding, explanations, debugging and editorial refinement. The business observations, project decisions and final responsibility remain the author’s.

Technology disclaimer: The article is educational and does not present the application as a ready-made product for every business. ERP implementation, cybersecurity, data protection, taxation and accounting treatments should be evaluated for the relevant organisation and jurisdiction.

© 2026 Manish Kumar Bansal. All rights reserved.

Thursday, June 4, 2026

How to Create a Personal Financial Plan in India (2026) | Complete Step-by-Step Guide

How to Create a Personal Financial Plan: A Complete Step-by-Step Guide for Indians

Many people work hard and earn a decent income, yet they often feel uncertain about their financial future. The reason is simple: earning money and managing money are two different skills.

A personal financial plan acts as a roadmap that helps you organize your income, expenses, savings, investments, insurance, and retirement goals. Whether you are a salaried employee, business owner, freelancer, or professional, having a financial plan helps you make informed decisions and build long-term financial security.

In this guide, we will discuss a practical framework that you can use to create your own financial plan.


Table of Contents

  • Assess Your Current Financial Position
  • Track Your Income and Expenses
  • Build an Emergency Fund
  • Define Financial Goals
  • Insurance Planning
  • Debt Management
  • Investment Planning
  • Tax Planning
  • Net Worth Tracking
  • Annual Review
  • Frequently Asked Questions

Step 1: Assess Your Current Financial Position

Before planning your future, understand where you stand today.

List Your Assets

  • Bank Balances
  • Fixed Deposits
  • Mutual Funds
  • Stocks
  • Bonds, Treasury Bills and Commercial Papers
  • EPF and PPF
  • Rental Real Estate
  • Gold
  • Business Investments

A useful way to think about assets is to focus on assets that generate income or have the potential to generate future cash flows.

For example, your self-occupied home may be valuable, but it generally does not produce cash flow and often involves ongoing maintenance expenses and taxes. On the other hand, a rental property can generate regular income and therefore contributes directly to your financial growth.

This concept was popularized by Robert Kiyosaki in his book Rich Dad Poor Dad, where he explains the importance of acquiring income-producing assets.

Recommended Reading:

  • The Psychology of Money
  • Rich Dad Poor Dad
  • The Intelligent Investor

List Your Liabilities

  • Home Loan
  • Car Loan
  • Personal Loan
  • Credit Card Dues
  • Business Debt

Calculate Your Net Worth

Net Worth = Total Assets – Total Liabilities

This provides a high-level view of your current financial health and income-generating capability.


Step 2: Track Your Income and Expenses

For at least one month, track every source of income and every expense.

Income Sources

  • Salary
  • Business Income
  • Rental Income
  • Dividend Income
  • Interest Income
  • Freelancing Income

Expense Categories

  • Household Expenses
  • EMIs
  • Utilities
  • Insurance Premiums
  • Education
  • Entertainment
  • Travel

Understand Active vs Passive Income

One of the biggest mistakes many salaried individuals make is treating education and upskilling as expenses rather than investments.

Your salary today is often the result of investments made years ago in education, certifications, skills, and professional development.

Consider separating income into:

  • Active Income: Income earned through your direct effort.
  • Passive Income: Income generated through investments or assets.

This analysis often reveals that most people depend heavily on active income while spending very little on activities that can increase future earning power.


Step 3: Build an Emergency Fund

An emergency fund protects you against:

  • Job Loss
  • Medical Emergencies
  • Unexpected Repairs
  • Family Emergencies

Recommended Emergency Fund

  • Salaried Individuals: 6 Months of Expenses
  • Self-Employed Professionals: 12 Months of Expenses

Keep this money in highly liquid instruments such as savings accounts, liquid mutual funds, or short-term fixed deposits.

Without an emergency fund, people often make poor financial decisions under pressure.


Step 4: Define Your Financial Goals

Short-Term Goals (0–3 Years)

  • Vacation
  • Emergency Fund
  • Vehicle Purchase

Medium-Term Goals (3–7 Years)

  • Home Down Payment
  • Children's Education

Long-Term Goals (7+ Years)

  • Retirement
  • Financial Independence
  • Wealth Creation

Each goal should have:

  • Target Amount
  • Target Date
  • Required Monthly Investment

Cash Flow Generating Goals

Most financial planning articles stop at expense-related goals. However, an equally important category is cash-flow-generating goals.

Examples include:

  • Purchasing a rental property
  • Building a dividend portfolio
  • Investing in equity mutual funds
  • Starting a side business
  • Developing professional skills that increase earning potential

The objective is not only to meet future expenses but also to increase future income streams.


Step 5: Ensure Adequate Insurance Coverage

Health Insurance

Protects against rising medical costs.

Term Insurance

Provides financial protection to dependents at a relatively low cost.

Avoid mixing insurance and investment objectives whenever possible.

A pure term insurance policy typically provides significantly higher coverage than traditional investment-linked insurance plans for the same premium.


Step 6: Eliminate High-Interest Debt

Prioritize repayment of:

  • Credit Card Debt
  • Personal Loans

These liabilities often carry interest rates that exceed long-term investment returns.


Step 7: Create an Investment Plan

Your investment allocation should depend on:

  • Financial Goals
  • Risk Tolerance
  • Investment Horizon

Sample Asset Allocation

  • Emergency Fund: 10%
  • Fixed Income: 20%
  • Equity Mutual Funds and Stocks: 60%
  • Gold: 10%

This allocation should be customized based on age, risk appetite, and financial objectives.

For investors seeking a deeper understanding of investing psychology and value investing, The Intelligent Investor remains one of the most respected books ever written on investing.


Step 8: Plan for Taxes

Tax planning should be done throughout the year.

  • Section 80C Investments
  • Health Insurance Deductions
  • NPS Contributions
  • Capital Gains Planning

Effective tax planning can significantly improve long-term investment returns.


Step 9: Monitor Your Net Worth

Review quarterly:

  • Net Worth
  • Investment Portfolio
  • Savings Rate
  • Debt Levels

What gets measured gets managed.


Step 10: Review and Update Annually

Life circumstances change:

  • Marriage
  • Children
  • Career Growth
  • Business Expansion
  • Retirement Planning

Review your financial plan at least once every year.


Conclusion

A personal financial plan is not about predicting the future. It is about preparing for it.

By understanding your current financial position, setting meaningful goals, protecting your family through insurance, investing wisely, and regularly reviewing progress, you can build long-term financial security and financial freedom.

Remember: Financial planning is not a one-time activity. It is a lifelong process.


Frequently Asked Questions (FAQ)

What is a personal financial plan?

A personal financial plan is a structured roadmap that helps an individual manage income, expenses, savings, investments, insurance, taxes, and retirement goals.

How often should I review my financial plan?

At least once every year or whenever a major life event occurs.

Can I create a financial plan without a financial advisor?

Yes. Many people can build a solid financial plan independently. Professional advice may help in more complex situations.

What is the first step in financial planning?

Assessing your current financial position by calculating assets, liabilities, income, expenses, and net worth.

What is the difference between active income and passive income?

Active income requires your direct effort and time, such as salary, consulting fees, or business income. Passive income is generated from assets or investments such as dividends, rental income, royalties, and interest income.

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!

© 2026 Manish Bansal | All Rights Reserved

⚠️ Disclaimer

The information provided in this article is for educational and informational purposes only and should not be considered financial, investment, tax, legal, or professional advice.

Every individual's financial situation, goals, risk tolerance, and circumstances are different. Before making any financial decisions, investments, or purchases of financial products, you should consult a qualified financial advisor, tax professional, or other relevant expert.


© 2026 Manish Bansal | All Rights Reserved

Author: Manish Kumar Bansal

Manish Kumar Bansal is a Chartered Accountant and finance professional with a passion for personal finance, investing, financial planning, and wealth creation. Through his writing, he aims to simplify complex financial concepts and help individuals make informed decisions to achieve their financial goals.

© Manish Kumar Bansal — example code uses numpy and scipy. Install with pip install numpy scipy.

Tuesday, October 28, 2025

10 Most-Used Libraries to Automate Trading and Make Money in the Share Market

10 Most-Used Libraries to Automate Trading and Make Money in the Share Market

In today’s split-second markets, automation is not optional — it’s essential. Robotics and automation are advancing across industries, and trading is no exception: decisions that once took minutes now happen in milliseconds. Even if coding feels new and unfamiliar, learning to automate trading strategies is becoming part of everyday trading practice — enabling faster decisions, consistent execution, and the ability to scale.

Why automate trading today?

Markets are faster, data is larger, and opportunities — especially in derivatives like options — are time-sensitive. Automation helps remove human latency (slow reaction), emotional bias, and manual errors. For intraday straddle strategies and options trading, automation lets you:

  • Detect market regime (trend vs range) in real time using objective rules.
  • Compute Greeks across strikes and expiries instantly to size positions and manage risk.
  • Backtest hundreds of scenarios reliably and iterate quickly.
  • Execute entries, hedges and exits on defined conditions to preserve discipline.

Top 10 Python libraries for automated trading (ranked for intraday option straddles)

Below is a compact, practical ranked list that you can use as a starting toolkit. Each item includes when to use it and a short code snippet.

🏆 1. pandas

Purpose: Data cleaning, manipulation, and analysis
Why you need it: Everything in trading automation starts and ends with structured data — especially for OHLC or tick data.

import pandas as pd

# Load intraday price data
df = pd.read_csv("nifty_15s_data.csv", parse_dates=['datetime'])
df.set_index('datetime', inplace=True)

# Resample to 1-minute candles
df_1m = df.resample('1T').agg({'open':'first', 'high':'max', 'low':'min', 'close':'last'})

⚙️ 2. numpy

Purpose: Fast mathematical computation
Why it matters: Used for array operations while calculating Greeks, returns, or indicators.

import numpy as np

returns = np.log(df_1m['close'] / df_1m['close'].shift(1))
volatility = np.std(returns) * np.sqrt(252)

📈 3. pandas-ta

Purpose: Technical analysis (100+ built-in indicators)
Why you need it: Lightweight and easy to integrate. Perfect for identifying trends vs. ranges.

import pandas_ta as ta

df_1m['ADX'] = ta.adx(df_1m['high'], df_1m['low'], df_1m['close'])['ADX_14']
df_1m['BB_width'] = ta.bbands(df_1m['close'])['BBB_5_2.0'] - ta.bbands(df_1m['close'])['BBL_5_2.0']

🧠 Use ADX < 25 for range-bound; ADX > 25 for trending market.


🧮 4. py_vollib

Purpose: Option pricing and Greeks
Why it matters: Precise computation for Delta, Gamma, Vega, Theta, and Rho.

from py_vollib.black_scholes.greeks.analytical import delta, gamma, vega, theta, rho

S, K, T, r, sigma = 21500, 21500, 0.05, 0.07, 0.18
print("Delta:", delta('c', S, K, T, r, sigma))

🧩 Loop across strikes to compute Greeks for your straddle legs.


📊 5. matplotlib / mplfinance

Purpose: Charting and visualization
Why you need it: Visualize market phases, volatility, or options behavior.

import mplfinance as mpf

mpf.plot(df_1m.tail(100), type='candle', title='NIFTY Intraday', mav=(20,50), volume=True)

💹 6. TA-Lib

Purpose: Professional-grade technical indicators
Why it matters: Offers advanced indicators like MFI, SAR, and CCI.

import talib

df_1m['RSI'] = talib.RSI(df_1m['close'], timeperiod=14)
df_1m['CCI'] = talib.CCI(df_1m['high'], df_1m['low'], df_1m['close'], timeperiod=20)

⚠️ TA-Lib needs C dependencies; use `ta` or `pandas-ta` as alternatives.


💼 7. QuantLib

Purpose: Professional quantitative finance models
Why you need it: Advanced option pricing and volatility surface modeling.

import QuantLib as ql

today = ql.Date.todaysDate()
ql.Settings.instance().evaluationDate = today
option_type = ql.Option.Call
spot = ql.SimpleQuote(21500)
rate = ql.SimpleQuote(0.07)
vol = ql.SimpleQuote(0.18)

💻 8. vectorbt

Purpose: Fast backtesting and signal combination
Why you need it: Lets you test multiple indicators and trading logics at lightning speed.

import vectorbt as vbt

entries = df_1m['ADX'] > 25
exits = df_1m['ADX'] < 20
portfolio = vbt.Portfolio.from_signals(df_1m['close'], entries, exits, size=1)
portfolio.stats()

📊 9. option-greek-pricing

Purpose: Easy Greek computation
Why it matters: Simplified syntax, ideal for beginners.

from option_greek_pricing import Option

opt = Option(S=21500, K=21500, T=0.05, r=0.07, sigma=0.18, option_type='call')
print(opt.greeks())

🧠 10. backtrader

Purpose: Strategy backtesting engine
Why you need it: Test and optimize your entry, exit, and risk logic with real-world simulation.

import backtrader as bt

class MyStrategy(bt.Strategy):
    def next(self):
        if self.data.adx[0] > 25:
            self.buy()
        elif self.data.adx[0] < 20:
            self.sell()

cerebro = bt.Cerebro()
data = bt.feeds.PandasData(dataname=df_1m)
cerebro.adddata(data)
cerebro.addstrategy(MyStrategy)
cerebro.run()

🧩 Recommended Setup Order

StepPurposeLibraries
1️⃣ Data LoadingIngest, resample, cleanpandas, numpy
2️⃣ Market Regime DetectionIdentify trend vs. rangepandas-ta, ta, TA-Lib
3️⃣ Option Pricing & GreeksCompute straddle sensitivitypy_vollib, option-greek-pricing, QuantLib
4️⃣ VisualizationCandlestick & indicator overlaysmatplotlib, mplfinance
5️⃣ BacktestingSimulate your systemvectorbt, backtrader

To understand each library in detail, simply Google the library name and read its official documentation — or explore the numerous tutorials available on YouTube. Explaining every function and capability is beyond the scope of a single post, as each library could easily take multiple articles to cover in depth.

Conclusion — a final thought

Automation is no longer an advanced luxury reserved for quant desks. It’s becoming a practical necessity for traders who want speed, repeatability, and the ability to test ideas at scale. Whether you are starting with pandas & pandas-ta or advancing into QuantLib and vectorbt, building automated pipelines today will let you act on opportunities that are invisible to manual traders. Take a small step — automate one signal, validate it, and iterate. The future of trading rewards the prepared and the automated.

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!

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


Author: Manish Kumar Bansal

Manish is a Chartered Accountant and finance practitioner passionate about trading automation and market analytics. He writes about practical trading automation, options analytics and Python tools for retail traders.

© Manish Kumar Bansal — example code uses numpy and scipy. Install with pip install numpy scipy.

Thursday, October 23, 2025

# Real-Time Option Greeks in Python — Black-Scholes, Implied Volatility & Copy-Ready Code for Retail Traders Real-Time Option Greeks in Python | Black-Scholes Model Explained

Real-Time Option Greeks with Python — Black-Scholes, Implied Volatility & Practical, Copy-Ready Code for Retail Traders

A practical, detailed guide with full explanations, ready-to-copy code blocks and formulas — prepared for Blogger and Jupyter. (Author note at the end.)


In this article I want to explore how trading and decision-making have evolved as technology has accelerated. Execution is easier and data is far more abundant, but decision windows have shrunk to split seconds — far faster than unaided human reflexes. Retail traders who want to stay relevant must learn to define decision logic and automate analysis where appropriate.

I keep all original points and code intact from my draft but cleaned them for grammar, readability and correctness. If you paste the code into a Jupyter notebook, the blocks are ready to run after installing the listed libraries.

Why this matters — data velocity and decision time

Historically, traders observed, thought, acted, and then watched — human cycles that took time. There simply wasn’t the flood of tick-level data we have today. Now, multiple software systems stream quotes every millisecond. Manually processing such volumes is impractical. Programmers write logic that consumes the data and produces actionable signals in real time. That is the new norm.

Consequently, it is very important for every trader — retail or institutional — to be able to define how they want to think through data and which decisions to take based on that logic. Complicated logic and automation have become commonplace, but insightful, real-time information is not always available to retail traders. In this article I focus on how retail option traders can use Python to compute option Greeks in real time.

Scope and assumptions

  • I will not cover how to obtain real-time data here — I have covered data APIs elsewhere. You can use broker or vendor APIs to stream quotes. Once you have that data, this article shows how to calculate Greeks.
  • Tools used: Python (I prefer Jupyter Notebook). Libraries used: numpy, scipy.stats, scipy.optimize, and math.
  • All formulas from the Black-Scholes model and Greek calculations are preserved and formatted so you can copy them into Blogger or your notebooks.

Initial inputs — what you must gather

First things first: you must get market data and put it into a DataFrame (or similar) so you can use it. The initial inputs you need for each option contract are:

  • Spot Price (S) — the latest price of the underlying.
  • Strike Price (K) — the option strike.
  • Time to expiry (T) — in years (use seconds or hours precision for real-time Greeks).
  • Risk-free rate (r) — annualized.
  • Market option price — observed premium (use mid price when possible).
  • Option type — call or put.

Spot price example function

I usually write a small wrapper function to extract the latest traded price (LTP) from the JSON structure returned by a broker or vendor API. The exact fields depend on the provider; below is a simple example that works with a common structure containing exchange_token and ltp.

def get_spot_price(allQuotes, token):
    for quote in allQuotes:
        if quote.get('exchange_token') == token:
            return float(quote.get('ltp', 0))
    return None  # If not found

Whenever I need the spot price, I call this function and pass the list of quotes and the token for the instrument.

Extracting strike (K) from symbol

You can hardcode K (for example K = 25250), but a better approach is to parse it from the display symbol. Assume the display symbol is NIFTY25000CE. You can extract the strike with a simple regex:

import re
display_symbol = "NIFTY25000CE"
K = int(re.findall(r'\d+', display_symbol)[0])
# K == 25000

If you prefer, wrap this into a small function that accepts the display symbol and returns the numeric strike.

Time to expiry (T) — real-time precision

Since we want to calculate Greeks on a real-time basis and capture changes per tick, compute time to expiry with sufficient precision (seconds or hours). One example I use in production is:

Time (T) = hours_until_expiry_thursday() / (251 * 6.25) # Time to expiry in years

This formula is an example; you can adapt it to use exact trading days (commonly 252) or compute exact seconds → years as T = seconds_until_expiry / (365 * 24 * 3600). Use the approach that fits your needs for precision.

Risk-free rate (r)

I usually take a baseline of r = 0.07 (7%). Adjust this based on prevailing short-term government yields or the rate used by your firm.


Theoretical price: Black-Scholes model

One of the fundamental building blocks is the Black-Scholes theoretical price. When you can compute the theoretical price for a given volatility, you can invert that to obtain implied volatility from the market price.

from scipy.stats import norm
import math

def black_scholes_price(S, K, T, r, sigma, option_type):
    d1 = (math.log(S / K) + (r + 0.5 * sigma ** 2) * T) / (sigma * math.sqrt(T))
    d2 = d1 - sigma * math.sqrt(T)
    if option_type == 'call':
        return S * norm.cdf(d1) - K * math.exp(-r * T) * norm.cdf(d2)
    elif option_type == 'put':
        return K * math.exp(-r * T) * norm.cdf(-d2) - S * norm.cdf(-d1)
    else:
        raise ValueError("Invalid option type")

🧩 Function Overview (black_scholes_price)

VariableMeaningExample
SCurrent spot price of the underlying (e.g., NIFTY = 25000)25000
KStrike price of the option25200
TTime to expiry in years (e.g., 7 days → 7/365 ≈ 0.0192)0.02
rRisk-free interest rate (annualized, e.g., 7%)0.07
sigmaVolatility of the underlying (standard deviation of returns)0.15
option_type'call' or 'put''call'

🧠 Step-by-Step Explanation

1️⃣ Compute d1 and d2

d1 = ( ln(S/K) + (r + 0.5·σ²)·T ) / ( σ·√T ) d2 = d1 − σ·√T

These are intermediate variables used in the Black-Scholes formula. They represent how far the current price is from the strike price, measured in standard deviations.

Intuitively:

  • d1 measures the (adjusted) distance between spot and strike after accounting for drift (risk-free rate) and volatility.
  • d2 is used to discount the expected payoff to the present value; it equals d1 − σ√T.

2️⃣ Call option price formula

if option_type == 'call':
    return S * norm.cdf(d1) - K * math.exp(-r * T) * norm.cdf(d2)
C = S·N(d1) − K·e^(−rT)·N(d2)

Where N(·) is the cumulative distribution function (CDF) of the standard normal. Here:

  • S·N(d1) is the present value of the expected payoff if exercised.
  • K·e^(−rT)·N(d2) is the discounted expected payment for exercising.

3️⃣ Put option price formula

elif option_type == 'put':
    return K * math.exp(-r * T) * norm.cdf(-d2) - S * norm.cdf(-d1)
P = K·e^(−rT)·N(−d2) − S·N(−d1)

This is the Black-Scholes price for a put option, using symmetry of the normal distribution.

4️⃣ Error handling

else:
    raise ValueError("Invalid option type")

If someone passes a value other than 'call' or 'put', the function raises an error.

✅ Example calculation

from math import log, sqrt, exp
from scipy.stats import norm
import math

price = black_scholes_price(S=25000, K=25200, T=0.02, r=0.07, sigma=0.15, option_type='call')
print(price)

# Output might be: 210.54

So the theoretical call option price ≈ ₹210.54 (example output).


Finding implied volatility (σ) using Brent's method

Implied volatility is the volatility value that makes the theoretical Black-Scholes price equal to the observed market price. We use a root-finding algorithm to invert the Black-Scholes pricing function. Below is a robust approach using scipy.optimize.brentq.

from scipy.optimize import brentq

def implied_volatility(price, S, K, T, r, option_type):
    try:
        return brentq(
            lambda sigma: black_scholes_price(S, K, T, r, sigma, option_type) - price,
            1e-6, 5.0, maxiter=1000)
    except Exception:
        return 0.0

Detailed explanation of implied_volatility() (line by line)

The goal of this function is to find the implied volatility (σ) — the volatility value that makes the Black-Scholes theoretical price equal to the observed market price.

🧩 Function signature

def implied_volatility(price, S, K, T, r, option_type):

Parameters:

  • price — market premium of the option
  • S — spot price of underlying
  • K — strike price
  • T — time to expiry (in years)
  • r — risk-free rate (annualized)
  • option_type — 'call' or 'put'

⚙️ Core logic

return brentq(
    lambda sigma: black_scholes_price(S, K, T, r, sigma, option_type) - price,
    1e-6, 5.0, maxiter=1000)

Let’s break that down:

  • brentq(...) — Brent's method is a robust root-finding algorithm from scipy.optimize. It finds a value x such that f(x) = 0 given an interval where the function changes sign.
  • Here, we define f(σ) = BlackScholesPrice(σ) − MarketPrice. We are solving for σ such that f(σ) = 0, i.e., theoretical price equals market price.
  • The lambda passed to brentq computes the difference between the Black-Scholes price at σ and the observed market price.
  • 1e-6 to 5.0 is the search range for σ (0.000001 to 500% volatility) — broad enough for practical cases.
  • maxiter=1000 sets a reasonably high iteration limit to allow convergence if possible.

🧯 Error handling

except:
    return 0

If the solver fails (the function does not cross zero in the search interval or the inputs are invalid), the function returns 0.0 instead of raising an error. You can choose to handle this case differently in production (for example, log and skip, or fallback to a numerical approximation).

✅ Summary

In simple words: the function finds implied volatility by adjusting σ until the Black-Scholes price equals the observed market price. If it cannot find a valid σ, it returns a safe default (0.0).

# Example:
iv = implied_volatility(price=150, S=25000, K=25000, T=0.05, r=0.07, option_type='call')
print(iv)
# Might return: 0.12  # i.e., 12% implied volatility

Calculating Greeks — Delta, Gamma, Vega, Theta, Rho

Once we have the implied volatility we compute the main Greeks using Black-Scholes formulas. Below is the full function that returns Delta, Gamma, Vega, Theta and Rho for either calls or puts.

import numpy as np
from scipy.stats import norm

def black_scholes_greeks(S, K, T, r, iv, option_type):
    """
    Calculate Black-Scholes Greeks for Call or Put options.

    Parameters:
    S : float : Spot price
    K : float : Strike price
    T : float : Time to expiration (in years)
    r : float : Risk-free rate (annual)
    iv : float : Implied volatility (as decimal, e.g., 0.2 for 20%)
    option_type : str : 'call' or 'put'

    Returns:
    dict of Greeks: delta, gamma, vega, theta, rho
    """
    d1 = (np.log(S / K) + (r + 0.5 * iv**2) * T) / (iv * np.sqrt(T))
    d2 = d1 - iv * np.sqrt(T)

    if option_type == 'call':
        delta = norm.cdf(d1)
        theta = (-S * norm.pdf(d1) * iv / (2 * np.sqrt(T))
                 - r * K * np.exp(-r * T) * norm.cdf(d2))
        rho = K * T * np.exp(-r * T) * norm.cdf(d2)
    elif option_type == 'put':
        delta = -norm.cdf(-d1)
        theta = (-S * norm.pdf(d1) * iv / (2 * np.sqrt(T))
                 + r * K * np.exp(-r * T) * norm.cdf(-d2))
        rho = -K * T * np.exp(-r * T) * norm.cdf(-d2)
    else:
        raise ValueError("option_type must be 'call' or 'put'")

    gamma = norm.pdf(d1) / (S * iv * np.sqrt(T))
    vega = S * norm.pdf(d1) * np.sqrt(T)

    return {
        'delta': delta,
        'gamma': gamma,
        'vega': vega / 100,   # often expressed per 1% change
        'theta': theta / 365, # per day
        'rho': rho / 100      # per 1% change
    }

🧩 What this function does

This function computes the main Greeks (Δ, Γ, Θ, 𝜈, ρ) for a call or put using the Black-Scholes model. It returns a dictionary with all values adjusted for commonly used units (vega per 1% IV change, theta per day, rho per 1% interest rate change).

📘 Function signature recap

  • S — current spot price
  • K — strike
  • T — time to expiry in years
  • r — risk-free rate (annual)
  • iv — implied volatility (decimal)
  • option_type — 'call' or 'put'

⚙️ Greek formulas & intuition

d1 = ( ln(S/K) + (r + 0.5·σ²)·T ) / ( σ·√T ) d2 = d1 − σ·√T

🔹 For call options

delta = N(d1)
theta = −(S·φ(d1)·σ) / (2·√T) − r·K·e^(−rT)·N(d2)
rho = K·T·e^(−rT)·N(d2)

Interpretation:

  • Δ (Delta) = N(d1) — change in option price per ₹1 change in underlying.
  • Θ (Theta) = negative for calls (time decay), composed of volatility decay and interest-rate discounting.
  • ρ (Rho) — sensitivity to interest rate changes (positive for calls).

🔹 For put options

delta = −N(−d1)
theta = −(S·φ(d1)·σ)/(2·√T) + r·K·e^(−rT)·N(−d2)
rho = −K·T·e^(−rT)·N(−d2)

Interpretation:

  • Δ for puts is negative: puts lose value when the underlying rises.
  • Θ and ρ signs differ slightly from calls — puts can behave differently near expiry depending on moneyness.

⚙️ Common Greeks (both calls and puts)

gamma = φ(d1) / (S·σ·√T)
vega = S·φ(d1)·√T

Where φ(d1) = norm.pdf(d1) is the standard normal probability density function.


Unit adjustments

  • Vega is divided by 100 → expressed per 1% volatility change.
  • Theta is divided by 365 → expressed per day instead of per year.
  • Rho is divided by 100 → expressed per 1% interest rate change.

✅ Example usage

S = 25000    # Spot price
K = 25200    # Strike
T = 7/365    # 7 days to expiry
r = 0.07     # 7% risk-free rate
iv = 0.15    # 15% implied volatility

greeks = black_scholes_greeks(S, K, T, r, iv, 'call')
print(greeks)
# Example output (approx):
# {
#  'delta': 0.43,
#  'gamma': 0.00015,
#  'vega': 0.12,
#  'theta': -6.5,
#  'rho': 0.28
# }

🧠 Intuition

  • Delta = 0.43: Option moves ₹0.43 for every ₹1 move in NIFTY.
  • Gamma = 0.00015: Delta itself changes slowly with price.
  • Vega = 0.12: Option gains ₹0.12 if IV rises by 1%.
  • Theta = −6.5: Option loses ₹6.5 per day (time decay).
  • Rho = 0.28: Option gains ₹0.28 if rates rise by 1%.

Putting it together — real-time pipeline

You can implement a real-time pipeline that repeatedly ingests ticks and computes Greeks per contract. High-level steps:

  1. Stream quotes from your broker or data vendor into your process.
  2. For every tick, parse the data: get S, display symbol → extract K, get option market price, and timestamp.
  3. Calculate precise time to expiry T (include seconds for high precision).
  4. Compute implied volatility using implied_volatility().
  5. Compute Greeks using black_scholes_greeks().
  6. Feed Greeks into your decision logic: hedging, position sizing, risk limits, or automated orders.

I am not discussing any specific trading strategy here; Greeks are inputs — how you use them depends on your experience, risk tolerance, and trading rules.

Practical tips & pitfalls

  • Numerical stability: Very near expiry (T extremely small) can create divisions by zero or overflow. Add guards (e.g., clamp T to a sensible minimum like 1 second → years) to avoid errors.
  • Use midprice: For IV estimation use midprice (bid+ask)/2 instead of last trade, especially for illiquid strikes.
  • Invalid IV: If implied_volatility() returns zero, log the event, skip the contract or apply fallback logic.
  • Performance: Running root-finders for many strikes per second can be expensive. Consider warm starts, approximate IV initial guesses, vectorized techniques, or precomputing an IV surface if you need very high throughput.
  • Data hygiene: Filter stale ticks and outliers to prevent wild IV spikes due to bad data.

Conclusion — the value for retail traders

Option Greeks provide a compact and interpretable summary of how option prices react to environmental changes: underlying price moves, volatility shifts, time decay, and interest-rate moves. By automating IV and Greek calculations in Python, retail traders can move from instinctive trading to a more structured, rules-based approach.

Automation does not replace judgment — it amplifies it. Use the building blocks in this article to:

  • Make faster and more informed decisions based on standardized sensitivities rather than pure intuition.
  • Implement simple risk controls like net delta or vega limits across your book.
  • Monitor intraday dynamics and detect regime shifts in volatility or liquidity.

The code in this article is intentionally simple and copy-friendly. It uses Black-Scholes as a workhorse — simple, fast and well understood. For advanced needs you can incorporate dividends, discrete payouts, or move to local / stochastic volatility models.

If you are already streaming tick data from your broker, paste the code blocks into a Jupyter notebook, adapt the get_spot_price and symbol parsing functions to your vendor’s JSON, and run them in a loop. You will then have real-time Greeks you can hook into your own decision logic.

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!

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


Author: Manish Kumar Bansal

Manish is a Chartered Accountant and finance practitioner passionate about trading automation and market analytics. He writes about practical trading automation, options analytics and Python tools for retail traders.

© Manish Kumar Bansal — example code uses numpy and scipy. Install with pip install numpy scipy.

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