Introduction à Python
  • Back to Main Website
  • Home
  • Comprendre Et Installer Python
    • Comprendre Et Installer Python
    • Histoire du Langage
    • Exécution d’un Programme Python
    • Versions et Compilation de Python
    • Le PATH
    • Path.. et environnements virtuels!
    • Les IDEs
    • Les Notebooks

    • Quelques IDEs en Python
    • VsCode - L’IDE Flexible et Polyvalent
    • Spyder - Un IDE Orienté Science des Données
    • PyCharm - L’IDE orienté Python

    • Travaux Pratiques
    • TP Guidé - Installer plusieurs versions de python avec pyenv
    • TP - Construire son python depuis la source
  • Syntaxes et Concepts de Base
    • Syntaxes et Concepts de Base
    • Syntaxe et objets de Base Python
    • Fonctions et Modules
    • Introduction à la POO en Python

    • Travaux Pratiques
    • Exercices d’applications
    • Base de la POO: Exercice
  • Les Librairies Python
    • Les Librairies Python
    • Installer et importer des librairies en Python
    • Les DataFrames
    • Exemple sur pandas
    • Calcul Scientifique et Optimization
    • Machine Learning
    • Recupérer des données du net
    • Python - Aussi un language pour servir des données
    • Visualiser et présenter ces données avec Python

    • Travaux Pratiques
    • TP-3 Libraries
    • TP - Utiliser pandas
  • Bonne pratiques, Dangers, et Astuces
    • Bonne pratiques, Dangers, et Astuces
    • Mutabilité et Scope
    • Typage en Python
    • Asynchronie et Multiprocessing

    • Travaux Pratiques
    • Modern Portfolio Theory - Practical Work
    • Modern Portfolio Theory - Practical Work - Corrected version
    • TP Python for Finance: Introduction to Option Pricing
    • TP Python for Finance: Introduction to Option Pricing - Corrected Version
    • TP - Creer un outil de récupération de donnée
  • Concepts avancés
    • Concepts avancés
    • L’arbre Syntaxique Abstrait ou AST
    • Python Orienté Objet - Les Dunders
    • Python Orienté Objet - les Design Patterns

    • Travaux Pratiques
    • TP-5
  • Sujets de Projets possibles
    • Projets
    • Projets Introduction à Python - Millésime 2024
    • Projets Introduction à Python - Millésime 2025
  • Code source
  1. Travaux Pratiques
  2. TP Python for Finance: Introduction to Option Pricing
  • Bonne pratiques, Dangers, et Astuces
  • Mutabilité et Scope
  • Typage en Python
  • Asynchronie et Multiprocessing
  • Travaux Pratiques
    • Modern Portfolio Theory - Practical Work
    • Modern Portfolio Theory - Practical Work - Corrected version
    • TP Python for Finance: Introduction to Option Pricing
    • TP Python for Finance: Introduction to Option Pricing - Corrected Version
    • TP - Creer un outil de récupération de donnée

On this page

  • Question 1: Data Collection
  • Question 2: Understanding Call Options
  • Question 3: Monte Carlo Simulation
  • Question 4: Competing Option Sellers
    • Question 4.2:
  1. Travaux Pratiques
  2. TP Python for Finance: Introduction to Option Pricing

TP Python for Finance: Introduction to Option Pricing

Author

Remi Genet

Published

2025-02-12

Question 1: Data Collection

Using the yfinance library, download daily price data for the stock “AAPL” (Apple Inc.) for the last year. Calculate and plot the daily returns of the stock.


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

# Download the data
ticker = "AAPL"
start_date = "2020-01-01"
end_date = "2024-12-31"

# Your code here to:
# 1. Download the data using yfinance
# 2. Calculate daily returns
# 3. Create a plot of the stock price and returns
[*********************100%***********************]  1 of 1 completed

Question 2: Understanding Call Options

A Call option is a financial contract that gives the buyer the right (but not the obligation) to buy a stock at a predetermined price (strike price) at a future date (expiration date). The seller of the option (writer) receives a premium for taking on the obligation to sell at the strike price if the buyer exercises their right.

Example: If you buy a call option for AAPL with: - Strike price (K) = $180 - Current price (S) = $170 - Expiration = 1 month

If at expiration: - AAPL price = $190: Your profit = $190 - $180 = $10 (minus the premium paid) - AAPL price = $170: Your loss = premium paid

Create a function that calculates the payoff of a call option at expiration.

# Your code here to:
# Create a function that takes as input:
# - Strike price (K)
# - Current price (S)
# And returns the payoff at expiration
Testing call option payoff with strike price = 180
Stock price: 160, Payoff: 0
Stock price: 170, Payoff: 0
Stock price: 180, Payoff: 0
Stock price: 190, Payoff: 10
Stock price: 200, Payoff: 20

Question 3: Monte Carlo Simulation

Create a function that simulates future stock prices using Monte Carlo simulation. We’ll use the following assumptions: - Stock returns are normally distributed (Note: This is a simplifying assumption that doesn’t hold well in reality) - The volatility is estimated from historical data

# Your code here to:
# 1. Create a function that simulates stock paths
# 2. Use it to estimate option prices
Estimated call option price: 0.81

Question 4: Competing Option Sellers

Two option sellers are competing in the market. They use different methods to estimate volatility: - Seller 1: Uses 5-day rolling standard deviation - Seller 2: Uses 10-day rolling standard deviation

Follow these steps to simulate their competition:

  1. First, calculate the rolling volatility for each seller:
    • Use rolling() function with window=5 for seller 1
    • Use rolling() function with window=10 for seller 2
    • Don’t forget to use .std() to get the standard deviation
  2. For each day, calculate the option price that each seller would offer:
    • Use the estimate_call_price function we created earlier
    • You can use apply() with a lambda function to calculate prices
    • Each seller uses their own volatility estimate
  3. Determine which seller makes the sale:
    • The seller with the lower price wins the trade
    • Use comparison operators and astype(int) to create indicator variables
  4. Calculate the payoff of the options:
    • Remember: payoff = max(0, future_price - strike_price)
    • Use shift(-1) to get the next day’s price
    • Use apply() with lambda x: max(x, 0) for the payoff
  5. Calculate the PnL for each seller:
    • PnL = (premium received - option payoff) when seller wins the trade
    • Use the indicator variables from step 3
  6. Plot the cumulative PnL:
    • Use cumsum() to calculate cumulative sums
    • Use plot() to visualize the results
# Your code here:

# 1. Calculate rolling volatilities
stock_data['vol_5d'] = ...
stock_data['vol_10d'] = ...

# 2. Calculate option prices for each seller
stock_data['seller_1_price'] = ...
stock_data['seller_2_price'] = ...

# 3. Determine who makes each sale
stock_data['seller_1_sold'] = ...
stock_data['seller_2_sold'] = ...

# 4. Calculate option payoffs
stock_data['Option Payoff'] = ...

# 5. Calculate PnL for each seller
stock_data['seller_1_pnl'] = ...
stock_data['seller_2_pnl'] = ...

# 6. Plot cumulative PnL
...

Question 4.2:

Create the degenerated case with only one option seller, and see how the choice of sigma impact the obtained PnL


Back to top
Modern Portfolio Theory - Practical Work - Corrected version
TP Python for Finance: Introduction to Option Pricing - Corrected Version

Introduction à Python, Rémi Genet.
Licence
Code source disponible sur Github

 

Site construit avec et Quarto
Inspiration pour la mise en forme du site ici
Code source disponible sur GitHub