CodeForFinance
← Python Track

Python for Finance: Getting Started

Set up your environment, pull real market data, and calculate your first returns — all in under 20 minutes.

Why Python Dominates Finance

Python is the most widely used language in quantitative finance and it is not even close. Every major bank, hedge fund, and fintech uses it. The reasons are simple:

  • Massive ecosystem of financial libraries (pandas, numpy, scipy, yfinance)
  • Fast prototyping — test an idea in minutes, not hours
  • Huge community — if you get stuck, someone has solved it before
  • Integration with data sources, APIs, and visualisation tools
  • Used in production at Goldman Sachs, JPMorgan, Two Sigma, and more

Setup

You need Python 3.8 or newer. Download it from python.org if you do not have it. Then install the libraries we need:

pip install pandas numpy matplotlib yfinance

pandas handles tabular data. numpy does fast maths. matplotlib plots charts. yfinance pulls market data from Yahoo Finance for free.

Your First Script: Fetching FTSE 100 Data

Create a file called ftse_analysis.py and add the following:

import yfinance as yf
import pandas as pd

# Fetch 1 year of FTSE 100 data
ftse = yf.download("^FTSE", period="1y")

# Show the last 5 rows
print(ftse.tail())

# Basic stats
print(ftse["Close"].describe())

Run it with python ftse_analysis.py. You should see a table of dates, open, high, low, close, and volume data. The describe() call gives you count, mean, std, min, quartiles, and max.

Calculating Daily Returns

The raw price is useful, but returns are what matter. A daily return tells you the percentage change from one day to the next:

# Calculate daily percentage returns
ftse["Daily Return"] = ftse["Close"].pct_change() * 100

# Drop the first NaN row
ftse = ftse.dropna()

# Show the result
print(ftse[["Close", "Daily Return"]].tail(10))

# Average daily return
avg = ftse["Daily Return"].mean()
print(f"
Average daily return: {avg:.4f}%")

The pct_change() method computes (price_today - price_yesterday) / price_yesterday. We multiply by 100 to get a percentage.

Plotting a Chart

Visualisation is essential. Add this to your script to create a two-panel chart showing price and returns:

import matplotlib.pyplot as plt

fig, axes = plt.subplots(2, 1, figsize=(12, 8), sharex=True)

# Price chart
axes[0].plot(ftse.index, ftse["Close"], color="#22d3ee", linewidth=1)
axes[0].set_title("FTSE 100 — Closing Price")
axes[0].set_ylabel("Price")
axes[0].grid(alpha=0.2)

# Returns chart
axes[1].bar(ftse.index, ftse["Daily Return"], color="#22d3ee", alpha=0.6, width=1)
axes[1].set_title("FTSE 100 — Daily Returns (%)")
axes[1].set_ylabel("Return %")
axes[1].grid(alpha=0.2)

plt.tight_layout()
plt.savefig("ftse100_analysis.png", dpi=150)
plt.show()

This saves a PNG file and opens an interactive window. You will see the FTSE price trend on top and the daily return distribution below.

Complete Working Script

Here is everything in one file, ready to copy and run:

import yfinance as yf
import pandas as pd
import matplotlib.pyplot as plt

# 1. Fetch data
ftse = yf.download("^FTSE", period="1y")

# 2. Calculate returns
ftse["Daily Return"] = ftse["Close"].pct_change() * 100
ftse = ftse.dropna()

# 3. Summary statistics
print("=== FTSE 100 Summary ===")
print(f"Period: {ftse.index[0].date()} to {ftse.index[-1].date()}")
print(f"Start price: {ftse['Close'].iloc[0]:.2f}")
print(f"End price:   {ftse['Close'].iloc[-1]:.2f}")
print(f"Total return: {((ftse['Close'].iloc[-1] / ftse['Close'].iloc[0]) - 1) * 100:.2f}%")
print(f"Avg daily return: {ftse['Daily Return'].mean():.4f}%")
print(f"Daily volatility:  {ftse['Daily Return'].std():.4f}%")

# 4. Plot
fig, axes = plt.subplots(2, 1, figsize=(12, 8), sharex=True)
axes[0].plot(ftse.index, ftse["Close"], color="#22d3ee", linewidth=1)
axes[0].set_title("FTSE 100 — Closing Price")
axes[0].set_ylabel("Price")
axes[0].grid(alpha=0.2)
axes[1].bar(ftse.index, ftse["Daily Return"], color="#22d3ee", alpha=0.6, width=1)
axes[1].set_title("FTSE 100 — Daily Returns (%)")
axes[1].set_ylabel("Return %")
axes[1].grid(alpha=0.2)
plt.tight_layout()
plt.savefig("ftse100_analysis.png", dpi=150)
plt.show()

Try It Yourself

  1. Change the ticker to "AAPL" and compare Apple returns to the FTSE.
  2. Add a 20-day moving average to the price chart using ftse["Close"].rolling(20).mean().
  3. Calculate the annualised volatility: daily_std * (252 ** 0.5).
  4. Fetch 5 years of data instead of 1. Does the average daily return change much?

Developer Essentials

As an Amazon Associate we may earn from qualifying purchases.