Python for finance: notebooks, pandas and dates
Why analysts add Python to their spreadsheets, how to set up a notebook, and the pandas DataFrame as a programmable spreadsheet, with a SUMIFS and a lookup rebuilt in code step by step. The date handling financial data depends on: day-first Indian dates, indexing by date, resampling daily data to months, and the special sessions, like Diwali's muhurat trading and the Saturday Budget session of February 2025, that break 'markets shut at weekends'; plus exact holding periods for returns, with a calculator.
Facts reviewed Oct 2026
Spreadsheets are perfect for models people read and change by hand. But some jobs outgrow them:
- the data runs to hundreds of thousands of rows;
- the same analysis must be repeated every week;
- you need statistics a spreadsheet struggles with.
For these, Python is the standard tool across banks, funds and fintechs. (Careers in Finance covers why it’s worth learning.) This lesson gets you from zero to a working notebook. The next two load real market data and analyse it.
Why Python
- Repeatable. A script runs the same analysis on new data in seconds, with no copy-paste errors.
- Scalable. Millions of rows are no problem.
- Libraries. pandas for tables, NumPy for maths, matplotlib for charts, statsmodels and scikit-learn for statistics and machine learning.
- Transparent. The code records every step, so others can check your work.
Setting up a notebook
A Jupyter notebook mixes code, results and notes in one document. It’s ideal for analysis. Easy ways to start:
- Google Colab: runs in your browser, with nothing to install.
- Anaconda or pip on your own computer: run
pip install pandas matplotlib jupyter, thenjupyter notebook. - VS Code, with the Python and Jupyter extensions.
The DataFrame: a programmable spreadsheet
A pandas DataFrame is a table with labelled rows and columns.
import pandas as pd
trades = pd.read_csv("trades.csv", parse_dates=["date"])
trades.head() # first five rows
trades["value"] = trades["qty"] * trades["price"] # a new column, like a formula copied down
buys = trades[trades["side"] == "BUY"] # keep only some rows, like a filter
trades.groupby("symbol")["value"].sum() # like SUMIFS, or a pivot table
Worked example: SUMIFS in pandas. In a spreadsheet, total buying of one share in 2026 would be:
=SUMIFS(Trades[Value], Trades[Side], "BUY", Trades[Symbol], "INFY", Trades[Year], 2026)
In pandas, you build the same thing in steps:
- One condition at a time:
is_buy = trades["side"] == "BUY"gives True or False for each row. - The other conditions:
is_infy = trades["symbol"] == "INFY"andin_2026 = trades["date"].dt.year == 2026. - Combine with
&(and):mask = is_buy & is_infy & in_2026. - Add up the matching rows:
trades.loc[mask, "value"].sum().
Worked example: a lookup. To bring today’s prices into a holdings table, like XLOOKUP:
holdings.merge(prices, on="symbol", how="left"). Each holding gets the price whose symbol matches. Withhow="left", holdings with no match keep a blank (NaN), so you can spot them.- Check:
holdings_with_prices["price"].isna().sum()counts the misses. It should be zero.
Everything you did with lookups and pivots in this module’s tables lesson has a pandas version: merge for lookups, groupby and pivot_table for summaries.
Which pandas step plays the role of a spreadsheet's XLOOKUP?
merge joins two tables on a shared key column, such as the share symbol, just as XLOOKUP matches on a key.
Dates: the backbone of financial data
Financial data is almost always a time series: values in date order. So dates must be real dates, not text.
prices = pd.read_csv("nifty.csv", parse_dates=["Date"], dayfirst=True, index_col="Date")
prices = prices.sort_index() # oldest first
prices.loc["2025-01-01":"2025-12-31"] # one calendar year
monthly = prices["Close"].resample("ME").last() # month-end closes
parse_datesturns text into dates. Check the format. Indian sources usually write dates day-first (03/04/2026 means 3 April), so adddayfirst=True, or give an exact format.- A DatetimeIndex lets you slice by date, and resample daily data to weekly (
"W"), month-end ("ME") or year-end ("YE"). - Count observations in trading days, but measure holding periods in calendar days.
Worked example: resampling. You have daily Nifty closes for 2025.
- Daily data: about 250 rows, one per trading day.
resample("ME").last(): groups the rows by month and takes each month’s last close. You get 12 rows..pct_change(): turns those 12 closes into 11 monthly returns (the first month has nothing to compare with).
A real case: when “markets shut at weekends” isn’t true
Indian markets are usually closed on weekends and public holidays. But not always:
- Muhurat trading. Every Diwali, NSE and BSE hold a short special session, often about an hour, on what is otherwise a holiday. Your data will show a “trading day” with tiny volumes.
- Budget day. On Saturday 1 February 2025, the exchanges held a full trading session because the Union Budget was presented that day.
Code that assumes “no trading on Saturdays”, or drops days with low volume, can silently get these wrong. Always build your calendar from the dates in the data, not from rules about weekdays.
Exact holding periods
To annualise a return, you need the exact time invested, as with XIRR in this module’s first lesson:
days = (end_date - start_date).days
cagr = (end_value / start_value) ** (365 / days) - 1
Worked example. An investment grows from ₹1 lakh to ₹1.42 lakh over 1,100 days.
- Total return: 1.42 − 1 = 42%.
- Years: 1,100 ÷ 365 = about 3.01.
- Annualised (compounded): 1.42^(365 ÷ 1,100) − 1 = about 12.3% a year.
- The naive figure: 42% ÷ 3.01 = about 13.9%. That’s wrong, because it ignores compounding.
The defaults: a 42% total gain over 1,100 days is about 12.3% a year, compounded; dividing simply gives about 13.9%. Annualising a return over less than a year can wildly exaggerate it: try 90 days.
A CSV's date column reads '03/04/2026', and pandas treats it as 4 March 2026. But it means 3 April 2026. What fixes it?
Indian sources usually write dates day-first. Telling pandas so, or giving an exact format, stops it silently swapping days and months.
Habits that save trouble
- Keep raw data untouched. Clean it in code, so you can always rerun from the original.
- Check after every load:
df.info(),df.isna().sum(), and the first and last dates. - Name things clearly, and comment the “why”, not the “what”.
- Restart and run all before trusting a notebook. Cells run out of order are a classic source of wrong answers.
Going further: 365 days for returns, 252 for volatility. Two different “years” appear in finance code, and mixing them up is a common bug. To annualise a return, use calendar days: money grows every day you hold it, weekends included, so use 365. To annualise volatility from daily returns, use trading days. Prices only move on trading days, so a year has about 250 daily returns. Volatility grows with the square root of time, so daily volatility × √250 gives yearly volatility. A daily volatility of 1% becomes about 1% × 15.8 = 15.8% a year. Use √365 by mistake and you’d get 19.1%, about a fifth too high.
Common mistakes
- Leaving dates as text. Use
parse_dates, and check the format. - Forgetting
dayfirst=Truefor Indian dates. - Dividing a total return by the years. Compound it with the exact days.
- Assuming no trading at weekends. Build calendars from the data.
- Trusting a notebook run out of order. Restart and run all.
Practice 1: A holding grows from ₹2 lakh to ₹2.3 lakh in 200 days. What's the annualised return?
- Total return: 2.3 ÷ 2 − 1 = 15%.
- Annualised: 1.15^(365 ÷ 200) − 1 = 1.15^1.825 − 1 = about 29.1% a year.
Over short periods, annualising magnifies results, so treat such numbers with care. Enter 200000, 230000 and 200 in the calculator to check.
Practice 2: Write pandas code to find total dividends received per year from a table divs with columns date and amount.
- Make sure dates are dates:
divs["date"] = pd.to_datetime(divs["date"], dayfirst=True). - Group by year and add:
divs.groupby(divs["date"].dt.year)["amount"].sum().
Or, with the date as the index: divs.set_index("date")["amount"].resample("YE").sum(). For India’s April–March financial year, use resample("YE-MAR").
Key takeaways
- Python makes analysis repeatable, scalable and checkable. pandas is the core library.
- Start with a Jupyter notebook in Colab, Anaconda or VS Code.
- A DataFrame is a programmable spreadsheet: new columns, filters, merge for lookups, groupby and pivot_table for summaries.
- Make dates real: parse_dates, dayfirst for Indian formats, a DatetimeIndex, and resample.
- Markets sometimes trade on holidays and weekends, like muhurat trading and 1 February 2025. Build calendars from the data.
- Annualise returns with exact calendar days; annualise volatility with about 250 trading days.
Go deeper
- pandas: 10 minutes to pandas.
- pandas: time series and date functionality.