Here's an example Python program that uses the Yahoo Finance API to retrieve the latest option prices for a given stock symbol:
import yfinance as yf
# User inputs
symbol = input("Enter stock symbol: ")
expiry = input("Enter option expiry date (YYYY-MM-DD): ")
option_type = input("Enter option type (call/put): ")
strike_price = float(input("Enter option strike price: "))
# Get option chain for the stock symbol
option_chain = yf.Ticker(symbol).option_chain(expiry)
# Get the option price for the given strike price and option type
if option_type == 'call':
option_price = option_chain.calls.loc[option_chain.calls['strike'] == strike_price, 'lastPrice'].values[0]
else:
option_price = option_chain.puts.loc[option_chain.puts['strike'] == strike_price, 'lastPrice'].values[0]
# Display the option price
print("The latest {} option price for {} with strike price {} and expiry date {} is {:.2f}".format(option_type, symbol, strike_price, expiry, option_price))
In this program, we use the yfinance
library to retrieve the option chain for the given stock symbol and expiry date. We then extract the latest option price for the given strike price and option type (call or put). Finally, we display the option price to the user. Note that you'll need to install the yfinance
library if you haven't done so already, using pip install yfinance
.
沒有留言:
張貼留言