Skip to main content

Package for quantitative analysis

Project description

Welcome on the quant23rg package

quant23rg is python package for quantitative analysis

Install it by typing this command in your command prompt

pip install quant23rg

The package is still in progress

Author : Adrien Calas - Le23RayGorbella (Freelancer)

Click here to contact by mail, Location : Paris and Nice, France

Linkedin

Available : european options pricing, implied volatilities, geometrical brownian motion for assets and portfolios, value at risk & conditional value at risk (work in progress for portfolio)

European options pricing

from pricingCallEuropBS import PricingCallEuropBS
from pricingPutEuropBS import PricingPutEuropBS


import pandas as pd
from implied_volatility import ImpliedVolatility
from pricingCallEuropBS import PricingCallEuropBS
from pricingPutEuropBS import PricingPutEuropBS

spy_opt = pd.read_csv(
    "spy-options.csv",
).dropna()
spy_opt.columns = [
    col + "_call" if ".1" not in col and col != "Strike" else col
    for col in spy_opt.columns
]
spy_opt.columns = [col.replace(".1", "_put") for col in spy_opt.columns]
spy_opt["IV_call"] = spy_opt["IV_call"].apply(lambda x: float(x.replace("%", "")) / 100)
spy_opt["IV_put"] = spy_opt["IV_put"].apply(lambda x: float(x.replace("%", "")) / 100)
spy_opt["Last_call"] = spy_opt["Last_call"].apply(lambda x: float(x))
spy_opt["Last_put"] = spy_opt["Last_put"].apply(lambda x: float(x))
call_example = spy_opt.sort_values("Volume_call", ascending=False).iloc[0]

# Last_call              27.9
# Bid_call              27.85
# Ask_call              28.18
# Change_call            27.9
# Volume_call             962
# Open Int_call         2,741
# IV_call              0.1815
# Last Trade_call    05/26/23
# Strike                410.0
# Last_put              12.45
# Bid_put               12.24
# Ask_put                12.4
# Change_put            12.45
# Volume_put            1,234
# Open Int_put         20,292
# IV_put               0.1831
# Last Trade_put     05/26/23
# Name: 47, dtype: object

s0 = 420.02  # 29 may 2023
dt = 146 / 252  # in years, expiration date : 20 october 2023
call_pricing = PricingCallEuropBS(
    s0=s0,
    strike=call_example.Strike,
    dt=dt,
    interest_rate=0.05 * dt,  # fed rate multiplied by our period of time
    volatility=0.1326,
)
call_pricing.payoff_sigma_fixed()


put_pricing = PricingPutEuropBS(
    s0=s0,
    strike=call_example.Strike,
    dt=dt,
    interest_rate=0.05 * dt,  # fed rate multiplied by our period of time
    volatility=0.1326,
)
put_pricing.payoff_sigma_fixed()

Implied volatilities

### See volatility smile (Strike -> IV(Strike)) ###

ivs = ImpliedVolatility(
    s0=s0,
    strike=call_example.Strike,
    dt=dt,
    interest_rate=0.05 * dt,  # fed rate  multiplied by our period of time
    volatility=0.1326,
)

ivs.show_implied_vol_and_compare(
    marketPrices_call=spy_opt["Last_call"].tolist(),
    marketPrices_put=spy_opt["Last_put"].tolist(),
    strikes=spy_opt.Strike.tolist(),
    marketVols=spy_opt.IV_call.tolist(),
)

Geometrical Brownian Motion for assets and portfolios

from pricingGBM import PricingGBM, PricingGBMPortfolio
import yfinance as yf


sp500 = yf.Ticker("^GSPC")
hist_sp500 = sp500.history("1y")
hist_sp500["returns"] = hist_sp500.Close / hist_sp500.Close.shift(1) - 1
returns_serie = hist_sp500.dropna().returns

#################################################


### Pricing with Geometric Brownian Motion ###
pricer = PricingGBM.create_pricing_GBM_from_time_series(
    hist_sp500.Close,
    nb_steps=100,
    maturity=1,
    returns=returns_serie,
    nb_simulations=1000,
)
pricer.simulate_and_see()

Value at Risk & Conditional Value at Risk (work in progress for portfolio)

### Value at Risk (one asset) ###
from riskManagement import RiskManagementOneAsset

rkManageHistoric = RiskManagementOneAsset(returns_serie, input_type="returns")
rkManageNormal = RiskManagementOneAsset(
    returns_serie,
    mode="normal",
)
rkManageMonteCarlo = RiskManagementOneAsset(
    hist_sp500.Close, "Monte-Carlo", returns=returns_serie, input_type="value"
)

print(
    f"VaR Historic 1 day : {rkManageHistoric.value_at_risk(nb_past_days=len(returns_serie),confiance=.95, nb_days=1 )}"
)
print(
    f"VaR Normal 1 day  : {rkManageNormal.value_at_risk(nb_past_days=len(returns_serie),confiance=.95, nb_days=1 )}"
)
print(
    f"VaR Monte-Carlo 1 day : {rkManageMonteCarlo.value_at_risk(nb_past_days=len(returns_serie),confiance=.95, nb_days=1 )}"
)

print(
    f"Cond-VaR Historic 1 day : {rkManageHistoric.conditional_value_at_risk(nb_past_days=len(returns_serie),confiance=.95, nb_days=1 )}"
)
print(
    f"Cond-VaR Normal 1 day  : {rkManageNormal.conditional_value_at_risk(nb_past_days=len(returns_serie),confiance=.95, nb_days=1 )}"
)
print(
    f"Cond-VaR Monte-Carlo 1 day : {rkManageMonteCarlo.conditional_value_at_risk(nb_past_days=len(returns_serie),confiance=.95, nb_days=1 )}"
)


#################################################


### Value at Risk multiple assets (Cholesky) ###

import yfinance as yf
import numpy as np
from riskManagement import RiskManagementPortfolio

## Datas for the test
sp500 = yf.Ticker("^GSPC")
hist_sp500 = sp500.history("1y")
aapl = yf.Ticker("AAPL")
hist_aapl = aapl.history("1y")
hist_sp500["returns"] = hist_sp500.Close / hist_sp500.Close.shift(1) - 1
###############################@


pf_risk_Test = RiskManagementPortfolio.init_and_instantiate_RK_PF(
    portfolio_time_series=np.array(
        [
            hist_sp500.Close.tolist(),
            hist_aapl.Close.tolist(),
        ]
    ),
    interest_free_rate=0.05 / 252,
    mode="Monte-Carlo",
    nb_days=1,
    input_type="value",
)
print("Correlation matrix :")
print(pf_risk_Test.correlation_matrix)
print(
    "Value-at-risk 1 day",
    pf_risk_Test.value_at_risk(
        nb_past_days=1,  # not important here
        confiance=0.95,
    ),
)

pf_risk_Test = RiskManagementPortfolio.init_and_instantiate_RK_PF(
    portfolio_time_series=np.array(
        [
            hist_sp500.Close.tolist(),
            hist_aapl.Close.tolist(),
        ]
    ),
    interest_free_rate=0.05 / 252,
    mode="normal",
    nb_days=1,
    input_type="value",
)
print("Correlation matrix :")
print(pf_risk_Test.correlation_matrix)
print(
    "Value-at-risk 1 day",
    pf_risk_Test.value_at_risk(
        nb_past_days=1,  # not important here
        confiance=0.95,
    ),
)

################################################

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

quant23rg-0.0.1.tar.gz (14.0 kB view details)

Uploaded Source

Built Distribution

quant23rg-0.0.1-py3-none-any.whl (17.8 kB view details)

Uploaded Python 3

File details

Details for the file quant23rg-0.0.1.tar.gz.

File metadata

  • Download URL: quant23rg-0.0.1.tar.gz
  • Upload date:
  • Size: 14.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.2 CPython/3.9.2

File hashes

Hashes for quant23rg-0.0.1.tar.gz
Algorithm Hash digest
SHA256 31e2eb4a50030b97b9cdf8f5122be912fba4391123778d240fb5a72b723972be
MD5 7523ec5df0f7f53a2f97b740b220aa3c
BLAKE2b-256 152716e254bc47eecf83e1f07a46e14d1c37b63a275a42c29ba46a52acd90ce1

See more details on using hashes here.

File details

Details for the file quant23rg-0.0.1-py3-none-any.whl.

File metadata

  • Download URL: quant23rg-0.0.1-py3-none-any.whl
  • Upload date:
  • Size: 17.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.2 CPython/3.9.2

File hashes

Hashes for quant23rg-0.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 b0b3013d5158a4603cfa39d6cdad6cd6649c69b55a1a54ffad0ceeb2cadf8664
MD5 4e470d3273370a80000bfcd0788da929
BLAKE2b-256 938bef4f0a3a2238d205c573a7a116b82d5de4086d295845592eaf80d4f052ff

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page