stock option analysis
Drop files here
or click to upload
import streamlit as st
import yfinance as yf
import pandas as pd
import numpy as np
import plotly.graph_objects as go
from datetime import datetime, timedelta
st.title('Stock Option Analysis')
# Sidebar inputs
ticker = st.sidebar.text_input('Stock Ticker', 'AAPL').upper()
today = datetime.today()
expiry_dates = pd.date_range(today, today + timedelta(days=365), freq='W-FRI')
expiry = st.sidebar.selectbox('Option Expiry Date', expiry_dates)
analysis_type = st.sidebar.radio('Analysis Type', ['Calls', 'Puts'])
try:
# Get stock data
stock = yf.Ticker(ticker)
current_price = stock.info['regularMarketPrice']
st.write(f"Current {ticker} Price: ${current_price:.2f}")
# Get options chain
options = stock.option_chain(expiry.strftime('%Y-%m-%d'))
if analysis_type == 'Calls':
chain = options.calls
option_type = 'Call'
else:
chain = options.puts
option_type = 'Put'
# Calculate implied volatility and other metrics
chain['Premium'] = chain['ask'] + chain['bid'] / 2
chain['IntrinsicValue'] = np.where(
option_type == 'Call',
np.maximum(current_price - chain['strike'], 0),
np.maximum(chain['strike'] - current_price, 0)
)
chain['TimeValue'] = chain['Premium'] - chain['IntrinsicValue']
# Display options chain
st.subheader(f'{ticker} {option_type} Options Chain')
st.dataframe(chain[['strike', 'Premium', 'IntrinsicValue', 'TimeValue', 'volume', 'openInterest', 'impliedVolatility']])
# Plot payoff diagram
strikes = chain['strike'].values
premiums = chain['Premium'].values
fig = go.Figure()
# Generate price range for x-axis
price_range = np.linspace(current_price * 0.7, current_price * 1.3, 100)
for i, strike in enumerate(strikes):
premium = premiums[i]
if option_type == 'Call':
payoff = np.maximum(price_range - strike, 0) - premium
else:
payoff = np.maximum(strike - price_range, 0) - premium
fig.add_trace(go.Scatter(
x=price_range,
y=payoff,
name=f'Strike ${strike:.2f}',
hovertemplate='Stock Price: $%{x:.2f}<br>Profit/Loss: $%{y:.2f}'
))
fig.add_hline(y=0, line_dash="dash", line_color="gray")
fig.add_vline(x=current_price, line_dash="dash", line_color="red")
fig.update_layout(
title=f'{ticker} {option_type} Options Payoff Diagram',
xaxis_title='Stock Price',
yaxis_title='Profit/Loss',
showlegend=True
)
st.plotly_chart(fig)
# Risk analysis
st.subheader('Risk Analysis')
max_loss = -premiums.min()
max_profit = 'Unlimited' if option_type == 'Call' else strikes.min() - premiums.min()
col1, col2 = st.columns(2)
with col1:
st.metric('Maximum Loss', f'${max_loss:.2f}')
with col2:
st.metric('Maximum Profit', 'Unlimited' if max_profit == 'Unlimited' else f'${max_profit:.2f}')
except Exception as e:
st.error(f'Error: {str(e)}. Please check the ticker symbol and try again.')
Hi! I can help you with any questions about Streamlit and Python. What would you like to know?