Hi all,

I am trying to plot implied volatility vs realized volatility, but I am not able to access the price of the option.

This is my code now:

I have checked the function calculate implied volatility, it works fine.

In the main calculation function - the problem arises in contract.BidPrice. I have tried both contract.BidPrice and contract.ID.BidPrice, but there is no attribute called price. 

I think there has to be a different way of obtaining option data, but since I am new, I dont know how.

Can you please help me?

def main_calculation(qb, option_contracts, current_date):
    r = 0.0405  # Risk-free interest rate
    implied_volatilities = []
    
    for contract in option_contracts:

        S = get_underlying_price(qb, contract.Underlying, current_date)
        K = contract.ID.StrikePrice
        T = (contract.ID.Date - current_date).days / 365.0  # Time to expiration in years
        option_type = 'call' if contract.ID.OptionRight == OptionRight.Call else 'put'
        
        # Get the market price for the option
        #print(f"contracts in main calculation:    {contract}")


        if isinstance(contract, OptionContract):
            market_price = contract.BidPrice if contract.BidPrice else contract.AskPrice
            iv = calculate_implied_volatility(S, K, T, r, market_price, option_type)
            print(f"iv in main calculation:    {iv}")
            implied_volatilities.append((contract, iv))
        else:
            print("Not a option contract")
    
        return implied_volatilities


qb = QuantBook()
current_date = datetime(2023, 6, 1)


min_strike = 100
max_strike = 500
min_expiry = current_date + timedelta(days=20)
max_expiry = current_date + timedelta(days=40)


option_chain = qb.OptionChainProvider.GetOptionContractList(Symbol.Create("SPY", SecurityType.Equity, Market.USA), current_date)

filtered_contracts = [contract for contract in option_chain if min_strike <= contract.ID.StrikePrice <= max_strike and min_expiry <= contract.ID.Date <= max_expiry]

print(f"filtered contracts.price: {filtered_contracts}")
contract = filtered_contracts[0]
print(dir(contract.ID))


# Calculate implied volatilities
implied_volatilities = main_calculation(qb, filtered_contracts, current_date)

print(f"implied_volatilities: {implied_volatilities}")

# Display results
for contract in implied_volatilities:
    
    print(f"Symbol: {contract}, Strike: {contract.ID.StrikePrice}, Expiry: {contract.ID.Date}, Implied Volatility: {iv}")