OpTrade๏
OpTrade is a complete toolkit for quantitative research and development of options trading strategies. By abstracting away the complexity of data handling and experimental design, researchers and traders can focus on what matters most: developing and testing alpha-generating ideas.
Installation๏
The recommended way to install OptTrade is via pip:
pip install optrade
*Note: At this time OpTrade requires an active subscription to [ThetaData API](https://www.thetadata.net/subscribe) for the stocks (VALUE) and options (VALUE) packages.
Example (Single Contract)๏
1# Step 1: Find and initialize the optimal contract
2from optrade.data.contracts import Contract
3from rich.console import Console
4
5
6ctx = Console()
7ctx.log("Searching for an ATM call option available January 3, 2023 with approximately 30 days to expiration...")
8contract = Contract.find_optimal(
9 root="AAPL",
10 right="C", # Call option
11 start_date="20230103", # First trading day of 2023
12 target_tte=30, # Desired expiration: 30 days
13 tte_tolerance=(20, 40), # Min 20, max 40 days expiration
14 interval_min=15, # Data requested at 15-min level
15 moneyness="ATM", # At-the-money option
16 verbose=True,
17)
18ctx.log(f"Optimal contract found: {contract}")
19
20# Step 2: Load market data (NBBO quotes and OHLCV)
21ctx.log("Loading market data from ThetaData API...")
22df = contract.load_data()
23print(df.head())
24
25# Step 3: Transform raw data into ML-ready features
26from optrade.data.features import transform_features
27from rich.table import Table
28from rich import box
29
30data = transform_features(
31 df=df,
32 core_feats=[
33 "option_returns", # Option price returns
34 "stock_returns", # Underlying stock returns
35 "moneyness", # Log(S/K)
36 "option_lob_imbalance", # Order book imbalance
37 "stock_quote_spread", # Bid-ask spread normalized
38 ],
39 tte_feats=["sqrt"], # Time-to-expiration features
40 datetime_feats=["minute_of_day"], # Time features
41 vol_feats=["rolling_volatility"], # Rolling volatility window and short-to-long volatility ratio
42 rolling_volatility_range=[60], # 60min rolling volatility windows
43 strike=contract.strike,
44 exp=contract.exp,
45 root=contract.root,
46 right=contract.right,
47)
48
49
50table = Table(title="Transformed Features", box=box.SIMPLE)
51
52# Add column headers
53for col in data.columns:
54 table.add_column(col, justify="center", style="cyan", no_wrap=True)
55
56# Add top 10 rows only
57for i, row in data.head(10).iterrows():
58 table.add_row(*[str(item) for item in row.values])
59ctx.log(table)
60
61
62# Step 4: Create dataset for time series forecasting
63from optrade.data.forecasting import ForecastingDataset
64from torch.utils.data import DataLoader
65
66ctx.log("Converting data to PyTorch dataset with lookback window size of 20 data points (300min) and forecast horizon of 5 data points (25min)")
67ctx.log("Using all features as inputs, with target channel set to option returns")
68torch_dataset = ForecastingDataset(
69 data=data,
70 seq_len=20, # 300-minute lookback window
71 pred_len=5, # 25-minute forecast horizon
72 target_channels=["option_returns"], # Forecast option returns
73)
74
75torch_loader = DataLoader(torch_dataset, batch_size=32)
76
77for batch in torch_loader:
78 x, y = batch
79 ctx.log("Grabbing a single example:")
80 ctx.log(f"Input shape: {x.shape}, Target shape: {y.shape}")
81 break
Overview๏
๐ Data Pipeline OpTrade integrates with ThetaDataโs API for affordable options and security data access (down to 1-min resolution). The framework processes NBBO quotes and OHLCVC metrics through a contract selection system optimizing for moneyness, expiration windows, and volatility-scaled strikes.
๐ Market Environments Built-in market environments enable precise universe selection through multifaceted filtering. OpTrade supports composition by major indices, fundamental-based screening (e.g., PE ratio, market cap), and Fama-French model categorization.
๐งช Experimental Pipeline The experimentation framework supports PyTorch and scikit-learn for options forecasting with online Neptune logging, hyperparameter tuning, and model version control, supporting both online and offline experiment tracking.
๐งฎ Featurization OpTrade provides option market features including mid-price derivations, order book imbalance metrics, quote spreads, and moneyness calculations. Time-to-expiration transformations capture theta decay effects, while datetime features extract cyclical market patterns for intraday seasonality.
๐ค Models OpTrade includes several off-the-shelf PyTorch and scikit-learn models, including state-of-the-art architectures for time series forecasting alongside tried and true machine learning methods
Contact๏
For queries, please contact: xmootoo at gmail dot com.