Files
strategy-lab/to_explore/pyquantnews/73_OptionsBacktesting.ipynb
David Brazda e3da60c647 daily update
2024-10-21 20:57:56 +02:00

5.7 KiB

No description has been provided for this image

This code processes historical stock data for financial analysis and option strategy backtesting. It reads multiple CSV files containing end-of-day data, concatenates them, and saves the result in a single file. The script then loads this combined data and uses the Optopsy library to analyze option chains. It evaluates various option strategies such as short calls, long straddles, and short strangles, providing a practical tool for financial professionals to assess historical performance and strategy efficacy.

In [ ]:
import os
import glob
import pandas as pd
import optopsy as op

Collect all CSV files in the "rut-eod" directory

In [ ]:
files = glob.glob(os.path.join("rut-eod", "*.csv"))

Initialize an empty list for storing dataframes

In [ ]:
dfs = []
for fl in files:
    # Read each CSV file and append its dataframe to the list
    df = pd.read_csv(fl)
    dfs.append(df)

Concatenate all dataframes and save the combined data to a new CSV file

In [ ]:
pd.concat(dfs).to_csv("rut_historic.csv", index=False)

Load the combined historical data from the new CSV file

In [ ]:
rut = pd.read_csv("rut_historic.csv")

Print the most recent date in the dataset

In [ ]:
rut.date.max()

Load the option chains from the combined historical data using specific column indices

In [ ]:
rut_chains = op.csv_data(
    "rut_historic.csv",
    underlying_symbol=1,
    underlying_price=4,
    option_type=8,
    expiration=6,
    quote_date=0,
    strike=7,
    bid=14,
    ask=15
)

Display the first few rows of the option chains dataframe

In [ ]:
rut_chains.head()

Evaluate and round the results of the short calls strategy

In [ ]:
op.short_calls(rut_chains).round(2)

Evaluate and round the results of the long straddles strategy

In [ ]:
op.long_straddles(rut_chains).round(2)

Evaluate and round the results of the short strangles strategy with specified parameters

In [ ]:
op.short_strangles(
    rut_chains, 
    dte_interval=60, 
    max_entry_dte=70, 
    exit_dte=10,
    otm_pct_interval=0.01,
    max_otm_pct=0.10
).round(2)

PyQuant News is where finance practitioners level up with Python for quant finance, algorithmic trading, and market data analysis. Looking to get started? Check out the fastest growing, top-selling course to get started with Python for quant finance. For educational purposes. Not investment advise. Use at your own risk.