CoolFace
Apppublic

toonchien/Options

sourceHugging Faceupdated 3mo agoView on Hugging Face
0likes
app.py299 linesDownload Raw Back to root
1# -*- coding: utf-8 -*-2"""Untitled8.ipynb3 4Automatically generated by Colab.5 6Original file is located at7    https://colab.research.google.com/drive/1-trZwwGMPWA_C9u7gec4eHux9sPbaADQ8"""9 10#!pip install pandas gradio yfinance11 12import gradio as gr13import pandas as pd14import yfinance as yf15from datetime import datetime16from dateutil.relativedelta import relativedelta17import tempfile18import os19 20 21def scan_options(ticker, strike_price, months):22 23    try:24        ticker = ticker.upper().strip()25 26        stock = yf.Ticker(ticker)27 28        hist = stock.history(period="1d")29 30        if hist.empty:31            return "Invalid Ticker", pd.DataFrame(), None32 33        current_price = float(hist["Close"].iloc[-1])34 35        today = datetime.today()36        max_expiry = today + relativedelta(months=int(months))37 38        results = []39 40        for expiry in stock.options:41 42            expiry_date = datetime.strptime(43                expiry,44                "%Y-%m-%d"45            )46 47            # Filter by selected months48            if expiry_date > max_expiry:49                continue50 51            try:52 53                chain = stock.option_chain(expiry)54 55                days_to_expiry = max(56                    (expiry_date - today).days,57                    158                )59 60                # CALL OPTIONS61                calls = chain.calls62 63                matching_calls = calls[64                    calls["strike"] == strike_price65                ]66 67                for _, row in matching_calls.iterrows():68 69                    premium = float(row["lastPrice"])70 71                    roi = (72                        premium /73                        strike_price74                    ) * 10075 76                    annualized_roi = (77                        roi *78                        365 /79                        days_to_expiry80                    )81 82                    results.append({83                        "Type": "CALL",84                        "Expiration": expiry,85                        "Days": days_to_expiry,86                        "Stock Price":87                            round(current_price, 2),88                        "Strike":89                            row["strike"],90                        "Premium":91                            premium,92                        "Bid":93                            row["bid"],94                        "Ask":95                            row["ask"],96                        "Volume":97                            row["volume"],98                        "Open Interest":99                            row["openInterest"],100                        "IV (%)":101                            round(102                                row["impliedVolatility"] * 100,103                                2104                            ),105                        "Breakeven":106                            round(107                                row["strike"] + premium,108                                2109                            ),110                        "ROI (%)":111                            round(roi, 2),112                        "Annualized ROI (%)":113                            round(114                                annualized_roi,115                                2116                            )117                    })118 119                # PUT OPTIONS120                puts = chain.puts121 122                matching_puts = puts[123                    puts["strike"] == strike_price124                ]125 126                for _, row in matching_puts.iterrows():127 128                    premium = float(row["lastPrice"])129 130                    roi = (131                        premium /132                        strike_price133                    ) * 100134 135                    annualized_roi = (136                        roi *137                        365 /138                        days_to_expiry139                    )140 141                    results.append({142                        "Type": "PUT",143                        "Expiration": expiry,144                        "Days": days_to_expiry,145                        "Stock Price":146                            round(current_price, 2),147                        "Strike":148                            row["strike"],149                        "Premium":150                            premium,151                        "Bid":152                            row["bid"],153                        "Ask":154                            row["ask"],155                        "Volume":156                            row["volume"],157                        "Open Interest":158                            row["openInterest"],159                        "IV (%)":160                            round(161                                row["impliedVolatility"] * 100,162                                2163                            ),164                        "Breakeven":165                            round(166                                row["strike"] - premium,167                                2168                            ),169                        "ROI (%)":170                            round(roi, 2),171                        "Annualized ROI (%)":172                            round(173                                annualized_roi,174                                2175                            )176                    })177 178            except Exception:179                continue180 181        if len(results) == 0:182 183            empty_df = pd.DataFrame({184                "Message": [185                    "No matching options found."186                ]187            })188 189            return (190                f"Current Stock Price: ${current_price:.2f}",191                empty_df,192                None193            )194 195        df = pd.DataFrame(results)196 197        df = df.sort_values(198            by="Annualized ROI (%)",199            ascending=False200        )201 202        csv_file = os.path.join(203            tempfile.gettempdir(),204            f"{ticker}_{strike_price}_{months}M_ROI.csv"205        )206 207        df.to_csv(csv_file, index=False)208 209        return (210            f"Current Stock Price: ${current_price:.2f}",211            df,212            csv_file213        )214 215    except Exception as e:216 217        return (218            "Error",219            pd.DataFrame({"Error": [str(e)]}),220            None221        )222 223 224with gr.Blocks(225    title="US Option ROI Scanner"226) as demo:227 228    gr.Markdown(229        """230        # ๐Ÿ“ˆ US Option ROI Scanner231 232        Enter:233 234        1. US Stock Ticker235        2. Strike Price236        3. Date Range (Months)237 238        Results include:239 240        - Calls & Puts241        - Premium242        - ROI %243        - Annualized ROI %244        - Breakeven245        - CSV Download246        """247    )248 249    with gr.Row():250 251        ticker = gr.Textbox(252            label="Ticker",253            placeholder="AAPL"254        )255 256        strike = gr.Number(257            label="Strike Price",258            value=200259        )260 261        months = gr.Number(262            label="Date Range (Months)",263            value=6,264            precision=0265        )266 267    scan_btn = gr.Button(268        "Scan Options"269    )270 271    stock_price = gr.Textbox(272        label="Current Stock Price"273    )274 275    results = gr.Dataframe(276        label="ROI Results",277        interactive=False278    )279 280    csv_download = gr.File(281        label="Download CSV"282    )283 284    scan_btn.click(285        fn=scan_options,286        inputs=[287            ticker,288            strike,289            months290        ],291        outputs=[292            stock_price,293            results,294            csv_download295        ]296    )297 298if __name__ == "__main__":299  demo.launch(share=True)