Install opstrat via pip
mainInstall the opstrat package using the standard Python package manager.
pip install opstratrepository·main·Indexed 41 days ago
https://github.com/hashabcd/opstratA Python library for visualizing options trading strategies through payoff diagrams. It features tools for plotting single options via single_plotter(), complex multi-option strategies via multi_plotter(), and real market data integration via yf_plotter() using yfinance. The library also includes op.black_scholes() to compute theoretical option prices and Greeks (delta, gamma, theta, rho, vega).
Install the opstrat package using the standard Python package manager.
pip install opstratTo save a generated plot to your local directory, pass save=True and provide a filename via the file parameter to any of the plotter functions (e.g., single_plotter). If file is omitted, the library defaults to saving the file as fig.png.
import opstrat as op
# Save as a specific jpeg file
op.single_plotter(save=True, file='simple_option.jpeg')Use multi_plotter() to visualize complex strategies involving multiple simultaneous option positions. This function plots each individual payoff diagram alongside the resultant combined payoff diagram.
Arguments:
spot: The current price of the underlying asset.op_list: A list of dictionaries, where each dictionary defines an individual option's parameters.spot_range: (Optional) Limits the range of spot values covered in the plot. The default is +/-20%. Use smaller values (e.g., 5) for low volatility or larger values for high volatility assets.Each dictionary in op_list must contain:
op_type: 'c' (call) or 'p' (put).strike: The strike price.tr_type: 'b' (buy) or 's' (sell).op_pr: The option premium.import opstrat as op
# Example: Short Strangle
op_1 = {'op_type':'c', 'strike':110, 'tr_type':'s', 'op_pr':2}
op_2 = {'op_type':'p', 'strike':95, 'tr_type':'s', 'op_pr':6}
op.multi_plotter(spot=100, op_list=[op_1, op_2])
# Example: Iron Condor
op1={'op_type': 'c', 'strike': 215, 'tr_type': 's', 'op_pr': 7.63}
op2={'op_type': 'c', 'strike': 220, 'tr_type': 'b', 'op_pr': 5.35}
op3={'op_type': 'p', 'strike': 210, 'tr_type': 's', 'op_pr': 7.20}
op4={'op_type': 'p', 'strike': 205, 'tr_type': 'b', 'op_pr': 5.52}
op.multi_plotter(spot=212.26, spot_range=10, op_list=[op1, op2, op3, op4])Use yf_plotter() to fetch real-time or historical data via yfinance and plot option strategies based on a specific stock ticker.
Parameters:
ticker: Stock Ticker string (e.g., 'msft', 'amzn') (default: 'msft')exp: Option expiration date in 'YYYY-MM-DD' format. Use 'default' for the next available expiration date.spot_range: Range of spot variation in percentage (default: 10)op_list: A list of dictionaries representing the options. Each dictionary must contain:strike: Strike Pricetr_type: 'b' (long) or 's' (short)op_type: 'c' (call) or 'p' (put)import opstrat as op
# Example: Strangle on Amazon
op_1={'op_type': 'c', 'strike': 3070, 'tr_type': 'b'}
op_2={'op_type': 'p', 'strike': 3070, 'tr_type': 'b'}
op.yf_plotter(ticker='amzn', exp='default', op_list=[op_1, op_2])Use single_plotter() to visualize the risk/reward profile of a single option contract.
By default, calling op.single_plotter() generates a long call option diagram with a strike price of $102 and a spot price of $100. Profit is indicated by a green shade and loss by a red shade.
To customize the plot, provide the following arguments:
spot: The current price of the underlying asset.strike: The strike price of the option.op_type: The type of option ('c' for call, 'p' for put).tr_type: The transaction type ('b' for buy/long, 's' for sell/short).op_pr: The option premium.import opstrat as op
# Example: Selling a put option at strike 460 when spot is 460, receiving 12.50 premium
op.single_plotter(spot=460, strike=460, op_type='p', tr_type='s', op_pr=12.5)Use single_plotter() to generate a payoff diagram for a single option position. The plot uses Green for profit and Red for loss.
Parameters:
op_type: 'c' for call option, 'p' for put option (default: 'c')spot: Spot Price (default: 100)spot_range: Range of spot variation in percentage (default: 5)strike: Strike Price (default: 102)tr_type: Transaction Type, 'b' for long, 's' for short (default: 'b')op_pr: Option Price/Premium (default: 10)save: Boolean, set to True to save the figurefile: Filename with extension to save the figure (e.g., 'plot.png'). If not provided, defaults to fig.png.import opstrat as op
# Default plot
op.single_plotter()
# Custom plot: Short Put
op.single_plotter(spot=460, strike=460, op_type='p', tr_type='s', op_pr=12.5)
# Save a custom plot
op.single_plotter(save=True, file='simple_option.jpeg')Use multi_plotter() to plot payoff diagrams for strategies involving multiple options (e.g., Strangles, Iron Condors).
Parameters:
spot: Spot Price (default: 100)spot_range: Range of spot variation in percentage (default: 20)op_list: A list of dictionaries, where each dictionary represents one option in the strategy. Each dictionary must contain:strike: Strike Pricetr_type: 'b' (long) or 's' (short)op_pr: Option Price/Premiumop_type: 'c' (call) or 'p' (put)import opstrat as op
# Example: Iron Condor (4 options)
op1={'op_type': 'c', 'strike': 215, 'tr_type': 's', 'op_pr': 7.63}
op2={'op_type': 'c', 'strike': 220, 'tr_type': 'b', 'op_pr': 5.35}
op3={'op_type': 'p', 'strike': 210, 'tr_type': 's', 'op_pr': 7.20}
op4={'op_type': 'p', 'strike': 205, 'tr_type': 'b', 'op_pr': 5.52}
op_list=[op1, op2, op3, op4]
op.multi_plotter(spot=212.26, spot_range=10, op_list=op_list)Use yf_plotter() to generate payoff diagrams using real-world market data via the Yahoo Finance API. This allows you to specify a stock ticker and an expiration date.
Arguments:
ticker: The stock ticker symbol (e.g., 'msft', 'amzn').exp: The option expiry date in 'YYYY-MM-DD' format.op_list: A list of dictionaries defining the options (e.g., {'tr_type':'b', 'op_type':'c', 'strike':235}).spot_range: (Optional) The range of spot values to cover in the plot.import opstrat as op
# Example: Call Option Buyer for Microsoft
op_list=[{'tr_type':'b', 'op_type':'c', 'strike':235}]
op.yf_plotter('msft', spot_range=10, op_list=op_list)
# Example: Strangle on Amazon with specific expiry
op_1={'op_type': 'c', 'strike':3150, 'tr_type': 'b'}
op_2={'op_type': 'p', 'strike':3150, 'tr_type': 'b'}
op.yf_plotter(ticker='amzn', exp='2021-03-26', op_list=[op_1, op_2])To visualize how Greeks change as time to expiration approaches, iterate through a range of time values (ts) and different volatility levels (vs), collecting the results into a pandas DataFrame for plotting with matplotlib.
Note: When plotting time-decay, it is common to use plt.gca().invert_xaxis() to show time moving towards expiration.
import opstrat as op
import pandas as pd
import matplotlib.pyplot as plt
K=100
St=95
r=4
vs=[10,25,40,60]
ts=[i for i in range(1,101)]
type='c'
df_list=[]
for v in vs:
vals, vals_int, vals_time = [], [], []
deltas, gammas, thetas, rhos, vegas = [], [], [], [], []
for t in ts:
params = op.black_scholes(t=t, K=K, St=St, r=r, v=v, type=type)
vals.append(params['value']['option value'])
vals_int.append(params['value']['intrinsic value'])
vals_time.append(params['value']['time value'])
deltas.append(params['greeks']['delta'])
gammas.append(params['greeks']['gamma'])
thetas.append(params['greeks']['theta'])
rhos.append(params['greeks']['rho'])
vegas.append(params['greeks']['vega'])
df = pd.DataFrame({
'vals': vals, 'vals_int': vals_int, 'vals_time': vals_time,
'delta': deltas, 'gamma': gammas, 'theta': thetas,
'rho': rhos, 'vega': vegas
})
df_list.append(df)
# Plotting Delta across different volatilities
for greek in ['delta', 'gamma', 'theta', 'rho', 'vega']:
plt.figure(figsize=(10,6))
for df, v in zip(df_list, vs):
plt.plot(ts, df[greek], label=f'{greek} V:{v}%')
plt.gca().invert_xaxis()
plt.legend()
plt.show()Use op.black_scholes() to compute the theoretical price and the Greeks (delta, gamma, theta, rho, vega) for an option.
Parameters:
t: Time to expiration.K: Strike price.St: Current underlying asset price.r: Risk-free interest rate.v: Volatility.type: Option type, e.g., 'c' for call or 'p' for put.Return Value: A dictionary containing two main keys:
'value': A dictionary containing 'option value', 'intrinsic value', and 'time value'.'greeks': A dictionary containing 'delta', 'gamma', 'theta', 'rho', and 'vega'.import opstrat as op
# Example calculation
params = op.black_scholes(t=5, K=100, St=95, r=4, v=25, type='c')
# Accessing specific values
option_value = params['value']['option value']
theta = params['greeks']['theta']