<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by K4096K on Medium]]></title>
        <description><![CDATA[Stories by K4096K on Medium]]></description>
        <link>https://medium.com/@k4096k?source=rss-c059fd00a0db------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*-Go9XkqZfG4pfy7g0Og-kQ.png</url>
            <title>Stories by K4096K on Medium</title>
            <link>https://medium.com/@k4096k?source=rss-c059fd00a0db------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 17:57:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@k4096k/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[A safe Android for Kids]]></title>
            <link>https://medium.com/@k4096k/a-safe-android-for-kids-eb9f63973312?source=rss-c059fd00a0db------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb9f63973312</guid>
            <category><![CDATA[eosnetworkfoundation]]></category>
            <category><![CDATA[kids]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[parental-control]]></category>
            <dc:creator><![CDATA[K4096K]]></dc:creator>
            <pubDate>Wed, 04 Jun 2025 20:40:43 GMT</pubDate>
            <atom:updated>2025-06-11T19:39:22.688Z</atom:updated>
            <content:encoded><![CDATA[<p>A regular smartphone or tablet can be unsafe for a child. Unfiltered content, confusing interfaces, and distracting apps aren’t ideal when you’re trying to balance fun with learning. Kid-friendly Android devices solve this by offering a safer, more focused environment.</p><p>You can rely on Google Family Link or other parental control apps — but in my experience, they’re far from working as expected. Kids are surprisingly clever at finding ways around restrictions, and these apps often come with their own issues. They can be buggy, behave unpredictably on certain Android versions, or get disabled temporarily due to system triggers like battery saver modes. For instance, I tested one on a spare Xiaomi Mi 10T Pro, and MIUI (Xiaomi’s custom Android skin) proved particularly problematic, frequently interfering with parental controls. Blocked apps were not really blocked, kid was playing when the phone was supposed to be locked, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*tGf2w01Gfep7Pyfo.png" /></figure><p>Combine unreliable parental control apps with unrestricted browser access, and you’ve got a recipe for trouble. Kids can easily stumble upon inappropriate content. Games are another weak spot — many include built-in chat or social features that are hard, if not impossible, to fully monitor.</p><p>I won’t pretend the setup presented here is 100% foolproof. You should think of your child as a miniature hacker, constantly testing the system. That’s how it works: hackers find loopholes, those get patched, and new ones emerge. It’s a constant cycle. But the good news is, as you close each gap, the process becomes increasingly difficult for them. That’s the mindset you need — stay ahead, adapt, and know it’s a long game.</p><h3>/e/OS</h3><p>In this article, I want to introduce you to a special version of Android called <strong>/e/OS</strong>.</p><p><a href="https://e.foundation/e-os/">https://e.foundation/e-os/</a></p><p>It is based on the open source LineageOS. According to its creators, it’s an alternative to get a complete, fully “deGoogled”, mobile ecosystem:</p><blockquote>“/e/OS is an open-source mobile operating system paired with carefully selected applications. They form a privacy-enabled internal system for your smartphone. And it’s not just claims: open-source means auditable privacy. /e/OS has received academic recognition from researchers at the University of Edinburgh and Trinity College Dublin.”</blockquote><p>One key advantage of /e/OS is that it comes without the usual bloatware you typically find on devices from major manufacturers. The system is clean, lightweight, and focused. The current version is 3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*sQtJLwQfH50M2gkr.png" /><figcaption>/e/OS screen</figcaption></figure><p>Even more importantly, parental controls are built directly into the OS itself — not added on through a third-party app. This makes a big difference. External apps often run into limitations: they lack deep system access, may conflict with system settings, or get disabled by battery savers or background process restrictions.</p><p>Because the parental control features are natively developed by the /e/OS team, they’re tightly integrated, more stable, and far less prone to the typical issues you’d encounter on standard Android systems.</p><h3>Verify Compatibility</h3><p>This is where things get a bit tricky — it largely depends on the smartphone model you have. /e/OS supports a wide range of devices, and they even sell phones preloaded with /e/OS for a plug-and-play experience. However, older models may be only partially supported — or not supported at all.</p><p>The first step is to check whether your device is listed on their official website. As of this writing, around 225 Android models are supported, but compatibility can vary in terms of features and stability.</p><p><a href="https://doc.e.foundation/devices">Smartphone Selector</a></p><p>If your device is compatible — as was the case with the Xiaomi Mi 10T Pro — you can proceed with the installation by following the official documentation, which is clear and well-written. Keep in mind that the installation process will completely wipe your phone, so be sure to back up all important data beforehand.</p><h3>Recovery and Installation</h3><p>For Xiaomi devices, there’s an extra step before you can install /e/OS: you need to unlock the bootloader using a dedicated tool provided by Xiaomi. This tool links the request to your MIUI account, and unfortunately, you can’t unlock the device immediately . You usually have to wait a few days before the process can be completed. Once unlocked, you gain access to low-level functions needed to install a custom operating system.</p><p>On Samsung devices, the process is generally easier and better documented, thanks to their wide market presence and active developer community.</p><p>Regardless of the brand, most installations follow several steps:</p><ul><li>Switch the phone to developer mode and enable USB debugging. You will need to connect your phone to your computer, use a cable that supports data transfer.</li><li>Install adb and fastboot tools to execute some actions on the phone from the command prompt in Windows</li><li>Install a custom recovery. This is a low-level interface (like TWRP) that runs before the operating system and allows you to flash custom software.</li><li>Use the custom recovery to install /e/OS . Once the recovery is in place, you can load the /e/OS image and install it onto your device.</li></ul><p>Make sure to follow the exact instructions provided for your specific model as details can vary significantly between manufacturers.</p><p>For the Xiaomi, I downloaded two files that were pushed onto the smartphone using adb/fastboot.</p><ul><li>recovery-e-3.0-a14–20250530496779-community-apollon.img</li><li>e-3.0-a14–20250530496779-community-apollon.zip</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/343/1*Au6pkASPI8rOreH4SIeMjA.png" /><figcaption>Recovery App</figcaption></figure><h3>Parental Control</h3><p>When the OS is installed, you will notice that it’s very lightweight. No bloatware, no Google account to setup. Just enter some basic information and an access to a Wifi. The set of preinstalled applications is limited.</p><p>Depending on your goal, you can enable parental control directly from Settings. There, you can set restrictions such as blocking app installations and limiting daily phone usage time. You can also enter the age range of the kid to offer a more appropriate access. The controls are basic but effective.</p><p>When enabled, parental control changes the device’s DNS settings to Cloudfare Safe DNS to block access to most unwanted content on the preinstalled browser. While it’s not 100% foolproof — there are always ways to bypass restrictions — it works well in practice. Note that browser settings become locked when parental control is active.</p><blockquote>Cloudflare Family DNS helps keep kids safe online by:<br>- Blocking adult content<br>- Filtering out malware and phishing sites<br>- Preventing access to violent or harmful content<br>- Limiting access to age-inappropriate content</blockquote><p>I recommend trying the OS without parental control first to customize settings (like changing the default search engine), then enabling parental controls afterward.</p><p><a href="https://doc.e.foundation/support-topics/parental-control">Parental Control on /e/OS</a></p><h3>Playing with installed Apps</h3><p>As mentioned before, /e/OS comes with a set of predefined apps including a browser but also a store called “App Lounge” that allows you to install the apps you would normally grab from Google Store.</p><p>In my case, I wanted to:</p><ul><li><strong>Discard the browser.</strong> This was a top priority.</li><li><strong>Discard the App Lounge.</strong> Second priority to avoid attempts to install apps or even browse them, even if this is blocked by the built-in parental control.</li><li><strong>Remove access to most preinstalled apps</strong>. I did not want the kid to play with the messages, phone, agenda, etc.</li></ul><p>Problem is that /e/OS does not allow you to disable/uninstall these applications, you will see that the option is greyed out. But there is a way…</p><p>To do this, it is necessary to switch the phone to developer mode and enable the <strong>USB debugging</strong>. This is exactly the same step as the one done to prepare the installation of /e/OS.</p><p>Using adb, you can get a list of installed apps:</p><p><em>&gt;</em><strong><em> adb shell pm list packages</em></strong></p><p>You will get a list of long list of packages. Most of them are services that are part of Android and should <strong>not </strong>be touched. But there are also applications that you may want to totally remove.</p><p><em>package:com.android.phone<br>package:foundation.e.mail<br>package:foundation.e.apps<br>(…)</em></p><p>The apps called “foundation.*” are those provided by /e/OS. With adb, it is then very easy to uninstall an application. Positive point here is that /e/OS does not require root rights to perform that.</p><p>But before doing so, we will first make a <strong>backup </strong>of the app on our machine, Android applications are packaged in .apk files.</p><p>&gt; <strong><em>adb shell pm path [name_of_package]</em></strong></p><p>It returns a string like “package:system/….”. The part after “package:” is the path on the smartphone and can be used to download the apk:</p><p>&gt; <strong>adb pull &lt;path_of_apk&gt;</strong></p><p>At this point, you should have a local copy of the .apk</p><h4>Example</h4><p>For example, to totally uninstall the browser, you can do:</p><p>&gt;<strong> adb shell pm path foundation.e.browser</strong><br>package:/product/app/Browser/Browser.apk</p><p>&gt; <strong>adb pull /product/app/Browser/Browser.apk</strong><br>/product/app/Browser/Browser.apk: 1 file pulled, 0 skipped. 40.3 MB/s (54003387 bytes in 1.278s)</p><p><strong>&gt; adb shell pm uninstall — user 0 foundation.e.pdfviewer</strong></p><h4>Finding the technical name</h4><p>If you’re unsure about the app’s technical name (package name), you can find it by going to:<br><em>Settings → Applications → See all applications.</em><br>Tap on the app, scroll to the bottom, and you’ll see the package name listed on the last line.</p><h3>Uninstallation of Commons Apps</h3><p>To avoid the hassle of going through all commands, we will make a few scripts to help ourselves.</p><p>At this point, it is highly recommended to install the additional apps you want before proceeding. By default, my scripts will uninstall the “Apps Lounge” that is the equivalent of the Google Store.</p><h4>Pull_apk.bat</h4><p>First create a script called “<strong>pull_apk.bat</strong>” with the following content:</p><pre>@echo off<br>setlocal enabledelayedexpansion<br><br>REM Check if package name is provided<br>if &quot;%~1&quot;==&quot;&quot; (<br>    echo Usage: %~nx0 package.name<br>    exit /b 1<br>)<br><br>set PACKAGE=%1<br><br>REM Get the path of the APK<br>for /f &quot;tokens=2 delims=:&quot; %%A in (&#39;adb shell pm path %PACKAGE%&#39;) do (<br>    set APKPATH=%%A<br>    set APKPATH=!APKPATH:~1!<br>)<br><br>REM Pull the APK<br>echo Pulling !APKPATH! ...<br>adb pull &quot;!APKPATH!&quot;</pre><h4>Pull_all_apks.bat</h4><p>Then create another script called “<strong>pull_all_apks.bat</strong>”</p><pre>@echo off<br>call pull_apk.bat com.android.contacts<br>call pull_apk.bat com.android.dialer<br>call pull_apk.bat com.android.documentsui<br>call pull_apk.bat com.android.phone<br>call pull_apk.bat foundation.e.apps<br>call pull_apk.bat foundation.e.browser<br>call pull_apk.bat foundation.e.calendar<br>call pull_apk.bat foundation.e.mail<br>call pull_apk.bat foundation.e.message<br>call pull_apk.bat foundation.e.notes<br>call pull_apk.bat foundation.e.pdfviewer <br>call pull_apk.bat foundation.e.tasks<br>call pull_apk.bat org.lineageos.recorder</pre><h4>Uninstall_apps.bat</h4><p>Finally, create a script called “uninstall_apps.bat”</p><pre>@echo off<br>adb shell pm uninstall --user 0 com.android.contacts<br>adb shell pm uninstall --user 0 com.android.dialer<br>adb shell pm uninstall --user 0 com.android.documentsui<br>adb shell pm uninstall --user 0 com.android.phone<br>adb shell pm uninstall --user 0 foundation.e.apps<br>adb shell pm uninstall --user 0 foundation.e.browser<br>adb shell pm uninstall --user 0 foundation.e.calendar<br>adb shell pm uninstall --user 0 foundation.e.mail<br>adb shell pm uninstall --user 0 foundation.e.message<br>adb shell pm uninstall --user 0 foundation.e.notes<br>adb shell pm uninstall --user 0 foundation.e.pdfviewer <br>adb shell pm uninstall --user 0 foundation.e.tasks<br>adb shell pm uninstall --user 0 org.lineageos.recorder</pre><p>Before going further, <strong>review the two last files</strong> and adapt it if you want to keep some apps! Just consider these scripts as a starting point.</p><p>First execute “pull_all_apks.bat”, it should download all the apks in your current folder. If this is fine, you can then run “uninstall_apps.bat”.</p><p>If you want to reinstall one of the uninstalled apk, you can easily do that using adb again, for example with AppLounge:</p><p><strong>&gt;adb install AppLounge.apk</strong><br>Performing Streamed Install<br>Success</p><p>Note that if you happen to lose your backup apks, you can still find them on the Android phone itself as you had prepared them for pulling, they are stored in either <em>system/app/ </em>or<em> product/priv-app</em></p><p>&gt;<strong> adb shell ls -l product/priv-app</strong></p><p>Then in subfolders, you will find the different apks.</p><h3>Example of my “hardened” phone</h3><p>I installed a few safe, kid-friendly apps relevant to Switzerland — like weather apps, map tools, Deezer for music, and Wikipedia Beta. I specifically tested Wikipedia to ensure it doesn’t allow access to external links, and it worked as expected since no browser was available. While some Wikipedia articles might touch on sensitive topics, I consider it acceptable overall given the educational value.</p><p>As it stands, core apps like phone, messaging, and email are removed, leaving a clean environment. The only remaining potentially sensitive area is the Settings (Parameters) app. While parental control blocks parts of it, some settings remain accessible that a child ideally shouldn’t be able to modify.</p><p>Technically, it’s possible to disable the Settings app (<em>com.android.settings</em>), but I’m cautious about doing so — it could lead to unintended side effects or even lock you out if USB debugging is disabled and no recovery access is available. If you go down that path, be sure you have a reliable way back in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*tpa62XpaZppjw1mqc5_YGw.png" /><figcaption>Xiaomi MI 10T Pro running /e/OS with limited apps</figcaption></figure><h4>Finalize</h4><p>The final steps are:</p><ul><li>Disable USB debugging</li><li>Turn off developer mode (I do think it enforces USB debugging being stopped anyway)</li><li>Re-enable parental control from the Settings</li></ul><h4>Greetings</h4><p>Thanks to Fox, tcecyk and soldan of /e/OS forum for their initial feedbacks.<br><a href="https://community.e.foundation/t/my-article-about-an-hardened-e-os-for-kids/70625">https://community.e.foundation/t/my-article-about-an-hardened-e-os-for-kids/70625</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb9f63973312" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Easily Find Resistance/Support Areas With Ichimoku]]></title>
            <link>https://medium.com/the-investors-handbook/easily-find-resistance-support-areas-with-ichimoku-06b97bbae9f6?source=rss-c059fd00a0db------2</link>
            <guid isPermaLink="false">https://medium.com/p/06b97bbae9f6</guid>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[ichimoku]]></category>
            <category><![CDATA[technical-analysis]]></category>
            <dc:creator><![CDATA[K4096K]]></dc:creator>
            <pubDate>Sun, 01 Dec 2024 21:51:56 GMT</pubDate>
            <atom:updated>2024-12-02T02:34:01.569Z</atom:updated>
            <content:encoded><![CDATA[<p>The<strong> Ichimoku Kinko Hyo</strong>, often referred to simply as “Ichimoku,” is a technical indicator developed in Japan during the 1930s. It consists of various trend lines and a unique feature known as the “Cloud,” which traders commonly use to identify potential entry and exit points for their positions.</p><p>While Ichimoku can be a challenging indicator to master, with extensive literature dedicated to it, this article does not aim to provide a detailed introduction. Instead, its purpose is to demonstrate how you can easily use Ichimoku to identify key resistance and support levels without needing to fully master the intricacies of the indicator. Don’t be afraid by the look of the indicator.</p><p>While I approach Ichimoku with a swing trading or investment perspective, focusing on daily or weekly time horizons, the same principles can also be applied to shorter timeframes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3hAAJkShBXqsNp3Nyi6nIg.png" /><figcaption>Typical Ichimoku indicator on a stock</figcaption></figure><p>In this article, I will be interested into only <strong>two </strong>of the lines composing Ichimoku out of a total of 6 components:</p><ul><li><strong>The Kijun (</strong>“Kijun-sen<em>” </em>or KS<em>) </em>: it represents the average of the highest high + lowest low during the last 26 days</li><li><strong>The Senkou Span B </strong>(SSB): it represents the average of the highest high + lowest low during the last 52 days. In the system, it is plotted 26 periods ahead.</li></ul><p>For the examples in this article, I’ll use TradingView, though Ichimoku is available on nearly all trading platforms.</p><h3>Setting up</h3><p>In TradingView, I add the “Ichimoku Cloud” indicator and customize its settings to focus on the key components. I disable most of the elements and keep only the <strong>Base Line (Kijun)</strong> and the <strong>Leading Span B (SSB)</strong>. To make these lines more visually distinct, I set the Base Line to medium thickness (in violet) and the SSB to a thicker line (in blue). Of course, you can adjust the colors to suit your preference.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qytsbVqltuBMWO4J7xkRUA.png" /></figure><p>You may also notice that prices are displayed using Heikin-Ashi candles rather than traditional candlesticks. This is a personal preference, as I prioritize identifying general trends over analyzing the finer details of individual candles and wicks. I find that Heikin-Ashi candles effectively reduce unnecessary noise, making them particularly useful for my mid- to long-term analysis.</p><h3>Drawing the R/S Lines</h3><p>Once our simplified Ichimoku indicator is set up, we switch to the weekly chart view. The objective here is to identify key resistance and support (R/S) zones.</p><p>Our focus will be on the blue line, which represents the <strong>Leading Span B (SSB)</strong>. Recall that the SSB is calculated as the average of the highest high and lowest low over the past 52 periods. On a weekly chart, this equates to approximately one year of price data.</p><p>You’ll notice that in many areas, the blue line appears horizontal. This occurs when prices fail to establish new highs or lows during the calculation period, indicating a range-bound market. The longer the horizontal segment, the more extended the period of price consolidation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*woJq06p4zRFcJ-mKyEIjWQ.png" /></figure><p>It’s not necessary to account for <strong>all</strong> horizontal lines. Instead, focus on those that are relatively long and particularly those located at the top or bottom of a broader price move. Longer horizontal segments typically hold greater significance than shorter ones.</p><p>Once identified, extend each of these horizontal segments by drawing a line (you can use the shortcut <strong>Alt + H</strong> in TradingView). Your chart will then resemble this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fvKnAhL4fGGcT4fyAC7PVg.png" /></figure><p>Now, we can switch to a lower timeframe. Since we started with the weekly chart, we’ll move to the daily timeframe and zoom in on the portion that corresponds to roughly the last third of the weekly chart analyzed earlier.</p><p>As you’ll notice, this allows us to clearly identify areas where prices have reacted, making it easier to highlight key support and resistance zones.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r5OqPrsWk-j0pSn4qoBcKQ.png" /></figure><p>The horizontal lines you’ve identified can now be used to define resistance and support zones by drawing rectangles around them. If multiple horizontal lines are clustered within a small area, it strongly indicates that this is a zone where prices have frequently reacted. These zones often represent significant levels of market activity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_d9EqF2Lbwx68g71JKrg2A.png" /></figure><p>Interestingly, the price (IBB, 2024–12–01) is currently testing another line identified in the first step. There is a high probability that the price will either bounce off this level or break through the resistance. If the latter occurs, it might subsequently test the upper zone, marked by the violet rectangle.</p><h3>Using the Kijun</h3><p>The <strong>Kijun</strong> is the other line we’re using, calculated over a 26-period span, making it less robust than the SSB. However, it can still provide valuable insights.</p><p>In this example, we observe that the Kijun often acts as a resistance or support line, depending on market conditions. Additionally, many of the horizontal lines drawn earlier align with flat sections of the Kijun. This overlap is a strong indication that these levels are significant, as they elicit reactions from prices on both higher and lower timeframes.</p><p>Similar to the SSB, you can also draw horizontal lines on the flat segments of the Kijun. While this may add some noise to your analysis, it can be a useful approach if you feel it enhances your understanding of the price action.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*Y9YgdTEWS-j6x5jZEgBe4A.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=06b97bbae9f6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-investors-handbook/easily-find-resistance-support-areas-with-ichimoku-06b97bbae9f6">Easily Find Resistance/Support Areas With Ichimoku</a> was originally published in <a href="https://medium.com/the-investors-handbook">Investor’s Handbook</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rolling in Returns: How to Generate Income with the Wheel Strategy]]></title>
            <link>https://medium.com/the-investors-handbook/rolling-in-returns-how-to-generate-income-with-the-wheel-strategy-a549858d851a?source=rss-c059fd00a0db------2</link>
            <guid isPermaLink="false">https://medium.com/p/a549858d851a</guid>
            <category><![CDATA[income]]></category>
            <category><![CDATA[options-trading]]></category>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[options]]></category>
            <category><![CDATA[wheel-strategy]]></category>
            <dc:creator><![CDATA[K4096K]]></dc:creator>
            <pubDate>Sat, 09 Nov 2024 10:28:15 GMT</pubDate>
            <atom:updated>2024-11-10T17:09:47.155Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/832/0*5xuckMax1RKupYfG" /></figure><p>Options trading can be intimidating, often filled with strategies that seem complicated or high-risk. But the Wheel strategy (WS) stands out as a straightforward, income-focused approach that’s accessible to traders that are new to options. By combining two core tactics —<strong> selling cash-secured puts</strong> and <strong>covered calls</strong> — this strategy allows investors to create a steady income stream, one step at a time.</p><p>The WS works in a cycle, offering traders a disciplined way to buy and sell shares at prices they control. In this article, we’ll walk through the ins and outs of the WS, exploring how it works, its potential for income generation, and the risks involved. If you’re looking for a way to add a structured, reliable element to your trading, it may be worth considering.</p><p>Some of the material presented here is inspired by information provided by <em>Scottish Trader</em> on Reddit in his article <em>The Wheel (aka Triple Income) Strategy Explained article</em>. Full references are given at the end of the article.</p><p>It is assumed that the reader has some basic knowledges about options and terminology such as strike, expiration, call vs put, etc. You may be interested into reading <a href="https://medium.com/the-investors-handbook/unlocking-the-power-of-covered-calls-with-chatgpt-part-1-7734deab5421">my serie of 3 articles about covered calls</a>.</p><p>The Wheel Strategy is built on two fundamental options strategies: the covered call and the cash-secured put. Both involve an underlying asset — typically a carefully selected stock, as we’ll discuss later.</p><h4>Quick Recap about Options</h4><p>When you <em>own</em> a call option, you have the <em>right</em> (but not the obligation) to buy 100 shares of a stock at a predetermined price (known as the strike price) before the option expires. If you choose to exercise this right, the <em>seller</em> of the call is obligated to sell you the shares at that strike price. For this right, you pay a premium, which is the cost of the option contract.</p><p>In contrast, a put option gives the buyer the right to <em>sell</em> 100 shares at the strike price. If the put option holder decides to exercise, the seller of the put is required to buy the shares at that agreed-upon price.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*UUPzFT3aM51vTErnsG1h8Q.png" /><figcaption>For the wheel strategy, we will be on the seller side all the time.</figcaption></figure><p>The decision to exercise an option depends on the stock’s current market price, or spot price. If exercising the option would be advantageous (e.g., buying at a strike price lower than the current spot price or selling at a higher one), it may be worth acting on.</p><p>For the rest of the article, I assume that we are dealing with american-style options, i.e can be exercised at any time before expiration.</p><h4>Covered Calls</h4><p>The covered call (CC) strategy involves buying 100 shares of stock and then selling a call option on those shares to collect a premium. This strategy is considered “covered” because if the call buyer decides to exercise, you already own the shares and can sell them at the strike price without needing to buy them on the open market. Typically, the strike price is set higher than the current market price, meaning that if the option is exercised, you’ll sell at a profit. However, that profit is capped at the strike price, and you keep the premium received from selling the call.</p><p>If the stock price is declining without reaching the strike, you will still have 100 shares but the call you sold will expire worthless. From your standpoint, you will have grabbed a premium but you may now have 100 shares that can potentially have a lower price than your initial position price.</p><p>Additionally, you still have the flexibility to discard the position by buying back the call at any time before expiration, potentially locking in gains if the option has decreased in value. And of course, you can then sell the 100 shares. What happens with the remaining contract depends on the market price and your decision as a call holder.</p><p><strong>Rolling the Call</strong></p><p>Another alternative is to “roll the call” — selling a new call option either at the same strike price with a later expiration or at a higher strike price. This strategy allows you to maintain your position in the shares while adjusting the call to reduce the risk of the shares being called away if the strike price is reached. Meanwhile, you continue to earn premiums, enhancing potential returns.</p><p>Imagine this scenario: you hold a covered call, “A,” and the stock price is approaching the strike. The market trend is bullish, but you expect it to slow down in the coming week. With expiration just a few days away and a high likelihood of assignment, you decide to roll your call to keep your shares and continue collecting premiums. To do this, you buy back call “A,” locking in some profit, and immediately sell a new call, “B,” with a higher strike price and a later expiration. This adjustment gives the market more room to move without reaching your new strike, allowing you to maintain flexibility. You can repeat this rolling strategy as needed.</p><p>Some brokers even offer a one-step roll feature, so you don’t have to separately execute the buy and sell transactions — though note that this may affect commission fees.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*wN1HUlTBvFmgn6AW4Dt3sQ.png" /><figcaption>Rolling the call by buying back the initial call (A) and selling a new one (B)</figcaption></figure><p>The decision to roll a call is an art in itself, as is selecting the optimal expiration and strike for the new call. Rolling depends not only on market dynamics but also on factors like days to expiration (DTE), delta, and other option metrics. There is ongoing debate around these parameters and their importance. Some traders feel that rolling is unnecessary, preferring instead to let the option be assigned and move on. Others argue that rolling offers valuable flexibility, allowing more time if you have strong convictions about market trends — as in the example above, where a bullish outlook suggests the market may rise without necessarily reaching the new strike.</p><h4>Cash-secured Puts</h4><p>In a cash-secured put (CSP) strategy, instead of selling a call, you sell a put option and collect a premium, with the understanding that you may need to buy 100 shares at the strike price if the option is exercised. However, unlike an “uncovered” put, where funds may not be set aside, in a CSP you reserve enough capital to cover the potential purchase. This ensures the put is fully “cash-secured,” much like holding shares in a covered call strategy.</p><p>If the stock price stays above the put’s strike price, the put holder is unlikely to exercise it, as they could sell shares at a higher price on the open market. However, if the stock price drops below the strike price, the put holder may choose to exercise, requiring you to buy the shares at the strike price using your cash-secured reserve. If the stock continues to decline after you acquire the shares, you may end up paying more than the market value, potentially leading to a paper loss on your position.</p><h4>Wheel Principles</h4><p>The Wheel strategy involves a continuous cycle of selling cash-secured puts and covered calls on the same underlying asset. While stock selection is crucial — arguably more important than the strategy’s mechanics — let’s first look at the main steps involved. I’ll also mention some parameters recommended by <em>Scottish Trader</em> in his well-regarded article.</p><p><strong>Suppose you’ve identified a suitable stock for this approach, with a current spot price just above $22</strong>.</p><h4><strong>Step 1</strong></h4><p>The first step of the Wheel Strategy involves selling a cash-secured put, aiming to balance risk with premium income. To optimize this tradeoff, consider the following guidelines:</p><ul><li>Set the expiration between 30–45 days.</li><li>Choose a strike price that is moderately out-of-the-money (OTM).</li><li>Target a delta around -0.3, indicating roughly a 30% probability of ending in-the-money (ITM) and a 70% chance of remaining OTM.</li></ul><p>This approach helps manage assignment risk while maximizing the premium potential.</p><p><strong>Initial CSP</strong></p><p>With the current spot price at $22, we choose a put contract expiring in one month with a $19 strike price and sell the cash-secured put (CSP). To cover potential assignment, we set aside $1,900 in cash while the put is open:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*Nh48r_hooo5spED2gwrd-Q.png" /></figure><p>The stock price decreases a bit and after 30 days (expiration), it is not assigned.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/845/1*iWcyoaeR5PG-uyhqAyX0JQ.png" /></figure><p><strong>Rolling the CSP</strong></p><p>We decide to roll our put at the same $19 strike for the next 30 days, collecting a higher premium this time as the option is now closer to being at-the-money (ATM). However, the market subsequently drops below the strike price, resulting in assignment: <strong>we are required to purchase 100 shares at $19 each, totaling $1,900</strong>. At the time of assignment, the market price is $18.50, meaning we are acquiring the shares at a slightly higher cost due to the put.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1021/1*O9dv4-46W0i-Tq5z26Hu6g.png" /></figure><p>This is the outcome of this first phase with the CSP.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*cUIHeh8DnDHMdaMHEpYs5g.png" /></figure><h4><strong>Step 2</strong></h4><p>You now own 100 shares at $19 each, while the market price is around $18.50. <strong>So, what’s the next step?</strong> You can implement the opposite strategy by selling a covered call. Choose an OTM strike with an expiration similar to the one used for the put — typically around 30 days. This allows you to generate additional premium income while holding your shares.</p><p><strong>Initial CC<br></strong>We select a call option with a strike price above our entry price of $19 and decide to sell a covered call with a $20 strike. In return, we collect the premium associated with the trade.</p><p>After 30 days, the call expires worthless, as it is not exercised, meaning we keep our shares and retain the premium income.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*GlasuimxyMUixzWeyDcRNw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/1*bR5xnkqIqBg0Ns6vkiXJeg.png" /></figure><p>We decide to wait a few days with just our shares in position (all the options are gone) because <strong>an ex-dividend date is announced</strong>. <strong>We collect the dividend on our stock.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*_KlMQlS7N5FeX2bgnKXwgA.png" /></figure><p>After the dividend, the stock price returns to the $18.50 range. We decide to try again by selling a covered call with a $20 strike price.</p><p>Midway through the contract, the CEO makes a statement that causes the stock to surge above our strike price. However, the call is not immediately exercised. The call holder waits until expiration, and ultimately, the stock price settles just above the strike. As a result, <strong>the call is exercised, and we are required to sell our 100 shares at the $20 strike price</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*L4aS8NoZTj40We06gTpyfg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*vG308F4waTr2vVXv8oCreA.png" /></figure><p>The Wheel strategy is now complete, and we’ve made a profit from the premiums collected along the way, as well as the dividend we were able to capture in between.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/657/1*oEn_TWxee7MmdxXFhSwl_w.png" /></figure><p><strong>However, it’s important to note that this is a favorable outcome.</strong> The strategy doesn’t always play out this smoothly, as market conditions and stock movements can vary, sometimes leading to different results.</p><h4>The Unhappy Scenarios and Remedations</h4><p>Several things can go wrong throughout the different stages of the Wheel strategy.</p><ul><li>The <strong>biggest risk</strong> is that the cash-secured put gets assigned, but the stock continues to decline, or worse, collapses if you’ve chosen a “falling knife.” In this case, you would find yourself holding 100 shares with an unrealized loss. Additionally, because your entry price is far from the current spot price, you may struggle to sell a covered call with a meaningful premium. This leaves you stuck in the first phase of the Wheel, potentially waiting a long time for the stock to recover. At this point, it’s similar to simply buying and holding the stock, with all the associated risks.</li><li>Another pitfall is impatience — rolling positions too early or making poor choices with strikes or expirations, resulting in less premium than expected. It’s important to “read” the market through multiple lenses, including technical analysis, fundamentals, and other factors, to make more informed decisions.</li><li>Be cautious around earnings reports, FOMC announcements, or other major events, as stocks can experience significant fluctuations, and option bid/ask spreads can widen.</li><li>It’s also important to remember that at any time, you can buy back your position — whether at a profit or a loss — and trade the shares if the strategy is no longer working. This flexibility allows you to adjust your approach when market conditions aren’t favorable or when more attractive opportunities arise. Sometimes, it’s better to change direction than to force a strategy that no longer fits the current market.</li></ul><p><strong>The strategy works best when you’re not assigned, allowing you to continue collecting attractive premiums while holding a stock that appreciates in value</strong>. When executed correctly, you not only earn premiums but may also see capital gains from the stock itself. This is why selecting the right stock is crucial.</p><ul><li>The first key rule is to only apply the strategy to stocks you would be comfortable holding long-term. Ensure the stock you choose has strong fundamentals and promising future prospects.</li><li>The second important rule is to target stocks that are either trading sideways or mildly bullish. While you may experience occasional bearish phases, the stock should generally remain flat or rise to avoid the risks associated with cash-secured puts. Remember, the Wheel strategy is meant for longer-term timeframes, not for quick, intraday scalping.</li><li>Avoid volatile or speculative stocks, particularly those in unstable sectors like crypto. Volatility is detrimental to this strategy, as it increases the chances of assignment when you don’t want it. The goal is to continue collecting premiums, not to be forced into unwanted positions.</li><li>Steer clear of penny stocks, you may be tempted to switch to shares with a low price if you lack the capital needed to secure the options and cover the cost of 100 shares but this is not recommended. If you have limited funds, consider investing in an ETF that uses a covered call strategy instead.</li><li>Ultimately, you’re looking for “boring” stocks with a steady dividend — these can provide additional income, as seen in the example. Such stocks tend to grow slowly but steadily, offering a stable foundation for the Wheel strategy.</li></ul><p>For a deeper understanding of this strategy, I highly recommend reading the article by <em>Scottish Trader</em>. You can find the link below.</p><h3>References</h3><p><em>Scottish Trader</em> on the Wheel Strategy — <a href="https://www.reddit.com/r/options/comments/a36k4j/the_wheel_aka_triple_income_strategy_explained/">https://www.reddit.com/r/options/comments/a36k4j/the_wheel_aka_triple_income_strategy_explained/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a549858d851a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-investors-handbook/rolling-in-returns-how-to-generate-income-with-the-wheel-strategy-a549858d851a">Rolling in Returns: How to Generate Income with the Wheel Strategy</a> was originally published in <a href="https://medium.com/the-investors-handbook">Investor’s Handbook</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Covered Call Strategy using Stochastics — Part 2]]></title>
            <link>https://medium.com/the-investors-handbook/exploring-covered-call-strategy-using-stochastics-part-2-aea5d52c0689?source=rss-c059fd00a0db------2</link>
            <guid isPermaLink="false">https://medium.com/p/aea5d52c0689</guid>
            <category><![CDATA[covered-call]]></category>
            <category><![CDATA[options]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[stochastic-modelling]]></category>
            <category><![CDATA[trading]]></category>
            <dc:creator><![CDATA[K4096K]]></dc:creator>
            <pubDate>Fri, 01 Nov 2024 21:34:49 GMT</pubDate>
            <atom:updated>2024-11-02T00:46:30.751Z</atom:updated>
            <content:encoded><![CDATA[<h3>Exploring Covered Call Strategy using Stochastics — Part 2</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*2TrgTgU0N8KNrzcDCw2bOA.png" /></figure><p>In today’s dynamic financial markets, traders and investors are continuously seeking strategies that balance risk and reward. One such popular method is the covered call strategy, often utilized to generate additional income from existing stock holdings. In my first serie of articles, “<strong>Unlocking the Power of Covered Calls using ChatGPT</strong>” (<a href="https://medium.com/the-investors-handbook/unlocking-the-power-of-covered-calls-with-chatgpt-part-1-7734deab5421">Part 1</a>,<a href="https://medium.com/@k4096/unlocking-the-power-of-covered-calls-with-chatgpt-part-2-0648e98a72e7"> Part 2</a>, P<a href="https://medium.com/@k4096k/unlocking-the-power-of-covered-calls-with-chatgpt-part-3-e3521ac8302d">art 3</a>), I introduced the foundational concepts of covered calls and outlined key criteria to consider when developing an effective strategy.</p><p>In Part 1 of <a href="https://medium.com/the-investors-handbook/exploring-covered-call-strategy-using-stochastics-part-1-397ba97b581e"><em>Exploring the Covered Call Strategy Using Stochastics</em></a>, I introduced a simple model to simulate stock price evolution over time, then transitioned to a more complex model based on the Black-Scholes formula. With the help of ChatGPT, we developed a script to handle this simulation, which paved the way for Monte Carlo simulations where we generated multiple potential price paths over time. We also explored how this tool could be applied in the context of a covered call strategy.</p><p>In this second part, we will take things further by automating part of the decision-making process. We will consider the recommendations of Mauricio Diaz in his thesis <em>Stochastic Optimization of Covered Call Strategies.</em>We’ll implement the covered call strategy across various expiration dates and strike prices, using Monte Carlo simulations to analyze the outcomes.</p><h4><strong>The challenge of American-style Options</strong></h4><p>Before diving deeper into our experimentation with different models, it’s essential to address a key concept in options trading: the difference between <strong>European</strong> and <strong>American-style options</strong>.</p><p>The key difference lies in when they can be exercised. European options can only be exercised at the <strong>expiration date</strong>, meaning the holder must wait until the option’s maturity to decide whether to exercise. In contrast,<strong> </strong>American options can be exercised <strong>at any time before or at expiration</strong>, providing more flexibility to the holder. This flexibility can be valuable, especially if the option becomes profitable before expiration or if the underlying asset pays dividends.</p><p>If you are the owner of a call option, you could decide to exercise your right and buy the stock at the strike price. However this is not advised if the stock does not pay dividends. Imagine you hold a call option trading at $10 per share with a strike price of $50, while the current market price of the stock is $57 and the option expires in two weeks. If you exercise the call, you would buy the stock at $50 and sell it immediately at $57, making a $7 profit per share. However, since the call’s price is $10, only $7 is the <strong>intrinsic value</strong>, and the remaining $3 is <strong>extrinsic value</strong> (representing time and volatility). By exercising early, you lose this $3 in extrinsic value. Therefore, it would be wiser to hold the option, hoping for further price increases, or sell the option for its full market value of $10, rather than exercising it early.</p><p>If a dividend is about to be issued, you might consider exercising your call early to acquire shares before the ex-dividend date. This allows you to capture the dividend, which you would miss by holding the option, and avoid the typical stock price drop equal to the dividend amount, which reduces the call’s intrinsic value.</p><p>In a covered call, as the seller, you generally don’t need to worry about early exercise unless a dividend is involved. This allows you to hold onto your shares longer and benefit from any potential price increase. For simplicity, <strong>we’ll assume the covered call behaves like a European option</strong>, exercisable only at expiration, and ignore dividend-related factors.</p><p>A note about the puts: they come with unique considerations, especially when it comes to exercising them. They operate differently than the calls and require distinct strategies and timing.</p><h4><strong>Diaz Thesis on Covered Calls</strong></h4><p>In 2019, Mauricio Diaz published a thesis called <em>Stochastic Optimization of Covered Call Strategies</em> which covers various strategies, including those based on multiple assets. As it is often the case with technical papers about options, it is quite heavy on maths but there are some interesting observations.</p><p>In chapter 2 which is focusing on single-asset covered calls, the author indicates the following in the context of <strong>strong aversion to risk:</strong></p><blockquote>Maximizing the expected return of a covered call strategy on a given asset position is equivalent to minimizing the call risk premium of options sold</blockquote><p>When selling a call, the seller faces the risk that the option could be exercised, capping their potential profit. To compensate for this risk, the option includes a “risk premium.” This premium reflects factors like volatility, which increases option prices due to the likelihood of the strike being hit and the chance of significant price drops. High expectations for the underlying asset can also raise the option price, as owning the shares might offer more upside than the capped profit of the covered call, necessitating compensation for this risk to the seller.</p><p>By minimizing the risk premium, selling occurs at a “fair price” and optimize the return vs unjustified risks. He adds:</p><blockquote>Selling calls produces a liability which reduces up-side returns and provides a premium that increases down-side returns. Call options with high premiums and low strike prices provide the largest down-side benefit and largest up-side liability making them most effective in minimizing risk. Therefore, to minimize variance, semivariance, VaR, or CVaR, it is optimal (to pick the option that) has the lowest strike price of the options available. Thus, if we are not considering options which are in-the-money, a sufficiently risk averse investor always ought to sell the maximum amount of ATM options.</blockquote><p><strong>In short, if you have a high aversion for risk and you want to minimize it while having the best tradeoff for return, you should aim at the lowest strike possible that is not ITM.</strong></p><p>Regarding the best expirations, there is no clear consensus but the shorter-term expirations (one week up to one month) offer attractive premiums. Diaz recommends longer expirations for investors with a more passive approach, as they allow for capturing time value more gradually and are less affected by sudden market moves but this depends on the strike level as we will see later on.</p><p>The author then explores other risk aversion profiles but before going further, what is the “risk”?</p><h4><strong>Definition of Risk(s)</strong></h4><p>There are many possible definitions depending upon your risk profile and your goals.</p><ul><li>In a covered call, you own shares, but if their price drops, the premium from the sold call may not fully cover the loss, leading to potential losses. This risk is quantified as <strong>Value-at-Risk (VaR)</strong> — for instance, a 95% VaR of $1000 means that 95% of the time, losses are below $1000, with a 5% chance they exceed this amount (and no indication on the maximum loss). <strong>Conditional Value-at-Risk (CVaR)</strong>, or <strong>Expected Shortfall</strong>, measures the average loss in those extreme 5% scenarios. So, if the 95% VaR is $1000, CVaR might indicate an average loss of $1500 beyond that threshold. Higher CVaR (e.g., $3000) suggests a riskier profile, even with the same VaR.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*73eRfB-BmmGvRJXL" /><figcaption>VaR and CVaR on the distribution of returns</figcaption></figure><ul><li>Random returns introduce risk because, while you may expect a steady $1000 each month, actual returns can vary widely — some months might bring only $200, while others yield $1500. This inconsistency in returns is measured by the “<strong>variance of return</strong>,” which quantifies how much returns fluctuate around the average.</li></ul><h4><strong>Risk Profile for Value-at-Risk (VaR)</strong></h4><p>I won’t cover all of Diaz’s risk management details here and encourage readers to check his paper. Notably, he examines different risk profiles, including those based on the VaR criteria.</p><blockquote>In the literature there is no consensus on how to best select strike prices of options to sell. Our methodology selects strike prices of options to sell based on risk-return optimality. <strong>Intermediate risk aversion values lead us to sell a blend of the ATM, 1.5% OTM, 2.4% OTM, 8.1% OTM, and 9.4% OTM options.</strong> Although there were many other options which could have been sold in this month the optimal mixes contain only these five.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*Ayuxn7Fjb2pxCW4WfhosMw.png" /><figcaption>Courtesy: Mauricio Diaz — Stochastic Optimization of Covered Call Strategies (2019).</figcaption></figure><p>In his thesis, the author presents several examples showing “mixes” for selling covered calls at different strikes, assuming a portfolio with multiple lots of 100 shares. Here, I’ve highlighted the “Value-at-Risk mix” with additional colored lines for clarity (not in the original).</p><p>To interpret this chart, <strong>observe how much of each colored line falls within each area</strong>. If you’re highly risk-averse, as indicated by the dark blue line, you would sell calls at the ATM strike, fully aligning with your conservative approach. Lowering risk aversion (light blue line), you’d mix strikes — around 1/3 ATM and the remaining at 1.5% OTM. For a moderate risk profile (orange line), the mix shifts to 50% at 1.5% OTM and 50% at 9.4% OTM, while the highest-risk (red line) places all positions at 9.4% OTM.</p><p>For example, if you prefer the “light blue” profile and have 300 shares, you’d sell one call at the ATM strike for 100 shares and two calls at 1.5% OTM for the other 200 shares.</p><p>For most small investors with limited capital, the funds needed for that kind of mix can be challenging. To make this more accessible, assuming a basket of 100 shares and a single call, we could simplify the approach as follows:</p><ul><li><strong>low risk → sell the ATM call</strong></li><li><strong>medium risk → sell the 1.5% OTM</strong></li><li><strong>high risk → sell the 9.4% OTM</strong></li></ul><blockquote>Our results suggest that from a risk-return perspective it is often optimal to sell combinations of call options with different strike prices for intermediate risk aversion. This result is relevant since in practice investors tend to have intermediate risk aversion since maximum return portfolios might have excessively high risk while minimum risk portfolios might provide very poor returns</blockquote><p>This may sound counterintuitive but selling deeper OTM options exposes the investor to <strong>tail risk</strong> — a low probability but high-magnitude risk if the stock price drops significantly. ATM options, while capping upside, reduce this exposure by generating consistent premium income.</p><p>We will illustrate this with real examples in the last part of the article.</p><h4><strong>Retrieving the Options Chain</strong></h4><p>Before going any further, we need to get our hands on the options chain corresponding to the ticker. We pick the last script of the series about Uncovered Call (<strong>please refer to the part 3 of </strong><a href="https://medium.com/the-investors-handbook/unlocking-the-power-of-covered-calls-with-chatgpt-part-3-e3521ac8302d"><strong>Unlocking the Power of Covered Calls with ChatGPT</strong></a>) and manually incorporate the functions into our Black-Scholes script. You could use ChatGPT for this but it’s more a hassle than to do it manually, this is where having some programming skills is handy. We must also not blindly trust the AI, it can generate code that is incomplete or incorrect.</p><p>We then pick the function “<em>analyze_covered_call</em>” from the part 3 script and this time we ask ChatGPT to adapt it but you could well do it manually:</p><p><em>Adapt this function, rename it to “filter_calls” and add a parameter “limitDays” that is used to exclude all calls whose expiration is above now+limitDays. Please also remove the filter based on delta, implied volatility, volume, open interest, and strike proximity. I do not need profit_if_exercised/profit_if_not_exercised and score either. The current market price can be removed too and remove TOP_CANDIDATES.<br>&lt;Code of the function pasted here … &gt;</em></p><p>We then paste this function in the script, this is the intermediate result.</p><pre>import os<br>import pandas as pd<br>import numpy as np<br>import yfinance as yf<br>import json<br>import matplotlib.pyplot as plt<br>from datetime import datetime, timedelta<br><br>API_URL_OPTIONS = &quot;https://finnhub.io/api/v1/stock/option-chain&quot;<br>API_URL_QUOTE = &quot;https://finnhub.io/api/v1/quote&quot;<br>API_KEY_FILE = &quot;apikey.txt&quot;<br>DATA_DIR = &quot;options_data&quot;<br><br><br>def fetch_historical_prices(ticker):<br>    &quot;&quot;&quot;Fetch historical prices from Yahoo Finance, caching if less than 1 day old.&quot;&quot;&quot;<br>    today = datetime.now().date()<br>    file_name = f&quot;{ticker}_historical_prices.csv&quot;<br><br>    # Check if the file exists and its age<br>    if os.path.exists(file_name):<br>        file_mod_time = datetime.fromtimestamp(os.path.getmtime(file_name)).date()<br>        if (today - file_mod_time) &lt; timedelta(days=1):<br>            print(f&quot;Using cached data from {file_name}&quot;)<br>            return pd.read_csv(file_name, index_col=0, parse_dates=True)<br><br>    # Fetch the data if file is older than 1 day or does not exist<br>    print(f&quot;Fetching new data for {ticker}...&quot;)<br>    data = yf.download(ticker, start=&#39;2020-01-01&#39;, end=today)<br>    <br>    # Save to a CSV file<br>    data.to_csv(file_name)<br>    return data<br>    <br># Function to read API key from file<br>def read_api_key():<br>    with open(API_KEY_FILE, &#39;r&#39;) as file:<br>        return file.read().strip()<br><br># Function to get options chain data<br>def get_options_chain(ticker):<br>    api_key = read_api_key()<br>    params = {<br>        &#39;symbol&#39;: ticker,<br>        &#39;token&#39;: api_key<br>    }<br>    response = requests.get(API_URL_OPTIONS, params=params)<br><br>    if response.status_code == 200:<br>        return response.json()<br>    else:<br>        print(f&quot;Error fetching options data: {response.status_code} - {response.text}&quot;)<br>        return None<br><br># Function to save data to a JSON file<br>def save_data(ticker, data):<br>    if not os.path.exists(DATA_DIR):<br>        os.makedirs(DATA_DIR)<br>    <br>    file_path = os.path.join(DATA_DIR, f&quot;{ticker}_options.json&quot;)<br>    with open(file_path, &#39;w&#39;) as json_file:<br>        json.dump(data, json_file)<br>    <br>    print(f&quot;Data saved to {file_path}&quot;)<br><br># Function to check if the file is outdated<br>def is_file_outdated(ticker):<br>    file_path = os.path.join(DATA_DIR, f&quot;{ticker}_options.json&quot;)<br>    if os.path.exists(file_path):<br>        file_mod_time = datetime.fromtimestamp(os.path.getmtime(file_path))<br>        if datetime.now() - file_mod_time &lt; timedelta(hours=4):<br>            return False  # File is not outdated<br>    return True  # File does not exist or is outdated    <br>    <br>def filter_calls(options_data, limitDays):<br>    if not options_data or &#39;data&#39; not in options_data:<br>        return []<br><br>    calls = []<br>    for option in options_data[&#39;data&#39;]:<br>        expiration_date = option[&#39;expirationDate&#39;]<br>        expiration = datetime.strptime(expiration_date, &quot;%Y-%m-%d&quot;)<br><br>        # Exclude options expiring beyond now + limitDays<br>        if expiration &lt;= datetime.now() + timedelta(days=limitDays):<br>            for call in option[&#39;options&#39;][&#39;CALL&#39;]:<br>                strike = call[&#39;strike&#39;]<br>                bid = call[&#39;bid&#39;]<br>                ask = call[&#39;ask&#39;]<br>                theta = call[&#39;theta&#39;]  # Assume theta is provided in the data<br>                gamma = call[&#39;gamma&#39;]  # Assume gamma is provided in the data<br>                contract_name = call[&#39;contractName&#39;]  # Get the contract name<br><br>                # Calculate median price<br>                median_price = (bid + ask) / 2<br><br>                # Append relevant information to calls<br>                calls.append({<br>                    &#39;contract_name&#39;: contract_name,  # Store the contract name<br>                    &#39;expiration&#39;: expiration,<br>                    &#39;strike&#39;: strike,<br>                    &#39;bid&#39;: bid,<br>                    &#39;ask&#39;: ask,<br>                    &#39;median_price&#39;: median_price,<br>                    &#39;theta&#39;: theta,  # Add theta<br>                    &#39;gamma&#39;: gamma   # Add gamma<br>                })<br>    <br>    # Sort calls by expiration date (optional, you can change the sorting as needed)<br>    sorted_calls = sorted(calls, key=lambda x: x[&#39;expiration&#39;])<br>    return sorted_calls<br><br>def black_scholes_simulation(start_price, mu, sigma, days=365):<br>    &quot;&quot;&quot;Simulate a single future price path using the Black-Scholes model.&quot;&quot;&quot;<br>    dt = 1 / 365  # Daily time increment<br>    prices = [start_price]<br>    <br>    for _ in range(days):<br>        price_t = prices[-1]<br>        # Simulate the next price with annualized parameters<br>        price_t1 = price_t * np.exp((mu - 0.5 * sigma ** 2) * dt + sigma * np.sqrt(dt) * np.random.normal())<br>        prices.append(price_t1)<br><br>    return prices<br><br>def main(ticker, simulations=500):<br>    # Fetch historical prices<br>    historical_data = fetch_historical_prices(ticker)<br>   <br>    # Fetch options chain<br>    options_data = None<br>   <br>    if is_file_outdated(ticker):<br>        print(f&quot;Fetching new data for {ticker}...&quot;)<br>        options_data = get_options_chain(ticker)<br>        if options_data:<br>            save_data(ticker, options_data)<br>    else:<br>        print(f&quot;Using cached data for {ticker}.&quot;)<br>        # Load cached data from the file<br>        file_path = os.path.join(DATA_DIR, f&quot;{ticker}_options.json&quot;)<br>        with open(file_path, &#39;r&#39;) as json_file:<br>            options_data = json.load(json_file)<br>         <br>    filtered_calls = filter_calls(options_data, 180)<br>         <br>    # Calculate daily returns<br>    historical_data[&#39;Return&#39;] = historical_data[&#39;Adj Close&#39;].pct_change()<br>    daily_mu = historical_data[&#39;Return&#39;].mean()<br>    daily_sigma = historical_data[&#39;Return&#39;].std()<br><br>    # Annualize the mean and standard deviation<br>    mu = daily_mu * 252  # Assuming 252 trading days in a year<br>    sigma = daily_sigma * np.sqrt(252)<br><br>    # Get the last price<br>    start_price = historical_data[&#39;Adj Close&#39;][-1]<br><br>    # Run multiple simulations and store paths<br>    all_simulated_prices = [black_scholes_simulation(start_price, mu, sigma) for _ in range(simulations)]<br>    all_simulated_prices = np.array(all_simulated_prices)<br><br>    # Calculate the mean path and standard deviations across simulations<br>    mean_path = all_simulated_prices.mean(axis=0)<br>    std_dev_path = all_simulated_prices.std(axis=0)<br>    upper_2std_bound = mean_path + 2 * std_dev_path<br>    lower_2std_bound = mean_path - 2 * std_dev_path<br>    upper_1std_bound = mean_path + std_dev_path<br>    lower_1std_bound = mean_path - std_dev_path<br><br>    # Plot each path with conditional coloring<br>    plt.figure(figsize=(12, 8))<br>    for prices in all_simulated_prices:<br>        final_price = prices[-1]<br>        mean_final_price = mean_path[-1]<br>        upper_1std_final_price = mean_path[-1] + std_dev_path[-1]<br>        lower_1std_final_price = mean_path[-1] - std_dev_path[-1]<br>        upper_2std_final_price = mean_path[-1] + 2 * std_dev_path[-1]<br>        lower_2std_final_price = mean_path[-1] - 2 * std_dev_path[-1]<br><br>        # Determine color based on final price<br>        if final_price &gt; upper_2std_final_price or final_price &lt; lower_2std_final_price:<br>            color = &#39;grey&#39;  # More than 2 std devs from the mean<br>        elif final_price &gt; upper_1std_final_price:<br>            color = &#39;lightgreen&#39;  # Between 1 and 2 std devs above the mean<br>        elif final_price &lt; lower_1std_final_price:<br>            color = &#39;lightcoral&#39;  # Between 1 and 2 std devs below the mean<br>        elif final_price &gt; mean_final_price:<br>            color = &#39;darkgreen&#39;  # Above mean but within 1 std dev<br>        else:<br>            color = &#39;darkred&#39;  # Below mean but within 1 std dev<br>        <br>        plt.plot(prices, color=color, alpha=0.6)<br><br>    # Plot the mean path in thick white<br>    plt.plot(mean_path, color=&#39;white&#39;, label=&#39;Mean Path&#39;, linewidth=2.5)<br><br>    # Plot the upper and lower bounds (± 2 std devs) in thick blue<br>    plt.plot(upper_2std_bound, color=&#39;blue&#39;, linestyle=&#39;--&#39;, label=&#39;Upper Bound (Mean + 2 Std Dev)&#39;, linewidth=2)<br>    plt.plot(lower_2std_bound, color=&#39;blue&#39;, linestyle=&#39;--&#39;, label=&#39;Lower Bound (Mean - 2 Std Dev)&#39;, linewidth=2)<br><br>    # Plot the upper and lower bounds (± 1 std dev) in thin cyan<br>    plt.plot(upper_1std_bound, color=&#39;cyan&#39;, linestyle=&#39;--&#39;, label=&#39;Upper Bound (Mean + 1 Std Dev)&#39;, linewidth=1)<br>    plt.plot(lower_1std_bound, color=&#39;cyan&#39;, linestyle=&#39;--&#39;, label=&#39;Lower Bound (Mean - 1 Std Dev)&#39;, linewidth=1)<br><br>    # Plotting settings<br>    plt.title(f&#39;{simulations} Simulated Price Paths for {ticker} over Next 365 Days&#39;)<br>    plt.xlabel(&#39;Days&#39;)<br>    plt.ylabel(&#39;Price&#39;)<br>    plt.legend()<br>    plt.grid()<br>    plt.show()<br><br>if __name__ == &quot;__main__&quot;:<br>    ticker = input(&quot;Enter the stock ticker symbol: &quot;)<br>    main(ticker)</pre><h4><strong>Evaluating Options Chain</strong></h4><p>With our simulated paths ready, we can now evaluate each one against various contracts in the options chain. Rather than selecting strikes or expirations at random, we’ll follow Diaz’s thesis guidelines for structured decision-making.</p><p>We’ve already filtered out calls with expirations beyond six months. Next, we apply the following low-risk criteria:</p><ul><li>Select the first set of calls expiring more than 25 days from today.</li><li>Choose the nearest strike just above the spot price (slightly above ATM).</li><li>Reduce the number of simulated prices to two, which will simplify script verification.</li></ul><p>Finally, we set a constant seed for the randomization process to ensure reproducibility.</p><p><em>Adapt the script: <br>1. at the beginning, enforce a default constant seed for random operations <br>2. From the list of filtered calls, find the first expiration that comes in at least 25 days, and only keep all the calls for that day. <br>3. Pick the first strike that is just above the spot price (ie. just above ATM) 4. Decrease the number of simulated prices to only 2, this will be helpful to verify the script <br>5. Show information about the call that you picked: contract name, expiration, strike, bid, ask<br>Keep the rest of the logic, plotting, etc. intact</em></p><p>The corresponding script launched on DIS ticker proposes me the contract with strike $97, expiring in 31 days. It also plots two paths (not shown here).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*kq3gA7JAiI2g9VR674Aw8Q.png" /></figure><p>Now we ask ChatGPT to simulate the covered call strategy on the available simulated paths, using this call. The idea is the following:</p><ul><li>Evaluate that call in the context of the covered call where I buy 100 shares at the spot price and I sell the candidate call.</li><li>If the call is exercised, I get the premium + the difference between the strike and my initial price</li><li>Otherwise, I just get the premium. I assume for the moment I keep the stock.</li></ul><p>We will get a result for each simulated path, either our call is exercised or not and the profit will vary depending on this.</p><p><em>Please update the script to do the following:<br>* Simulate a covered call strategy by buying 100 shares at the current spot price and simultaneously selling the selected call. The sale price of the call will be calculated as (ask + bid) * 0.5 * 100, referred to here as the “premium.”<br>* Run this simulation across the different sets of simulated random prices.<br>* For each set of simulated prices, identify the price on the day the contract expires.<br>* Calculate the profit for the covered call strategy:<br>If the call is exercised: profit = premium + (strike price * 100) — (initial purchase price of 100 shares).<br>If the call is not exercised, profit is simply the premium, and I retain the shares.<br>Please display a summary table with the following columns: Expiration Date, Spot Price, Stock Price at Expiration, Premium, Profit. Keep the plotting as it is, as I need to verify the prices visually.</em></p><p>The <strong>generated script has a flaw,</strong> we quickly notice by looking at the plots that it executed the profit computation against the last values in the simulated prices (ie. 365 days) instead of using the prices at the time of the expiration. We ask the AI to fix this…</p><p><em>The script is wrong, you must not use the prices after 365 days, this does not correspond to the expiration of my contract. Fix it.</em></p><pre>import os<br>import pandas as pd<br>import numpy as np<br>import yfinance as yf<br>import json<br>import matplotlib.pyplot as plt<br>import requests<br>from datetime import datetime, timedelta<br><br>API_URL_OPTIONS = &quot;https://finnhub.io/api/v1/stock/option-chain&quot;<br>API_KEY_FILE = &quot;apikey.txt&quot;<br>DATA_DIR = &quot;options_data&quot;<br><br># Set a constant random seed for reproducibility<br>np.random.seed(42)<br><br>def fetch_historical_prices(ticker):<br>    &quot;&quot;&quot;Fetch historical prices from Yahoo Finance, caching if less than 1 day old.&quot;&quot;&quot;<br>    today = datetime.now().date()<br>    file_name = f&quot;{ticker}_historical_prices.csv&quot;<br><br>    # Check if the file exists and its age<br>    if os.path.exists(file_name):<br>        file_mod_time = datetime.fromtimestamp(os.path.getmtime(file_name)).date()<br>        if (today - file_mod_time) &lt; timedelta(days=1):<br>            print(f&quot;Using cached data from {file_name}&quot;)<br>            return pd.read_csv(file_name, index_col=0, parse_dates=True)<br><br>    # Fetch the data if file is older than 1 day or does not exist<br>    print(f&quot;Fetching new data for {ticker}...&quot;)<br>    data = yf.download(ticker, start=&#39;2020-01-01&#39;, end=today)<br>    <br>    # Save to a CSV file<br>    data.to_csv(file_name)<br>    return data<br>    <br># Function to read API key from file<br>def read_api_key():<br>    with open(API_KEY_FILE, &#39;r&#39;) as file:<br>        return file.read().strip()<br><br># Function to get options chain data<br>def get_options_chain(ticker):<br>    api_key = read_api_key()<br>    params = {<br>        &#39;symbol&#39;: ticker,<br>        &#39;token&#39;: api_key<br>    }<br>    response = requests.get(API_URL_OPTIONS, params=params)<br><br>    if response.status_code == 200:<br>        return response.json()<br>    else:<br>        print(f&quot;Error fetching options data: {response.status_code} - {response.text}&quot;)<br>        return None<br><br># Function to save data to a JSON file<br>def save_data(ticker, data):<br>    if not os.path.exists(DATA_DIR):<br>        os.makedirs(DATA_DIR)<br>    <br>    file_path = os.path.join(DATA_DIR, f&quot;{ticker}_options.json&quot;)<br>    with open(file_path, &#39;w&#39;) as json_file:<br>        json.dump(data, json_file)<br>    <br>    print(f&quot;Data saved to {file_path}&quot;)<br><br># Function to check if the file is outdated<br>def is_file_outdated(ticker):<br>    file_path = os.path.join(DATA_DIR, f&quot;{ticker}_options.json&quot;)<br>    if os.path.exists(file_path):<br>        file_mod_time = datetime.fromtimestamp(os.path.getmtime(file_path))<br>        if datetime.now() - file_mod_time &lt; timedelta(hours=4):<br>            return False  # File is not outdated<br>    return True  # File does not exist or is outdated    <br>    <br>def filter_calls(options_data, limitDays):<br>    if not options_data or &#39;data&#39; not in options_data:<br>        return []<br><br>    calls = []<br>    for option in options_data[&#39;data&#39;]:<br>        expiration_date = option[&#39;expirationDate&#39;]<br>        expiration = datetime.strptime(expiration_date, &quot;%Y-%m-%d&quot;)<br><br>        # Exclude options expiring beyond now + limitDays<br>        if expiration &gt; datetime.now() + timedelta(days=25):  # Check for at least 25 days to expiration<br>            for call in option[&#39;options&#39;][&#39;CALL&#39;]:<br>                strike = call[&#39;strike&#39;]<br>                bid = call[&#39;bid&#39;]<br>                ask = call[&#39;ask&#39;]<br>                theta = call[&#39;theta&#39;]  # Assume theta is provided in the data<br>                gamma = call[&#39;gamma&#39;]  # Assume gamma is provided in the data<br>                contract_name = call[&#39;contractName&#39;]  # Get the contract name<br><br>                # Calculate median price<br>                median_price = (bid + ask) / 2<br><br>                # Append relevant information to calls<br>                calls.append({<br>                    &#39;contract_name&#39;: contract_name,  # Store the contract name<br>                    &#39;expiration&#39;: expiration,<br>                    &#39;strike&#39;: strike,<br>                    &#39;bid&#39;: bid,<br>                    &#39;ask&#39;: ask,<br>                    &#39;median_price&#39;: median_price,<br>                    &#39;theta&#39;: theta,  # Add theta<br>                    &#39;gamma&#39;: gamma   # Add gamma<br>                })<br>    <br>    # Sort calls by expiration date and filter to keep only those expiring soonest<br>    sorted_calls = sorted(calls, key=lambda x: x[&#39;expiration&#39;])<br>    if sorted_calls:<br>        # Keep only calls for the first expiration that meets the 25 days criteria<br>        target_expiration = sorted_calls[0][&#39;expiration&#39;]<br>        filtered_calls = [call for call in sorted_calls if call[&#39;expiration&#39;] == target_expiration]<br>        <br>        return filtered_calls<br><br>    return []<br><br>def select_strike(calls, spot_price):<br>    # Select the first strike that is just above the spot price (ATM)<br>    for call in calls:<br>        if call[&#39;strike&#39;] &gt; spot_price:<br>            return call<br>    return None<br><br>def black_scholes_simulation(start_price, mu, sigma, days=365):<br>    &quot;&quot;&quot;Simulate a single future price path using the Black-Scholes model.&quot;&quot;&quot;<br>    dt = 1 / 365  # Daily time increment<br>    prices = [start_price]<br>    <br>    for _ in range(days):<br>        price_t = prices[-1]<br>        # Simulate the next price with annualized parameters<br>        price_t1 = price_t * np.exp((mu - 0.5 * sigma ** 2) * dt + sigma * np.sqrt(dt) * np.random.normal())<br>        prices.append(price_t1)<br><br>    return prices<br><br>def main(ticker, simulations=100):  # Reduced simulations to only 2 for verification<br>    # Fetch historical prices<br>    historical_data = fetch_historical_prices(ticker)<br>   <br>    # Fetch options chain<br>    options_data = None<br>   <br>    if is_file_outdated(ticker):<br>        print(f&quot;Fetching new data for {ticker}...&quot;)<br>        options_data = get_options_chain(ticker)<br>        if options_data:<br>            save_data(ticker, options_data)<br>    else:<br>        print(f&quot;Using cached data for {ticker}.&quot;)<br>        # Load cached data from the file<br>        file_path = os.path.join(DATA_DIR, f&quot;{ticker}_options.json&quot;)<br>        with open(file_path, &#39;r&#39;) as json_file:<br>            options_data = json.load(json_file)<br>         <br>    filtered_calls = filter_calls(options_data, 180)<br>    <br>    if not filtered_calls:<br>        print(&quot;No calls found that meet the criteria.&quot;)<br>        return<br><br>    # Get the last price<br>    start_price = historical_data[&#39;Adj Close&#39;][-1]<br>    <br>    # Select the first strike above the spot price<br>    selected_call = select_strike(filtered_calls, start_price)<br><br>    if selected_call:<br>        print(f&quot;Selected Call Option:&quot;)<br>        print(f&quot;Contract Name: {selected_call[&#39;contract_name&#39;]}&quot;)<br>        print(f&quot;Expiration: {selected_call[&#39;expiration&#39;].date()}&quot;)<br>        print(f&quot;Strike: {selected_call[&#39;strike&#39;]}&quot;)<br>        print(f&quot;Bid: {selected_call[&#39;bid&#39;]}&quot;)<br>        print(f&quot;Ask: {selected_call[&#39;ask&#39;]}&quot;)<br><br>        # Calculate daily returns<br>        historical_data[&#39;Return&#39;] = historical_data[&#39;Adj Close&#39;].pct_change()<br>        daily_mu = historical_data[&#39;Return&#39;].mean()<br>        daily_sigma = historical_data[&#39;Return&#39;].std()<br><br>        # Annualize the mean and standard deviation<br>        mu = daily_mu * 252  # Assuming 252 trading days in a year<br>        sigma = daily_sigma * np.sqrt(252)<br><br>        # Calculate premium for covered call strategy<br>        premium = (selected_call[&#39;bid&#39;] + selected_call[&#39;ask&#39;]) * 0.5 * 100<br>        print(f&quot;Premium Received from Selling Call: ${premium:.2f}&quot;)<br><br>        # Calculate the index for the expiration day in the simulated price paths<br>        expiration_date = selected_call[&#39;expiration&#39;]<br>        days_to_expiration = (expiration_date - datetime.now()).days<br>        # Ensure days_to_expiration does not exceed the simulation length<br>        if days_to_expiration &gt;= 365:<br>            days_to_expiration = 364  # Last index in a 365-day simulation<br>        <br>        # Run multiple simulations and store paths<br>        all_simulated_prices = [black_scholes_simulation(start_price, mu, sigma) for _ in range(simulations)]<br>        all_simulated_prices = np.array(all_simulated_prices)<br><br>        # Store results for the summary table<br>        results = []<br><br>        strike_price = selected_call[&#39;strike&#39;]<br>        <br>        # Calculate profits based on simulation paths<br>        expiration_index = 365  # We are only interested in the final price for profit calculation<br>        for path_num, prices in enumerate(all_simulated_prices):<br>            stock_price_at_expiration = prices[days_to_expiration]  # Price at expiration<br>            <br>            # Calculate profit<br>            if stock_price_at_expiration &gt; strike_price:<br>                profit = premium + (strike_price * 100) - (start_price * 100)<br>            else:<br>                profit = premium  # If not exercised, only keep the premium<br>        <br>            results.append({<br>                &quot;Expiration Date&quot;: expiration_date.date(),<br>                &quot;Spot Price&quot;: start_price,<br>                &quot;Stock Price at Expiration&quot;: stock_price_at_expiration,<br>                &quot;Premium&quot;: premium,<br>                &quot;Profit&quot;: profit<br>            })<br><br><br>        # Create a DataFrame for better visualization<br>        results_df = pd.DataFrame(results)<br>        print(&quot;\nSummary of Covered Call Strategy Results:&quot;)<br>        print(results_df)<br><br>        # Plot each path with conditional coloring<br>        plt.figure(figsize=(12, 8))<br>        for prices in all_simulated_prices:<br>            final_price = prices[-1]<br>            mean_final_price = np.mean(all_simulated_prices[:, -1])<br><br>            # Define colors based on conditions<br>            if final_price &lt; mean_final_price - 2 * np.std(all_simulated_prices[:, -1]):<br>                color = &#39;red&#39;  # Below mean - 2 std dev<br>            elif final_price &lt; mean_final_price - np.std(all_simulated_prices[:, -1]):<br>                color = &#39;orange&#39;  # Between -1 and -2 std devs<br>            elif final_price &gt; mean_final_price + 2 * np.std(all_simulated_prices[:, -1]):<br>                color = &#39;green&#39;  # Above mean + 2 std dev<br>            elif final_price &gt; mean_final_price + np.std(all_simulated_prices[:, -1]):<br>                color = &#39;darkgreen&#39;  # Between +1 and +2 std devs<br>            elif final_price &lt; mean_final_price + np.std(all_simulated_prices[:, -1]):<br>                color = &#39;darkred&#39;  # Below mean + 1 std dev<br>            else:<br>                color = &#39;darkgray&#39;  # Above mean but within 1 std dev<br>            <br>            plt.plot(prices, color=color, alpha=0.6)<br><br>        # Plot the mean path in thick white<br>        mean_path = np.mean(all_simulated_prices, axis=0)<br>        plt.plot(mean_path, color=&#39;white&#39;, label=&#39;Mean Path&#39;, linewidth=2.5)<br><br>        # Plot the upper and lower bounds (± 2 std devs) in thick blue<br>        upper_2std_bound = np.mean(all_simulated_prices, axis=0) + 2 * np.std(all_simulated_prices, axis=0)<br>        lower_2std_bound = np.mean(all_simulated_prices, axis=0) - 2 * np.std(all_simulated_prices, axis=0)<br>        plt.plot(upper_2std_bound, color=&#39;blue&#39;, linestyle=&#39;--&#39;, label=&#39;Upper Bound (Mean + 2 Std Dev)&#39;, linewidth=2)<br>        plt.plot(lower_2std_bound, color=&#39;blue&#39;, linestyle=&#39;--&#39;, label=&#39;Lower Bound (Mean - 2 Std Dev)&#39;, linewidth=2)<br><br>        # Plot the upper and lower bounds (± 1 std dev) in thin cyan<br>        upper_1std_bound = np.mean(all_simulated_prices, axis=0) + np.std(all_simulated_prices, axis=0)<br>        lower_1std_bound = np.mean(all_simulated_prices, axis=0) - np.std(all_simulated_prices, axis=0)<br>        plt.plot(upper_1std_bound, color=&#39;cyan&#39;, linestyle=&#39;--&#39;, label=&#39;Upper Bound (Mean + 1 Std Dev)&#39;, linewidth=1)<br>        plt.plot(lower_1std_bound, color=&#39;cyan&#39;, linestyle=&#39;--&#39;, label=&#39;Lower Bound (Mean - 1 Std Dev)&#39;, linewidth=1)<br><br>        # Plotting settings<br>        plt.title(f&#39;{simulations} Simulated Price Paths for {ticker} over Next 365 Days&#39;)<br>        plt.xlabel(&#39;Days&#39;)<br>        plt.ylabel(&#39;Price&#39;)<br>        plt.legend()<br>        plt.grid()<br>        plt.show()<br>    else:<br>        print(&quot;No suitable strike price found above the current spot price.&quot;)<br><br>if __name__ == &quot;__main__&quot;:<br>    ticker = input(&quot;Enter the stock ticker symbol: &quot;)<br>    main(ticker)</pre><p>This looks better, but let’s verify. My expiration is set for 31 days, which corresponds to approximately $86 on the first path and $104 on the second path.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/1*18LMhgvKVymbSpC5jIN-OQ.png" /></figure><p>And this is the output of the script, which reflects a correct price extraction:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*0xMOmmT0UTeWK1uQH2VmcA.png" /></figure><p>Regarding the profit, the premium is correct and the profit when the shares were above the strike is correct too (97–96.2)*100+412.5 = 492.5</p><h4>More Statistics</h4><p>We ask for some improvements, the table is not very nice, there are too many digits and we’d like to get a better simulation by increasing to 250 paths and getting a statistical idea of all of this. I prefer to start with a fresh prompt with a clear instruction to not mess with the existing code.</p><p><em>Adapt this script (you must keep all the existing logic, plot etc) but I want the table to be nicer with borders in the console, use tabulate for example. I also want you to limit the number of digits after decimal point to 2. You must also increase the simulation to 200 paths. And finally, make a second table that contains a statistical summary of the result: mean stock price at expiration, mean profit, probability in % that the call gets exercised.</em></p><p>I then manually inserted some code to augment the generated statistical table and includeed additional figures such as:</p><ul><li><strong>Return in %</strong>: this metric calculates the mean profit as a percentage of the initial investment (i.e., the price of the 100 shares initially purchased). It only includes the premium collected from selling the call or the combined premium and share gains if the call is exercised. It does not account for any potential unrealized losses on the shares if the call expires unexercised.</li><li><strong>Annualized return in %</strong>: this is an extrapolated annual return based on the percentage return and the option’s duration, assuming you could repeat this strategy over the entire year. Note that this assumes the same outcomes each time, which may not reflect real-world market variations, so it should be interpreted cautiously.</li><li><strong>P/L on shares</strong>. This figure calculates the difference between the initial price of your shares and their mean (simulated) price at expiration, representing the profit or loss on the shares themselves when the call expires.</li><li><strong>P/L on shares with favorable/defavorable price.</strong> This extends the mean P/L calculation by considering potential outcomes if prices vary by one standard deviation. It shows possible gains or losses in cases where prices move favorably (upward) or unfavorably (downward). Each of these outcomes has an approximate 34% probability, reflecting typical market fluctuations around the mean price.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/1*cBEODP8pyVucpHh15W-b9w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*OtMZk2JC8RiSNs8X5HJ-Yw.png" /></figure><p>This last example was run on 31th October 2024. For Disney, with a near-ATM call expiring in 28 days at a $96 strike price, a spot price of $95.08, and a premium of $4.075 per share, the mean profit from this covered call strategy is estimated at $442.92. Additionally, there is roughly a 38% chance that the call will be exercised.</p><p>Regarding the stock price projection independently of the call, simulations indicate a slightly bearish outlook for Disney by expiration, with a modest average decline expected. In a favorable bullish scenario, the stock could rise by approximately $8.60, while an unfavorable bearish scenario could lead to a potential loss of around $9.00 per share.</p><p>This is the final version of our script:</p><pre>import os<br>import pandas as pd<br>import numpy as np<br>import yfinance as yf<br>import json<br>import matplotlib.pyplot as plt<br>import requests<br>from datetime import datetime, timedelta<br>from tabulate import tabulate  # Importing tabulate for nicer table formatting<br><br>API_URL_OPTIONS = &quot;https://finnhub.io/api/v1/stock/option-chain&quot;<br>API_KEY_FILE = &quot;apikey.txt&quot;<br>DATA_DIR = &quot;options_data&quot;<br><br># Set a constant random seed for reproducibility<br>np.random.seed(42)<br><br>def fetch_historical_prices(ticker):<br>    &quot;&quot;&quot;Fetch historical prices from Yahoo Finance, caching if less than 1 day old.&quot;&quot;&quot;<br>    today = datetime.now().date()<br>    file_name = f&quot;{ticker}_historical_prices.csv&quot;<br><br>    # Check if the file exists and its age<br>    if os.path.exists(file_name):<br>        file_mod_time = datetime.fromtimestamp(os.path.getmtime(file_name)).date()<br>        if (today - file_mod_time) &lt; timedelta(days=1):<br>            print(f&quot;Using cached data from {file_name}&quot;)<br>            return pd.read_csv(file_name, index_col=0, parse_dates=True)<br><br>    # Fetch the data if file is older than 1 day or does not exist<br>    print(f&quot;Fetching new data for {ticker}...&quot;)<br>    data = yf.download(ticker, start=&#39;2020-01-01&#39;, end=today)<br>    <br>    # Save to a CSV file<br>    data.to_csv(file_name)<br>    return data<br><br># Function to read API key from file<br>def read_api_key():<br>    with open(API_KEY_FILE, &#39;r&#39;) as file:<br>        return file.read().strip()<br><br># Function to get options chain data<br>def get_options_chain(ticker):<br>    api_key = read_api_key()<br>    params = {<br>        &#39;symbol&#39;: ticker,<br>        &#39;token&#39;: api_key<br>    }<br>    response = requests.get(API_URL_OPTIONS, params=params)<br><br>    if response.status_code == 200:<br>        return response.json()<br>    else:<br>        print(f&quot;Error fetching options data: {response.status_code} - {response.text}&quot;)<br>        return None<br><br># Function to save data to a JSON file<br>def save_data(ticker, data):<br>    if not os.path.exists(DATA_DIR):<br>        os.makedirs(DATA_DIR)<br>    <br>    file_path = os.path.join(DATA_DIR, f&quot;{ticker}_options.json&quot;)<br>    with open(file_path, &#39;w&#39;) as json_file:<br>        json.dump(data, json_file)<br>    <br>    print(f&quot;Data saved to {file_path}&quot;)<br><br># Function to check if the file is outdated<br>def is_file_outdated(ticker):<br>    file_path = os.path.join(DATA_DIR, f&quot;{ticker}_options.json&quot;)<br>    if os.path.exists(file_path):<br>        file_mod_time = datetime.fromtimestamp(os.path.getmtime(file_path))<br>        if datetime.now() - file_mod_time &lt; timedelta(hours=4):<br>            return False  # File is not outdated<br>    return True  # File does not exist or is outdated    <br><br>def filter_calls(options_data, limitDays):<br>    if not options_data or &#39;data&#39; not in options_data:<br>        return []<br><br>    calls = []<br>    for option in options_data[&#39;data&#39;]:<br>        expiration_date = option[&#39;expirationDate&#39;]<br>        expiration = datetime.strptime(expiration_date, &quot;%Y-%m-%d&quot;)<br><br>        if expiration &gt; datetime.now() + timedelta(days=25):  # Check for at least XX days to expiration<br>            for call in option[&#39;options&#39;][&#39;CALL&#39;]:<br>                strike = call[&#39;strike&#39;]<br>                bid = call[&#39;bid&#39;]<br>                ask = call[&#39;ask&#39;]<br>                theta = call[&#39;theta&#39;]  # Assume theta is provided in the data<br>                gamma = call[&#39;gamma&#39;]  # Assume gamma is provided in the data<br>                contract_name = call[&#39;contractName&#39;]  # Get the contract name<br><br>                # Calculate median price<br>                median_price = (bid + ask) / 2<br><br>                # Append relevant information to calls<br>                calls.append({<br>                    &#39;contract_name&#39;: contract_name,  # Store the contract name<br>                    &#39;expiration&#39;: expiration,<br>                    &#39;strike&#39;: strike,<br>                    &#39;bid&#39;: bid,<br>                    &#39;ask&#39;: ask,<br>                    &#39;median_price&#39;: median_price,<br>                    &#39;theta&#39;: theta,  # Add theta<br>                    &#39;gamma&#39;: gamma   # Add gamma<br>                })<br>    <br>    # Sort calls by expiration date and filter to keep only those expiring soonest<br>    sorted_calls = sorted(calls, key=lambda x: x[&#39;expiration&#39;])<br>    if sorted_calls:<br>        # Keep only calls for the first expiration that meets the XX days criteria<br>        target_expiration = sorted_calls[0][&#39;expiration&#39;]<br>        filtered_calls = [call for call in sorted_calls if call[&#39;expiration&#39;] == target_expiration]<br>        <br>        return filtered_calls<br><br>    return []<br><br>def select_strike(calls, spot_price):<br>    # change the multiplier of the spot_price if you want a call deeper OTM (ex. 1.0 for low risk, 1.2 for med risk or higher for greater risk)<br>    for call in calls:<br>        if call[&#39;strike&#39;] &gt; spot_price*1.0:     <br>            return call<br>    return None<br><br>def black_scholes_simulation(start_price, mu, sigma, days=365):<br>    &quot;&quot;&quot;Simulate a single future price path using the Black-Scholes model.&quot;&quot;&quot;<br>    dt = 1 / 365  # Daily time increment<br>    prices = [start_price]<br>    <br>    for _ in range(days):<br>        price_t = prices[-1]<br>        # Simulate the next price with annualized parameters<br>        price_t1 = price_t * np.exp((mu - 0.5 * sigma ** 2) * dt + sigma * np.sqrt(dt) * np.random.normal())<br>        prices.append(price_t1)<br><br>    return prices<br><br>def main(ticker, simulations=200):  # Increased simulations to 200<br>    # Fetch historical prices<br>    historical_data = fetch_historical_prices(ticker)<br>   <br>    # Fetch options chain<br>    options_data = None<br>   <br>    if is_file_outdated(ticker):<br>        print(f&quot;Fetching new data for {ticker}...&quot;)<br>        options_data = get_options_chain(ticker)<br>        if options_data:<br>            save_data(ticker, options_data)<br>    else:<br>        print(f&quot;Using cached data for {ticker}.&quot;)<br>        # Load cached data from the file<br>        file_path = os.path.join(DATA_DIR, f&quot;{ticker}_options.json&quot;)<br>        with open(file_path, &#39;r&#39;) as json_file:<br>            options_data = json.load(json_file)<br>         <br>    filtered_calls = filter_calls(options_data, 180)<br>    <br>    if not filtered_calls:<br>        print(&quot;No calls found that meet the criteria.&quot;)<br>        return<br><br>    # Get the last price<br>    start_price = historical_data[&#39;Adj Close&#39;].iloc[-1]<br>    <br>    # Select the first strike above the spot price<br>    selected_call = select_strike(filtered_calls, start_price)<br><br>    if selected_call:<br>        print(f&quot;Selected Call Option:&quot;)<br>        print(f&quot;Contract Name: {selected_call[&#39;contract_name&#39;]}&quot;)<br>        print(f&quot;Expiration: {selected_call[&#39;expiration&#39;].date()}&quot;)<br>        print(f&quot;Strike: {selected_call[&#39;strike&#39;]:.2f}&quot;)<br>        print(f&quot;Bid: {selected_call[&#39;bid&#39;]:.2f}&quot;)<br>        print(f&quot;Ask: {selected_call[&#39;ask&#39;]:.2f}&quot;)<br><br>        # Calculate daily returns<br>        historical_data[&#39;Return&#39;] = historical_data[&#39;Adj Close&#39;].pct_change()<br>        daily_mu = historical_data[&#39;Return&#39;].mean()<br>        daily_sigma = historical_data[&#39;Return&#39;].std()<br><br>        # Annualize the mean and standard deviation<br>        mu = daily_mu * 252  # Assuming 252 trading days in a year<br>        sigma = daily_sigma * np.sqrt(252)<br><br>        # Calculate premium for covered call strategy<br>        premium = (selected_call[&#39;bid&#39;] + selected_call[&#39;ask&#39;]) * 0.5 * 100<br>        print(f&quot;Premium Received from Selling Call: ${premium:.2f}&quot;)<br><br>        # Calculate the index for the expiration day in the simulated price paths<br>        expiration_date = selected_call[&#39;expiration&#39;]<br>        days_to_expiration = (expiration_date - datetime.now()).days<br>        # Ensure days_to_expiration does not exceed the simulation length<br>        if days_to_expiration &gt;= 365:<br>            days_to_expiration = 364  # Last index in a 365-day simulation<br>        <br>        # Run multiple simulations and store paths<br>        all_simulated_prices = [black_scholes_simulation(start_price, mu, sigma) for _ in range(simulations)]<br>        all_simulated_prices = np.array(all_simulated_prices)<br><br>        # Store results for the summary table<br>        results = []<br><br>        strike_price = selected_call[&#39;strike&#39;]<br>        <br>        # Calculate profits based on simulation paths<br>        expiration_index = 365  # We are only interested in the final price for profit calculation<br>        for path_num, prices in enumerate(all_simulated_prices):<br>            stock_price_at_expiration = prices[days_to_expiration]  # Price at expiration<br>            <br>            # Calculate profit<br>            if stock_price_at_expiration &gt; strike_price:<br>                profit = premium + (strike_price * 100) - (start_price * 100)<br>            else:<br>                profit = premium  # If not exercised, only keep the premium<br>        <br>            results.append({<br>                &quot;Expiration Date&quot;: expiration_date.date(),<br>                &quot;Spot Price&quot;: round(start_price, 2),<br>                &quot;Stock Price at Expiration&quot;: round(stock_price_at_expiration, 2),<br>                &quot;Premium&quot;: round(premium, 2),<br>                &quot;Profit&quot;: round(profit, 2)<br>            })<br><br>        # Create a DataFrame for better visualization<br>        results_df = pd.DataFrame(results)<br>        <br>        # Print detailed results using tabulate<br>        print(&quot;\nSummary of Covered Call Strategy Results:&quot;)<br>        print(tabulate(results_df, headers=&#39;keys&#39;, tablefmt=&#39;fancy_grid&#39;, floatfmt=&quot;.2f&quot;))<br><br>        # Statistical summary<br>        mean_stock_price = np.mean(results_df[&quot;Stock Price at Expiration&quot;])<br>        <br>        favorable_stock_price = mean_stock_price + np.std(results_df[&quot;Stock Price at Expiration&quot;])<br>        defavorable_stock_price = mean_stock_price - np.std(results_df[&quot;Stock Price at Expiration&quot;])<br>        <br>        mean_profit = np.mean(results_df[&quot;Profit&quot;])<br>        call_exercised_probability = np.mean(results_df[&quot;Stock Price at Expiration&quot;] &gt; strike_price) * 100<br><br>        # Create a summary DataFrame<br>        summary_df = pd.DataFrame({<br>            &quot;Statistic&quot;: [&quot;Strike&quot;, <br>            &quot;Mean Stock Price at Expiration&quot;, <br>                          &quot;Mean Profit (any call scenario, exerc. or not)&quot;,<br>                          &quot;Probability of Exercised Call (%)&quot;,<br>                          &quot;Return % (mean profit vs initial 100 shares)&quot;, &quot;Annualized Mean Return %&quot;,<br>                          &quot;P/L on shares (100 shares at mean sim price)&quot;,<br>                          &quot;P/L on shares (100 shares at favorable sim price, 1 std dev)&quot;,<br>                          &quot;P/L on shares (100 shares defavorable sim price, -1 std dev)&quot;,<br>                          &quot;Days to expiration&quot;<br>                          ],<br>            &quot;Value&quot;: [selected_call[&#39;strike&#39;], round(mean_stock_price, 2), round(mean_profit, 2), round(call_exercised_probability, 2), <br>                      100*mean_profit/(start_price*100), <br>                      365*(100*mean_profit/(start_price*100))/days_to_expiration,<br>                      (mean_stock_price*100)-(start_price*100),  (favorable_stock_price*100)-(start_price*100),  <br>                      (defavorable_stock_price*100)-(start_price*100), days_to_expiration]<br>        })<br><br>        # Print statistical summary using tabulate<br>        print(&quot;\nStatistical Summary:&quot;)<br>        print(tabulate(summary_df, headers=&#39;keys&#39;, tablefmt=&#39;fancy_grid&#39;, floatfmt=&quot;.2f&quot;))<br><br>        # Plot each path with conditional coloring<br>        plt.figure(figsize=(12, 8))<br>        for prices in all_simulated_prices:<br>            final_price = prices[-1]<br>            mean_final_price = np.mean(all_simulated_prices[:, -1])<br><br>            # Define colors based on conditions<br>            if final_price &lt; mean_final_price - 2 * np.std(all_simulated_prices[:, -1]):<br>                color = &#39;red&#39;  # Below mean - 2 std dev<br>            elif final_price &lt; mean_final_price - np.std(all_simulated_prices[:, -1]):<br>                color = &#39;orange&#39;  # Between -1 and -2 std devs<br>            elif final_price &gt; mean_final_price + 2 * np.std(all_simulated_prices[:, -1]):<br>                color = &#39;green&#39;  # Above mean + 2 std dev<br>            elif final_price &gt; mean_final_price + np.std(all_simulated_prices[:, -1]):<br>                color = &#39;darkgreen&#39;  # Between +1 and +2 std devs<br>            elif final_price &lt; mean_final_price + np.std(all_simulated_prices[:, -1]):<br>                color = &#39;darkred&#39;  # Below mean + 1 std dev<br>            else:<br>                color = &#39;darkgray&#39;  # Above mean but within 1 std dev<br>            <br>            plt.plot(prices, color=color, alpha=0.6)<br><br>        # Plot the mean path in thick white<br>        mean_path = np.mean(all_simulated_prices, axis=0)<br>        plt.plot(mean_path, color=&#39;white&#39;, label=&#39;Mean Path&#39;, linewidth=2.5)<br><br>        # Plot the upper and lower bounds (± 2 std devs) in thick blue<br>        upper_2std_bound = np.mean(all_simulated_prices, axis=0) + 2 * np.std(all_simulated_prices, axis=0)<br>        lower_2std_bound = np.mean(all_simulated_prices, axis=0) - 2 * np.std(all_simulated_prices, axis=0)<br>        plt.plot(upper_2std_bound, color=&#39;blue&#39;, linestyle=&#39;--&#39;, label=&#39;Upper Bound (Mean + 2 Std Dev)&#39;, linewidth=2)<br>        plt.plot(lower_2std_bound, color=&#39;blue&#39;, linestyle=&#39;--&#39;, label=&#39;Lower Bound (Mean - 2 Std Dev)&#39;, linewidth=2)<br><br>        # Plot the upper and lower bounds (± 1 std dev) in thin cyan<br>        upper_1std_bound = np.mean(all_simulated_prices, axis=0) + np.std(all_simulated_prices, axis=0)<br>        lower_1std_bound = np.mean(all_simulated_prices, axis=0) - np.std(all_simulated_prices, axis=0)<br>        plt.plot(upper_1std_bound, color=&#39;cyan&#39;, linestyle=&#39;--&#39;, label=&#39;Upper Bound (Mean + 1 Std Dev)&#39;, linewidth=1)<br>        plt.plot(lower_1std_bound, color=&#39;cyan&#39;, linestyle=&#39;--&#39;, label=&#39;Lower Bound (Mean - 1 Std Dev)&#39;, linewidth=1)<br><br>        # Plotting settings<br>        plt.title(f&#39;{simulations} Simulated Price Paths for {ticker} over Next 365 Days&#39;)<br>        plt.xlabel(&#39;Days&#39;)<br>        plt.ylabel(&#39;Price&#39;)<br>        plt.legend()<br>        plt.grid()<br>        plt.show()<br>    else:<br>        print(&quot;No suitable strike price found above the current spot price.&quot;)<br><br>if __name__ == &quot;__main__&quot;:<br>    ticker = input(&quot;Enter the stock ticker symbol: &quot;)<br>    main(ticker)</pre><h4><strong>Playing with the Risk</strong></h4><p>To increase the risk by selecting a call option further away from the current spot price, we can modify the <em>filter_calls </em>and <em>select_strike</em> functions. This adjustment involves changing the filtering criteria to allow for contracts that expire in 60 days for example and selecting an OTM call that is approximately 1.2% above the spot price</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*JLeZcfJFKyPS2ZrM2aTnwQ.png" /><figcaption>Change in filter_calls</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*gP8MgMudAWFMF2b9oisEBg.png" /><figcaption>Change in select_strike</figcaption></figure><p>And run the simulation again:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/1*Qd4gGn8YYGuoCsqkP4yecA.png" /></figure><p>The probability of the call being exercised at the $115 strike price is significantly lower than in our previous example, with only a 9% chance of exercise. This implies a reduced likelihood of capturing the capped profit from a covered call, representing the first risk in this strategy.</p><p>The second risk arises from the high probability (91%) that the call will expire unexercised, meaning that, while you’ll collect a modest premium, you’ll retain ownership of the shares most of the time. Consequently, this shifts the strategy away from the more reliable income (previously a 40% chance of exercise with a capped profit) toward a setup where returns are more heavily influenced by market fluctuations. This approach is therefore more exposed to both favorable and unfavorable market conditions, without the assurance of a defined profit.</p><h4><strong>What to Expect?</strong></h4><p>Imagine that you always sell your stocks if you call is not exercised and that the <strong>market was against you</strong> (we consider the defavorable price shown by our simulator)</p><p>In our low-risk scenario, the option expires in 28 days and the spot price is just above $95. There is a 38.5% chance that the call will be exercised, and a 61.5% chance that it will not. If the option is exercised, the profit is $499. Conversely, if it is not exercised, the profit/loss is calculated as the premium received minus the loss on the stock, resulting in $407 — $908 = -$501.</p><p>The expected value in this scenario can be calculated by weighing the various outcomes along with their probabilities of occurring:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*cDyDklNylJVB7u0Cb1QIoA.png" /></figure><p>This translates to an<strong> average loss of about $4 per day</strong>.</p><p>In the medium-risk scenario, the option expires in 77 days. Here, there is a 9% chance that the call will be exercised and a 91% chance that it will not. If the option is exercised, the profit is $2,067, as the strike price is approximately $20 away from the current spot price (strike at $115). If the option is not exercised, the profit is the premium received minus the stock loss, which is $75 — $1,492 = -$1,417.</p><p>The expected value for this scenario is calculated as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*n5d-hXbVul0aRSGJw3zcpA.png" /></figure><p>This translates to an <strong>average loss of about $14 per day</strong>.</p><p>However, the medium-risk approach offers a higher potential reward if the stock performs well, primarily due to the greater distance from the strike price before it is exercised. If the market conditions are favorable and the stock price remains just below the strike price at, for example, $114 in 91% of the scenarios, the profit would be calculated as ($114−$95) per share, resulting in a total profit of $1,900 for 100 shares. Consequently, the expected value for this scenario over 77 days would be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*zelbUi3eTlxj4ffKaYJJLQ.png" /></figure><p>In the low-risk scenario, the possible upside without the call being unexercised could not exceed about $100 (the strike was just $1 away from the spot price).</p><p>Adding the different expected values into the simulator is left as an exercise to the reader.</p><h4><strong>Conclusion</strong></h4><p>The art of implementing covered call strategies through stochastic optimization with the great help of the AI reveals itself as a delicate balance between risk management and potential returns. Our exploration, through Black-Scholes model and Monte Carlo process, backed by Diaz’s research and extensive simulations, demonstrates that success lies not in seeking a universal solution, but in aligning strategy selection with individual risk tolerance and investment objectives.</p><p>When implementing these strategies in practice, investors must carefully weigh their market outlook against their appetite for risk.</p><p><em>Disclaimer: The information provided in this article is for educational purposes only. It is not intended as financial advice, and readers are encouraged to seek professional guidance before making any investment decisions.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aea5d52c0689" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-investors-handbook/exploring-covered-call-strategy-using-stochastics-part-2-aea5d52c0689">Exploring Covered Call Strategy using Stochastics — Part 2</a> was originally published in <a href="https://medium.com/the-investors-handbook">Investor’s Handbook</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Covered Call Strategy using Stochastics — Part 1]]></title>
            <link>https://medium.com/the-investors-handbook/exploring-covered-call-strategy-using-stochastics-part-1-397ba97b581e?source=rss-c059fd00a0db------2</link>
            <guid isPermaLink="false">https://medium.com/p/397ba97b581e</guid>
            <category><![CDATA[stochastic-modelling]]></category>
            <category><![CDATA[options-trading]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[chatgpt]]></category>
            <dc:creator><![CDATA[K4096K]]></dc:creator>
            <pubDate>Wed, 23 Oct 2024 20:43:12 GMT</pubDate>
            <atom:updated>2024-11-01T22:06:54.654Z</atom:updated>
            <content:encoded><![CDATA[<h3>Exploring Covered Call Strategy using Stochastics — Part 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TvdZ56mRCvf0zkr2hmjwYg.png" /></figure><p>In today’s dynamic financial markets, traders and investors are continuously seeking strategies that balance risk and reward. One such popular method is the covered call strategy, often utilized to generate additional income from existing stock holdings. In my first serie of articles, “<strong>Unlocking the Power of Covered Calls using ChatGPT</strong>” (<a href="https://medium.com/the-investors-handbook/unlocking-the-power-of-covered-calls-with-chatgpt-part-1-7734deab5421">Part 1</a>,<a href="https://medium.com/@k4096/unlocking-the-power-of-covered-calls-with-chatgpt-part-2-0648e98a72e7"> Part 2</a>, P<a href="https://medium.com/@k4096k/unlocking-the-power-of-covered-calls-with-chatgpt-part-3-e3521ac8302d">art 3</a>), I introduced the foundational concepts of covered calls and outlined key criteria to consider when developing an effective strategy.</p><p>In this article, we explore how incorporating simulated prices can enhance the effectiveness of the covered call strategy. We will leverage the power of ChatGPT to build a simulation tool using Python, incorporating Monte Carlo methods to model and analyze the covered call strategy. By using <strong>stochastic simulations — randomly generated price paths based on probabilistic models </strong>— we can better understand how the strategy might perform under various market conditions.</p><p>ChatGPT will guide the development process, helping us create a dynamic tool that evaluates potential outcomes and optimizes key parameters. This approach provides a practical framework for applying the covered call strategy in real-world, uncertain market environments.</p><h4><strong>Simple Modeling of the Market</strong></h4><p>As you may know, stock prices in the market follow somewhat random paths, but they are not entirely unpredictable. Prices exhibit intrinsic characteristics that are heavily influenced by the specific asset in question, as well as broader micro- and macroeconomic factors. It’s also important to note that the behavior of stock prices can appear differently depending on the time scale at which they are observed, revealing varying patterns and dynamics across short-term and long-term perspectives.</p><p>To illustrate this in a simple manner, let’s consider the stock “Lockheed Martin Corp.” (LMT), a US company in the defense sector. The chart below is plotting the moving average (blue line) over 4 periods in weekly scale. The moving average removes some noise caused by smaller timescales. The dashed line in red is the “regression line”, that shows the overall direction for the data present in this blue curve.<strong> It’s like drawing the best possible line to summarize the underlying data.</strong></p><p>nb. the curious reader may refer to this article for a deeper, mathematical explanation about (linear) regressions: <a href="https://medium.com/analytics-vidhya/understanding-the-linear-regression-808c1f6941c0">https://medium.com/analytics-vidhya/understanding-the-linear-regression-808c1f6941c0</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dEupoxoZEHkrO0wjBtfB2A.png" /></figure><p>A very simplistic model might use this straight line to predict stock prices for the coming days, months, or years. However, this approach wouldn’t be very effective, as markets don’t move in a straight line. Instead, they fluctuate in a complex pattern of rises, falls, crashes, peaks, and waves, reflecting the inherent volatility and unpredictability of financial markets.</p><p>Volatility is a well-known parameter in the market. Some stocks are highly volatile, meaning their prices fluctuate significantly, while others are more stable, with price changes being less pronounced over time. To incorporate this into our simple model, we could define a “channel” that represents a plausible range where prices are likely to move. In this model, we can create green and red bands, indicating the areas where the price is expected to stay 95% of the time. Statistically, these green and red lines are positioned<strong> </strong>2 standard deviations away from the mean, providing a visual representation of the stock’s potential price movement range. This helps account for the inherent uncertainty in predicting future prices while factoring in volatility.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vQrMS3lNZ7xlgFpH-7T3Mw.png" /></figure><p>As you can see, LMT’s prices generally stay within this channel, with the exception of a recent period where a sharp breakout occurred. Using this model, however, provides a clearer indication of potential price movements over the next two years: around <strong>$600</strong> for a bullish outlook or approximately <strong>$475</strong> for a more bearish scenario, with the mean hovering near <strong>$525</strong>.</p><p>It’s important to remember that this is a simplified model, based only on data from the past 15 years and a limited number of parameters. While useful for rough estimates, it oversimplifies the complexity of market dynamics.</p><h4><strong>Better Modeling using Black-Scholes</strong></h4><p>The Black-Scholes model is a mathematical model used to calculate the theoretical price of options. Developed by economists Fischer Black, Myron Scholes, and Robert Merton in the early 1970s, the model revolutionized the options market and remains widely used today.</p><p>I won’t dive into the mathematical intricacies of the model, but it relies on variables similar to the Greeks we discussed in Part 2 of my covered calls series.</p><p>The approach begins with an initial stock price and calculates a new price at each time step (such as daily) by taking the previous price and adding a random price change influenced by volatility and the risk-free rate. These parameters can vary across different stocks and assets, and they can be determined by analyzing historical data.</p><p>Because of its random nature, this process mimics the actual behavior of stock prices more closely. However, this randomness also means that if you restart the simulation, you will likely get a different outcome each time.</p><p>We don’t need to understand the full mathematical picture to put this into action using ChatGPT.</p><p><em>I want to make a script in Python that fetches the historical prices from Yahoo for a given ticker. To avoid unnecessary calls, historical prices must be kept on the disk in a file whose name contains the ticker. The file must only be refreshed if it’s older than 1 day. This data will be used to model a plausible price evolution for the next 365 days, starting from today. The Black-Scholes model should be used. At the end, I would like that you plot the resulting path. Be careful to annualize the settings you are using.</em></p><p>ChatGPT indicates some libraries are necessary, we install them using pip in a command line:</p><p><strong>&gt; pip install yfinance numpy pandas matplotlib</strong></p><pre>import os<br>import pandas as pd<br>import numpy as np<br>import yfinance as yf<br>import matplotlib.pyplot as plt<br>from datetime import datetime, timedelta<br><br>def fetch_historical_prices(ticker):<br>    &quot;&quot;&quot;Fetch historical prices from Yahoo Finance.&quot;&quot;&quot;<br>    today = datetime.now().date()<br>    file_name = f&quot;{ticker}_historical_prices.csv&quot;<br><br>    # Check if the file exists and its age<br>    if os.path.exists(file_name):<br>        file_mod_time = datetime.fromtimestamp(os.path.getmtime(file_name)).date()<br>        if (today - file_mod_time) &lt; timedelta(days=1):<br>            print(f&quot;Using cached data from {file_name}&quot;)<br>            return pd.read_csv(file_name, index_col=0, parse_dates=True)<br><br>    # Fetch the data if file is older than 1 day or does not exist<br>    print(f&quot;Fetching new data for {ticker}...&quot;)<br>    data = yf.download(ticker, start=&#39;2020-01-01&#39;, end=today)<br>    <br>    # Save to a CSV file<br>    data.to_csv(file_name)<br>    return data<br><br>def black_scholes_simulation(start_price, mu, sigma, days=365):<br>    &quot;&quot;&quot;Simulate future price paths using the Black-Scholes model.&quot;&quot;&quot;<br>    dt = 1 / 365  # Daily time increment<br>    prices = [start_price]<br>    <br>    for _ in range(days):<br>        price_t = prices[-1]<br>        # Simulate the next price<br>        price_t1 = price_t * np.exp((mu - 0.5 * sigma ** 2) * dt + sigma * np.sqrt(dt) * np.random.normal())<br>        prices.append(price_t1)<br><br>    return prices<br><br>def main(ticker):<br>    # Fetch historical prices<br>    historical_data = fetch_historical_prices(ticker)<br>    <br>    # Calculate daily returns<br>    historical_data[&#39;Return&#39;] = historical_data[&#39;Adj Close&#39;].pct_change()<br>    mu = historical_data[&#39;Return&#39;].mean()<br>    sigma = historical_data[&#39;Return&#39;].std()<br><br>    # Get the last price<br>    start_price = historical_data[&#39;Adj Close&#39;][-1]<br><br>    # Simulate future prices<br>    simulated_prices = black_scholes_simulation(start_price, mu, sigma)<br><br>    # Plotting the results<br>    plt.figure(figsize=(10, 6))<br>    plt.plot(simulated_prices, label=&#39;Simulated Price Path&#39;)<br>    plt.title(f&#39;Simulated Price Path for {ticker}&#39;)<br>    plt.xlabel(&#39;Days&#39;)<br>    plt.ylabel(&#39;Price&#39;)<br>    plt.legend()<br>    plt.grid()<br>    plt.show()<br><br>if __name__ == &quot;__main__&quot;:<br>    ticker = input(&quot;Enter the stock ticker symbol: &quot;)<br>    main(ticker)<br></pre><p>Save this script as model1.py then execute it:</p><p>&gt; python model1.py</p><p>After running the script, you will see a graph depicting the simulated price path for the given stock ticker. Each time you execute the script, the output may vary since the price path is generated based on a random process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KuCNiQ76MBxkqKlp0nFe3Q.png" /></figure><p>In a second run, I get this price evolution:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*3l7It9MaULR8vypsGFtFzg.png" /></figure><h4><strong>Making it Monte-Carlo</strong></h4><p>Now imagine that we execute this (stochastic) process over and over, say 500 times. This is what is called a Monte-Carlo simulation. Instead of calculating outcomes directly, it creates numerous scenarios and possible outcomes. Afterward, the results are analyzed to identify patterns or probabilities, allowing you to see, for example, that the prices will fall within a given range most of the time. This method is used in a wide set of domains, not only in financial engineering.</p><p>We ask ChatGPT to amend the existing script:</p><p><em>Adapt the script to repeat the simulation process 500 times, all the curves must be plotted on the same plot</em></p><p>When executed, you will see the 500 simulated price paths for the entered stock ticker plotted on the same graph, showcasing the range of potential price movements based on historical volatility and trends.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8zfzY043wV7ah8NpFTMpkg.png" /></figure><p>The simulation results reveal some intriguing patterns. Most of the simulated paths start from the initial price of <strong>$575</strong> and tend to converge within a range of approximately <strong>$450 to $800</strong>. However, there are notable outliers that exhibit more erratic trajectories. Some of these paths rise as high as <strong>$1600</strong>, while others take a bearish turn, dipping down under <strong>$300</strong>.</p><p>To further analyze these price movements, we can calculate and visualize the “mean path” of the simulations. Additionally, we can identify and plot the two paths that deviate by two standard deviations from this mean. This approach will mirror our earlier model, which utilized a straightforward linear representation, allowing for a clearer understanding of potential price fluctuations.</p><p>We ask ChatGPT to proceed with these improvements:</p><p><em>Adapt the script to plot the mean path of the simulations (in thick white), as well as the two paths that deviate by two standard deviations from this mean (in thick blue). I also need one standard deviations from this mean (in thin cyan) I also want you to adapt the colors of each path by looking at its final price. If it’s above the mean value, plot it in dark green, otherwise in dark red. If it’s above one standard deviation, plot it in light green, resp. light red. Everything that is above or below two standard deviations, must be shown in grey.</em></p><p>We execute the adapted script and we get the following plot. Pretty neat, no?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*heNtDX6K02q4lHDdT4H0ew.png" /></figure><p>The blue lines are the boundaries where prices will stay within 95% of the time. The cyan lines are for 68% of the time. As we can see, the increased uncertainty inherent in financial markets leads to greater variability in potential prices as we move further away from the initial price. This reflects the natural volatility of asset prices over time.</p><pre>import os<br>import pandas as pd<br>import numpy as np<br>import yfinance as yf<br>import matplotlib.pyplot as plt<br>from datetime import datetime, timedelta<br><br>def fetch_historical_prices(ticker):<br>    &quot;&quot;&quot;Fetch historical prices from Yahoo Finance, caching if less than 1 day old.&quot;&quot;&quot;<br>    today = datetime.now().date()<br>    file_name = f&quot;{ticker}_historical_prices.csv&quot;<br><br>    # Check if the file exists and its age<br>    if os.path.exists(file_name):<br>        file_mod_time = datetime.fromtimestamp(os.path.getmtime(file_name)).date()<br>        if (today - file_mod_time) &lt; timedelta(days=1):<br>            print(f&quot;Using cached data from {file_name}&quot;)<br>            return pd.read_csv(file_name, index_col=0, parse_dates=True)<br><br>    # Fetch the data if file is older than 1 day or does not exist<br>    print(f&quot;Fetching new data for {ticker}...&quot;)<br>    data = yf.download(ticker, start=&#39;2020-01-01&#39;, end=today)<br>    <br>    # Save to a CSV file<br>    data.to_csv(file_name)<br>    return data<br><br>def black_scholes_simulation(start_price, mu, sigma, days=365):<br>    &quot;&quot;&quot;Simulate a single future price path using the Black-Scholes model.&quot;&quot;&quot;<br>    dt = 1 / 365  # Daily time increment<br>    prices = [start_price]<br>    <br>    for _ in range(days):<br>        price_t = prices[-1]<br>        # Simulate the next price with annualized parameters<br>        price_t1 = price_t * np.exp((mu - 0.5 * sigma ** 2) * dt + sigma * np.sqrt(dt) * np.random.normal())<br>        prices.append(price_t1)<br><br>    return prices<br><br>def main(ticker, simulations=500):<br>    # Fetch historical prices<br>    historical_data = fetch_historical_prices(ticker)<br>    <br>    # Calculate daily returns<br>    historical_data[&#39;Return&#39;] = historical_data[&#39;Adj Close&#39;].pct_change()<br>    daily_mu = historical_data[&#39;Return&#39;].mean()<br>    daily_sigma = historical_data[&#39;Return&#39;].std()<br><br>    # Annualize the mean and standard deviation<br>    mu = daily_mu * 252  # Assuming 252 trading days in a year<br>    sigma = daily_sigma * np.sqrt(252)<br><br>    # Get the last price<br>    start_price = historical_data[&#39;Adj Close&#39;][-1]<br><br>    # Run multiple simulations and store paths<br>    all_simulated_prices = [black_scholes_simulation(start_price, mu, sigma) for _ in range(simulations)]<br>    all_simulated_prices = np.array(all_simulated_prices)<br><br>    # Calculate the mean path and standard deviations across simulations<br>    mean_path = all_simulated_prices.mean(axis=0)<br>    std_dev_path = all_simulated_prices.std(axis=0)<br>    upper_2std_bound = mean_path + 2 * std_dev_path<br>    lower_2std_bound = mean_path - 2 * std_dev_path<br>    upper_1std_bound = mean_path + std_dev_path<br>    lower_1std_bound = mean_path - std_dev_path<br><br>    # Plot each path with conditional coloring<br>    plt.figure(figsize=(12, 8))<br>    for prices in all_simulated_prices:<br>        final_price = prices[-1]<br>        mean_final_price = mean_path[-1]<br>        upper_1std_final_price = mean_path[-1] + std_dev_path[-1]<br>        lower_1std_final_price = mean_path[-1] - std_dev_path[-1]<br>        upper_2std_final_price = mean_path[-1] + 2 * std_dev_path[-1]<br>        lower_2std_final_price = mean_path[-1] - 2 * std_dev_path[-1]<br><br>        # Determine color based on final price<br>        if final_price &gt; upper_2std_final_price or final_price &lt; lower_2std_final_price:<br>            color = &#39;grey&#39;  # More than 2 std devs from the mean<br>        elif final_price &gt; upper_1std_final_price:<br>            color = &#39;lightgreen&#39;  # Between 1 and 2 std devs above the mean<br>        elif final_price &lt; lower_1std_final_price:<br>            color = &#39;lightcoral&#39;  # Between 1 and 2 std devs below the mean<br>        elif final_price &gt; mean_final_price:<br>            color = &#39;darkgreen&#39;  # Above mean but within 1 std dev<br>        else:<br>            color = &#39;darkred&#39;  # Below mean but within 1 std dev<br>        <br>        plt.plot(prices, color=color, alpha=0.6)<br><br>    # Plot the mean path in thick white<br>    plt.plot(mean_path, color=&#39;white&#39;, label=&#39;Mean Path&#39;, linewidth=2.5)<br><br>    # Plot the upper and lower bounds (± 2 std devs) in thick blue<br>    plt.plot(upper_2std_bound, color=&#39;blue&#39;, linestyle=&#39;--&#39;, label=&#39;Upper Bound (Mean + 2 Std Dev)&#39;, linewidth=2)<br>    plt.plot(lower_2std_bound, color=&#39;blue&#39;, linestyle=&#39;--&#39;, label=&#39;Lower Bound (Mean - 2 Std Dev)&#39;, linewidth=2)<br><br>    # Plot the upper and lower bounds (± 1 std dev) in thin cyan<br>    plt.plot(upper_1std_bound, color=&#39;cyan&#39;, linestyle=&#39;--&#39;, label=&#39;Upper Bound (Mean + 1 Std Dev)&#39;, linewidth=1)<br>    plt.plot(lower_1std_bound, color=&#39;cyan&#39;, linestyle=&#39;--&#39;, label=&#39;Lower Bound (Mean - 1 Std Dev)&#39;, linewidth=1)<br><br>    # Plotting settings<br>    plt.title(f&#39;{simulations} Simulated Price Paths for {ticker} over Next 365 Days&#39;)<br>    plt.xlabel(&#39;Days&#39;)<br>    plt.ylabel(&#39;Price&#39;)<br>    plt.legend()<br>    plt.grid()<br>    plt.show()<br><br>if __name__ == &quot;__main__&quot;:<br>    ticker = input(&quot;Enter the stock ticker symbol: &quot;)<br>    main(ticker)</pre><h4><strong>Application for Covered Calls</strong></h4><p>In a covered call strategy, we try to find the best contract for us by considering the strike, expiration, premium, “moneyness” (ITM/OTM) and also the greeks. We also have to consider our view on the market and the stock that will be subject to the covered call.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*RTaBB0CBSGBmMhzU7IxjvA.png" /></figure><p>Let’s consider a scenario where we want to implement a covered call on LMT, which is currently priced at <strong>$577</strong>. We plan to select options with an expiration set for <strong>100 days</strong> from now. Our model suggests plausible stock prices in 100 days could range from <strong>$740 </strong>if we are extremely optimistic to <strong>$425 </strong>if we are extremely pessimistic (~95 chances we are within these blue lines). If we are more reasonable, we look at the first deviation (~68% chance) which is on the cyan lines: <strong>$660 for the upper bound, $505 for the lower bound, with a mean estimated price of $583.</strong></p><p>This information serves as a valuable decision-making tool. If we have a bullish outlook on the market and wish to retain our 100 shares while also collecting a (small) premium, we might consider selecting a strike price of close to the upper bound. This way would benefit from both the premium but also the stock’s appreciation.</p><p>Conversely, if we have a bearish outlook on the stock, our approach will depend on whether we want to retain our shares. If we decide to keep the shares, we might choose a lower strike price. This way, we can still collect a (higher) premium. Alternatively, if we prefer not to engage in this trade, we can simply explore other investment opportunities.</p><h4><strong>Next article…</strong></h4><p>In the <a href="https://medium.com/@k4096k/exploring-covered-call-strategy-using-stochastics-part-2-aea5d52c0689">next article</a>, we will explore how to automate part of the decision-making process by applying the covered call strategy across various expiration dates and strike prices, utilizing Monte Carlo simulations for analysis and by considering different risks.</p><p><em>Disclaimer: The information provided in this article is for educational purposes only. It is not intended as financial advice, and readers are encouraged to seek professional guidance before making any investment decisions.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=397ba97b581e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-investors-handbook/exploring-covered-call-strategy-using-stochastics-part-1-397ba97b581e">Exploring Covered Call Strategy using Stochastics — Part 1</a> was originally published in <a href="https://medium.com/the-investors-handbook">Investor’s Handbook</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unlocking the Power of Covered Calls with ChatGPT — Part 3]]></title>
            <link>https://medium.com/the-investors-handbook/unlocking-the-power-of-covered-calls-with-chatgpt-part-3-e3521ac8302d?source=rss-c059fd00a0db------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3521ac8302d</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[options-trading]]></category>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[covered-call]]></category>
            <dc:creator><![CDATA[K4096K]]></dc:creator>
            <pubDate>Wed, 23 Oct 2024 13:22:27 GMT</pubDate>
            <atom:updated>2024-10-29T20:34:29.928Z</atom:updated>
            <content:encoded><![CDATA[<h3>Unlocking the Power of Covered Calls with ChatGPT — Part 3</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yZSjVRbvUdql2r82bhdpqg.png" /></figure><p>For experienced traders, the <strong>covered call strategy</strong> offers a powerful way to generate additional income while managing risk. This strategy involves owning a stock and selling call options on it, allowing you to benefit from both potential capital appreciation and option premiums. However, selecting the optimal strike price, expiration date, and timing can be challenging, especially in today’s fast-paced markets with numerous variables to consider.</p><p>In <a href="https://medium.com/the-investors-handbook/unlocking-the-power-of-covered-calls-with-chatgpt-part-1-7734deab5421"><strong>Part 1</strong></a>, we introduced the covered call strategy and provided guidelines on when it’s appropriate and when it should be avoided. We used a real example of a stock of the US market (Pfizer).</p><p>In <a href="https://medium.com/the-investors-handbook/unlocking-the-power-of-covered-calls-with-chatgpt-part-2-0648e98a72e7"><strong>Part 2</strong></a>, we took a deeper dive, exploring more advanced parameters around options with the help of <strong>ChatGPT</strong> to refine decision-making.</p><p>In this final article, we’ll go even further by building a simple tool in <strong>Python </strong>that generates option picks for a given ticker based on the criteria we’ve discussed, making it easier to implement the strategies outlined here.</p><p><strong>Installing Python</strong></p><p>Numerous guides and tutorials are available to help you set up Python. If you are using Windows, the simplest approach is to visit the official Python download page and download the latest version. As of this writing, the most recent release is Python 3.13.0.</p><p><a href="https://www.python.org/downloads/">Download Python</a></p><p><strong>Getting the Data</strong></p><p>Our tool requires specific input, including the following mandatory information: the ticker symbol (e.g., PFE), the options chain with Greeks, and the current stock price.</p><p>There are various data providers available, ranging from free or limited options to more comprehensive but costly alternatives. It is essential that our tool allows for easy data downloads without relying on manual processes. While Yahoo provides an options chain, it lacks the Greeks, and we prefer not to calculate them ourselves. So far, the best option I’ve found is <a href="https://finnhub.io/"><strong>Finnhub.io</strong></a>, which offers an API (application programming interface) that delivers options chains along with numerous other features.</p><p><strong>Disclaimer:</strong> I am not affiliated with this provider in any way, but I appreciate their generous offering of such a robust API for options data at no cost.</p><p>You need to first register:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p_edRUx_ZgdrR9wb4IN_1A.png" /></figure><p>In the dashboard, you will find your “API Key,” which is essential for accessing data from their API. This key functions similarly to a password, so it’s crucial to keep it confidential and never share it with anyone.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*wJ79YJOTMOYUc0ymTHtDQA.png" /></figure><p>To test if everything is alright, just launch a browser and navigate to the following URL. You must replace the “token” parameter with your actual API key:</p><p><a href="https://finnhub.io/api/v1/stock/option-chain?symbol=DIS&amp;token=REPLACE_THIS_VALUE_WITH_YOUR_API_KEY"><strong>https://finnhub.io/api/v1/stock/option-chain?symbol=DIS&amp;token=REPLACE_THIS_VALUE_WITH_YOUR_API_KEY</strong></a></p><p>You should get as a result a JSON content that contains the different information about the options.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*WKI4AtJVlFEwIyt94iCTxg.png" /></figure><p>This is a formatted excerpt showcasing the type of information provided by Finnhub.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/909/1*-Es2CGMO2yFsPtOsVOuEkA.png" /></figure><p><strong>Automate the Chain Retrieval</strong></p><p>To streamline our process, we aim to automate the retrieval of the options chain for a given ticker. Since we’re not operating in the high-frequency trading space, we don’t require real-time data. Instead, we’ll maintain a cached copy of the options chain to minimize unnecessary calls to the Finnhub API. Additionally, we will store the API key in a separate apikey.txt file, allowing us to share the script without exposing our sensitive information.</p><p>We’ll make our request using the standard ChatGPT-4 model (rather than the latest ChatGPT-4o model). Let’s begin with an initial prompt:</p><p><em>I would like to write a Python script that retrieves the options chain for a given ticker. It must use the API of finnhub and store the result (JSON file) locally on my disk, the file must be distinct for each ticker.</em></p><p><em>To avoid unnecessary calls, I do not want to download the options chain each time the script is called, you can use the save date of the file for this. The script must check if the download is older than 4 hours. If that’s the case, if must download a fresh copy from the API.</em></p><p><em>I want to store the API key in a separate file called “apikey.txt”, you must read from it. Example of the option chain API: </em><a href="https://finnhub.io/api/v1/stock/option-chain"><em>https://finnhub.io/api/v1/stock/option-chain</em></a></p><p>ChatGPT answers with a first script. It also invites me to install an additional lib called “requests”, so on the command line, I issue the following:</p><p><em>pip install requests</em></p><p>I saved the Python script as covered_call_candidates.py and created a file named apikey.txt in the same directory, where I stored my API key.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*fXTjW-GP3HA7avmiqXXqjw.png" /></figure><p>This is the first proposed version by ChatGPT:</p><pre>import os<br>import json<br>import time<br>import requests<br>from datetime import datetime, timedelta<br><br># Constants<br>API_URL = &quot;https://finnhub.io/api/v1/stock/option-chain&quot;<br>API_KEY_FILE = &quot;apikey.txt&quot;<br>DATA_DIR = &quot;options_data&quot;<br><br># Function to read API key from file<br>def read_api_key():<br>    with open(API_KEY_FILE, &#39;r&#39;) as file:<br>        return file.read().strip()<br><br># Function to get options chain data<br>def get_options_chain(ticker):<br>    api_key = read_api_key()<br>    params = {<br>        &#39;symbol&#39;: ticker,<br>        &#39;token&#39;: api_key<br>    }<br>    response = requests.get(API_URL, params=params)<br><br>    if response.status_code == 200:<br>        return response.json()<br>    else:<br>        print(f&quot;Error fetching data: {response.status_code} - {response.text}&quot;)<br>        return None<br><br># Function to save data to a JSON file<br>def save_data(ticker, data):<br>    if not os.path.exists(DATA_DIR):<br>        os.makedirs(DATA_DIR)<br>    <br>    file_path = os.path.join(DATA_DIR, f&quot;{ticker}_options.json&quot;)<br>    with open(file_path, &#39;w&#39;) as json_file:<br>        json.dump(data, json_file)<br>    <br>    print(f&quot;Data saved to {file_path}&quot;)<br><br># Function to check if the file is outdated<br>def is_file_outdated(ticker):<br>    file_path = os.path.join(DATA_DIR, f&quot;{ticker}_options.json&quot;)<br>    if os.path.exists(file_path):<br>        file_mod_time = datetime.fromtimestamp(os.path.getmtime(file_path))<br>        if datetime.now() - file_mod_time &lt; timedelta(hours=4):<br>            return False  # File is not outdated<br>    return True  # File does not exist or is outdated<br><br># Main function<br>def main(ticker):<br>    if is_file_outdated(ticker):<br>        print(f&quot;Fetching new data for {ticker}...&quot;)<br>        options_data = get_options_chain(ticker)<br>        if options_data:<br>            save_data(ticker, options_data)<br>    else:<br>        print(f&quot;Using cached data for {ticker}.&quot;)<br><br>    # Load and return the existing (or freshly fetched) data<br>    with open(os.path.join(DATA_DIR, f&quot;{ticker}_options.json&quot;), &#39;r&#39;) as json_file:<br>        return json.load(json_file)<br><br>if __name__ == &quot;__main__&quot;:<br>    ticker_symbol = input(&quot;Enter the ticker symbol: &quot;).strip().upper()<br>    options_chain = main(ticker_symbol)<br>    print(options_chain)</pre><p>Let’s test our script by running the command python covered_call_candidates.py in the command line. When prompted, I entered the ticker symbol <strong>DIS</strong> and pressed Enter. The script notified me that a local copy did not exist and proceeded to fetch the data. The content was displayed on the screen, and at the end of the process, a new file named <strong>DIS_options_chain.json</strong> was created and saved.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*n_kqP-d7v6k6zcww3RMsoA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*w9HdsRGw0TaQVkO_vT67cA.png" /></figure><p>If we run the Python script a second time, the response will be much quicker since it will load the data from the stored copy on the disk.</p><p>You may want to examine the contents of <strong>DIS_options_chain.json</strong> to understand its structure and the available properties. At the top of the file, you will find general information, including the ticker and the current price. Below that, there is a data section that contains blocks for each expiration date. Within each of these blocks, you’ll find an array of “options,” which can be classified as either “CALL” or “PUT.” Inside each option, all the relevant details you need — such as strike price, ask/bid, Greeks, and more — are provided.</p><p><strong>Making the Brain</strong></p><p>Now that we have the options chain, we can use it to identify the best candidates for our covered call strategy. I will share the intermediate prompts we use to develop our desired tool, but to maintain clarity in the article, I will only provide the Python script at significant milestones.</p><p>As mentioned in Article 2, there are several criteria we would like to apply in our analysis.</p><p><em>Augment this script to analyze the options chain in the context of a covered call strategy. In this strategy, my goal would be to buy 100 shares at the current market price, and also sell a call. I don’t want to enter the current price manually, you must extract all the info by yourself .You must analyze the different calls at different expirations (expiring before 6 months) and propose me the best candidates. They must be sorted by the maximum profit they can provide me if they are exercised. The profit in case of exercise is the median price (between bid and ask) *100 + (strike*100 — market_price*100). I want the result to be shown in a table with aligned columns. Max decimals: 2.</em></p><p>ChatGPT suggested a new script, which I ran; however, it failed because it wasn’t properly reading the structure of the JSON file. To assist in resolving this, I provided additional context regarding the JSON payload (I’ve omitted part of the payload here for clarity, but the full information was included in the prompt).</p><p><em>Here is an extract of the JSON:<br>{<br> “code”: “DIS”,<br> “exchange”: “US”,<br> “lastTradeDate”: “2024–10–22”,<br> “lastTradePrice”: 96.74,<br> “data”: [<br> {<br>(…)<br> “options”: { <br> “CALL”: [<br> {<br> “contractName”: “DIS241025C00060000”,<br>(…)<br> “daysBeforeExpiration”: 2<br> },</em></p><p>This second version of the script is a significant improvement, but we need to evaluate whether it functions correctly. Additionally, we want to ensure that it returns only the top 10 candidates, along with an indication of the current price and other relevant information. Currently, the script displays the median price for a single share, whereas we need it to reflect the total for 100 shares.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*PT6be5Ll8o6af3kr5nmqHg.png" /></figure><p><em>Adapt the script to only consider the 10 best candidates, you must also indicate the current price of the share (before the table). I also want to see another column called “Median Price (x100)” to show the actual contract price. I also want a column called “Profit if not exercised” which correspond to the premium only (I keep the shares). Please also add a first column with the contract name. Just provide me the final implementation</em></p><p>This looks much better:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cAOhckSSFbcAwEPn4c9hkw.png" /></figure><p>Let’s quickly verify what has been implemented. ChatGPT indicates that for the contract <strong>DIS250321C00180000</strong>, expiring on <strong>2025–03–21</strong> with a strike price of <strong>180</strong> and a median price of <strong>6.50</strong> (for 100 shares), we would achieve a maximum profit of <strong>$8,332.50</strong> if exercised and <strong>$650</strong> if not exercised.</p><p>I checked the bid/ask prices on optionscharts.io, and they align with what ChatGPT has provided, confirming that the median price of <strong>$0.065</strong> per share is accurate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*-8Sw27iNendsA4acemnS1w.png" /></figure><p>The premium we collect is therefore <strong>6.50</strong>. In the event the covered call is exercised, we would purchase the 100 shares at <strong>$96.74</strong>, totaling <strong>$9,674</strong>. With the strike price set at <strong>$180</strong>, we would sell the shares for <strong>$18,000</strong>. This results in a gain of <strong>$8,332.50</strong> calculated as follows: <strong>$18,000 — $9,674 + 6.50 = $8,332.50</strong>. The formula provided by ChatGPT is correct.</p><p>However, these candidates are not particularly attractive. They are extremely deep out-of-the-money (OTM), offering a low premium that lacks appeal. Furthermore, these contracts are highly illiquid, making it unlikely that anyone would purchase our call options. With DIS currently trading at <strong>$96</strong>, it is improbable that the stock will reach <strong>$180</strong> within several years — or even decades.</p><p><em>Those candidates are not very good, they are too deep OTM. Please provide better candidates based on the analysis of the greeks and the recommended parameters for a good covered call. Please also consider the volume and open interest to avoid illiquid contracts where I won’t get any buyer for my call.</em></p><p>ChatGPT suggests some criteria that align with those we discussed in the second part of the article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*wWnU650EvkzlxbFqqDiYVg.png" /></figure><p>The new script is much more promising:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FZ46vNEhEp9nhy-DFqwoFA.png" /></figure><pre>import os<br>import json<br>import requests<br>from datetime import datetime, timedelta<br>from tabulate import tabulate<br><br># Constants<br>API_URL_OPTIONS = &quot;https://finnhub.io/api/v1/stock/option-chain&quot;<br>API_URL_QUOTE = &quot;https://finnhub.io/api/v1/quote&quot;<br>API_KEY_FILE = &quot;apikey.txt&quot;<br>DATA_DIR = &quot;options_data&quot;<br>MAX_EXPIRATION_MONTHS = 6<br>TOP_CANDIDATES = 10  # Limit to top 10 candidates<br>DELTA_MIN = 0.40     # Minimum delta threshold<br>DELTA_MAX = 0.70     # Maximum delta threshold<br>IV_MIN = 20          # Minimum implied volatility threshold (in %)<br>OPEN_INTEREST_MIN = 100  # Minimum open interest for liquidity<br>VOLUME_MIN = 100         # Minimum volume for activity<br>STRIKE_PROXIMITY = 0.1  # Maximum percentage difference from current price<br><br># Function to read API key from file<br>def read_api_key():<br>    with open(API_KEY_FILE, &#39;r&#39;) as file:<br>        return file.read().strip()<br><br># Function to get options chain data<br>def get_options_chain(ticker):<br>    api_key = read_api_key()<br>    params = {<br>        &#39;symbol&#39;: ticker,<br>        &#39;token&#39;: api_key<br>    }<br>    response = requests.get(API_URL_OPTIONS, params=params)<br><br>    if response.status_code == 200:<br>        return response.json()<br>    else:<br>        print(f&quot;Error fetching options data: {response.status_code} - {response.text}&quot;)<br>        return None<br><br># Function to get the current market price<br>def get_current_price(ticker):<br>    api_key = read_api_key()<br>    params = {<br>        &#39;symbol&#39;: ticker,<br>        &#39;token&#39;: api_key<br>    }<br>    response = requests.get(API_URL_QUOTE, params=params)<br><br>    if response.status_code == 200:<br>        quote_data = response.json()<br>        return quote_data[&#39;c&#39;]  # Current price<br>    else:<br>        print(f&quot;Error fetching current price: {response.status_code} - {response.text}&quot;)<br>        return None<br><br># Function to save data to a JSON file<br>def save_data(ticker, data):<br>    if not os.path.exists(DATA_DIR):<br>        os.makedirs(DATA_DIR)<br>    <br>    file_path = os.path.join(DATA_DIR, f&quot;{ticker}_options.json&quot;)<br>    with open(file_path, &#39;w&#39;) as json_file:<br>        json.dump(data, json_file)<br>    <br>    print(f&quot;Data saved to {file_path}&quot;)<br><br># Function to check if the file is outdated<br>def is_file_outdated(ticker):<br>    file_path = os.path.join(DATA_DIR, f&quot;{ticker}_options.json&quot;)<br>    if os.path.exists(file_path):<br>        file_mod_time = datetime.fromtimestamp(os.path.getmtime(file_path))<br>        if datetime.now() - file_mod_time &lt; timedelta(hours=4):<br>            return False  # File is not outdated<br>    return True  # File does not exist or is outdated<br><br># Function to analyze the options chain for covered call strategy<br>def analyze_covered_call(ticker, market_price):<br>    options_data = get_options_chain(ticker)<br>    <br>    if not options_data or &#39;data&#39; not in options_data:<br>        return []<br><br>    calls = []<br>    for option in options_data[&#39;data&#39;]:<br>        expiration_date = option[&#39;expirationDate&#39;]<br>        expiration = datetime.strptime(expiration_date, &quot;%Y-%m-%d&quot;)<br><br>        # Filter for options expiring within the next 6 months<br>        if expiration &lt;= datetime.now() + timedelta(days=MAX_EXPIRATION_MONTHS * 30):<br>            for call in option[&#39;options&#39;][&#39;CALL&#39;]:<br>                strike = call[&#39;strike&#39;]<br>                bid = call[&#39;bid&#39;]<br>                ask = call[&#39;ask&#39;]<br>                delta = call[&#39;delta&#39;]<br>                iv = call[&#39;impliedVolatility&#39;] * 100  # Convert to percentage<br>                open_interest = call[&#39;openInterest&#39;]<br>                volume = call[&#39;volume&#39;]<br>                contract_name = call[&#39;contractName&#39;]  # Get the contract name<br><br>                # Calculate the percentage difference between strike price and market price<br>                price_diff_percentage = abs(strike - market_price) / market_price<br><br>                # Apply filters based on delta, implied volatility, volume, open interest, and strike proximity<br>                if (DELTA_MIN &lt;= delta &lt;= DELTA_MAX and <br>                    iv &gt;= IV_MIN and <br>                    open_interest &gt;= OPEN_INTEREST_MIN and <br>                    volume &gt;= VOLUME_MIN and <br>                    price_diff_percentage &lt;= STRIKE_PROXIMITY):  # Check if the strike is within 10% of market price<br>                    <br>                    # Calculate median price<br>                    median_price = (bid + ask) / 2<br>                    # Calculate profit if exercised<br>                    profit_if_exercised = (median_price * 100) + (strike * 100 - market_price * 100)<br>                    # Calculate profit if not exercised (premium only)<br>                    profit_if_not_exercised = median_price * 100<br><br>                    calls.append({<br>                        &#39;contract_name&#39;: contract_name,  # Store the contract name<br>                        &#39;expiration&#39;: expiration,<br>                        &#39;strike&#39;: strike,<br>                        &#39;bid&#39;: bid,<br>                        &#39;ask&#39;: ask,<br>                        &#39;median_price&#39;: median_price,<br>                        &#39;profit_if_exercised&#39;: profit_if_exercised,<br>                        &#39;profit_if_not_exercised&#39;: profit_if_not_exercised,<br>                        &#39;delta&#39;: delta,<br>                        &#39;iv&#39;: iv,<br>                        &#39;open_interest&#39;: open_interest,<br>                        &#39;volume&#39;: volume<br>                    })<br>    <br>    # Sort calls by maximum profit if exercised and take top candidates<br>    sorted_calls = sorted(calls, key=lambda x: x[&#39;profit_if_exercised&#39;], reverse=True)[:TOP_CANDIDATES]<br>    return sorted_calls<br><br># Main function<br>def main(ticker):<br>    if is_file_outdated(ticker):<br>        print(f&quot;Fetching new data for {ticker}...&quot;)<br>        options_data = get_options_chain(ticker)<br>        if options_data:<br>            save_data(ticker, options_data)<br>    else:<br>        print(f&quot;Using cached data for {ticker}.&quot;)<br><br>    # Get current market price<br>    market_price = get_current_price(ticker)<br><br>    if market_price is None:<br>        print(&quot;Could not retrieve current market price. Exiting.&quot;)<br>        return<br><br>    print(f&quot;Current market price of {ticker}: ${market_price:.2f}&quot;)<br><br>    # Analyze options chain<br>    analyzed_calls = analyze_covered_call(ticker, market_price)<br><br>    # Display results in a table<br>    if analyzed_calls:<br>        table_data = []<br>        for call in analyzed_calls:<br>            table_data.append([<br>                call[&#39;contract_name&#39;],              # Contract Name<br>                call[&#39;expiration&#39;].strftime(&#39;%Y-%m-%d&#39;),<br>                call[&#39;strike&#39;],<br>                round(call[&#39;bid&#39;], 2),<br>                round(call[&#39;ask&#39;], 2),<br>                round(call[&#39;median_price&#39;], 2),<br>                round(call[&#39;median_price&#39;] * 100, 2),  # Median Price (x100)<br>                round(call[&#39;profit_if_exercised&#39;], 2),<br>                round(call[&#39;profit_if_not_exercised&#39;], 2),<br>                call[&#39;volume&#39;],                    # Add volume to the table<br>                call[&#39;open_interest&#39;]              # Add open interest to the table<br>            ])<br>        <br>        headers = [&quot;Contract Name&quot;, &quot;Expiration&quot;, &quot;Strike&quot;, &quot;Bid&quot;, &quot;Ask&quot;, &quot;Median Price&quot;, &quot;Median Price (x100)&quot;, &quot;Profit if Exercised&quot;, &quot;Profit if Not Exercised&quot;, &quot;Volume&quot;, &quot;Open Interest&quot;]<br>        print(tabulate(table_data, headers=headers, floatfmt=&quot;.2f&quot;, tablefmt=&quot;grid&quot;))<br>    else:<br>        print(&quot;No suitable call options found.&quot;)<br><br>if __name__ == &quot;__main__&quot;:<br>    ticker_symbol = input(&quot;Enter the ticker symbol: &quot;).strip().upper()<br>    main(ticker_symbol)</pre><p>I challenged ChatGPT regarding the criteria provided:</p><p><em>Are you considering all the available greeks, are there some improvements to make? I would also to have an additional column called “Score” with a value between 0 (terrible) and 100 (excellent) that indicates the chance of success and the quality of this contract. Order the results by Score.</em></p><p>It provides me some explanation about its intent:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*MuTWQorjsbhUk5gMSI94uQ.png" /></figure><p>And also its scoring system:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*XqoD3bGKmvcOu0EBL5lTxA.png" /></figure><p>I also asked ChatGPT to adapt the columns a bit to make it more concise. <br>The final output is similar to this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p1dEBXttC_Ej6xAzklzDmg.png" /></figure><pre>import os<br>import json<br>import requests<br>from datetime import datetime, timedelta<br>from tabulate import tabulate<br><br># Constants<br>API_URL_OPTIONS = &quot;https://finnhub.io/api/v1/stock/option-chain&quot;<br>API_URL_QUOTE = &quot;https://finnhub.io/api/v1/quote&quot;<br>API_KEY_FILE = &quot;apikey.txt&quot;<br>DATA_DIR = &quot;options_data&quot;<br>MAX_EXPIRATION_MONTHS = 6<br>TOP_CANDIDATES = 10  # Limit to top 10 candidates<br>DELTA_MIN = 0.40     # Minimum delta threshold<br>DELTA_MAX = 0.70     # Maximum delta threshold<br>IV_MIN = 20          # Minimum implied volatility threshold (in %)<br>OPEN_INTEREST_MIN = 100  # Minimum open interest for liquidity<br>VOLUME_MIN = 100         # Minimum volume for activity<br>STRIKE_PROXIMITY = 0.1  # Maximum percentage difference from current price<br><br># Function to read API key from file<br>def read_api_key():<br>    with open(API_KEY_FILE, &#39;r&#39;) as file:<br>        return file.read().strip()<br><br># Function to get options chain data<br>def get_options_chain(ticker):<br>    api_key = read_api_key()<br>    params = {<br>        &#39;symbol&#39;: ticker,<br>        &#39;token&#39;: api_key<br>    }<br>    response = requests.get(API_URL_OPTIONS, params=params)<br><br>    if response.status_code == 200:<br>        return response.json()<br>    else:<br>        print(f&quot;Error fetching options data: {response.status_code} - {response.text}&quot;)<br>        return None<br><br># Function to get the current market price<br>def get_current_price(ticker):<br>    api_key = read_api_key()<br>    params = {<br>        &#39;symbol&#39;: ticker,<br>        &#39;token&#39;: api_key<br>    }<br>    response = requests.get(API_URL_QUOTE, params=params)<br><br>    if response.status_code == 200:<br>        quote_data = response.json()<br>        return quote_data[&#39;c&#39;]  # Current price<br>    else:<br>        print(f&quot;Error fetching current price: {response.status_code} - {response.text}&quot;)<br>        return None<br><br># Function to save data to a JSON file<br>def save_data(ticker, data):<br>    if not os.path.exists(DATA_DIR):<br>        os.makedirs(DATA_DIR)<br>    <br>    file_path = os.path.join(DATA_DIR, f&quot;{ticker}_options.json&quot;)<br>    with open(file_path, &#39;w&#39;) as json_file:<br>        json.dump(data, json_file)<br>    <br>    print(f&quot;Data saved to {file_path}&quot;)<br><br># Function to check if the file is outdated<br>def is_file_outdated(ticker):<br>    file_path = os.path.join(DATA_DIR, f&quot;{ticker}_options.json&quot;)<br>    if os.path.exists(file_path):<br>        file_mod_time = datetime.fromtimestamp(os.path.getmtime(file_path))<br>        if datetime.now() - file_mod_time &lt; timedelta(hours=4):<br>            return False  # File is not outdated<br>    return True  # File does not exist or is outdated<br><br># Function to calculate score based on Greeks and other parameters<br>def calculate_score(delta, theta, gamma, open_interest, implied_volatility):<br>    # Score calculations based on delta, theta, gamma, open interest, and implied volatility<br>    score_delta = max(0, min((delta - 0.4) / 0.3 * 100, 100) if delta &lt;= 0.7 else 100)<br>    score_theta = max(0, min(theta * 100, 100))  # Assume theta is a positive value<br>    score_gamma = max(0, min((gamma - 0.1) / 0.2 * 100, 100) if gamma &lt;= 0.3 else 100)<br>    score_oi = max(0, min((open_interest - 100) / 900 * 100, 100))<br>    score_iv = max(0, min((implied_volatility - 20) / 80 * 100, 100))<br><br>    # Final score calculation as an average of the individual scores<br>    final_score = (score_delta + score_theta + score_gamma + score_oi + score_iv) / 5<br>    return final_score<br><br># Function to analyze the options chain for covered call strategy<br>def analyze_covered_call(ticker, market_price):<br>    options_data = get_options_chain(ticker)<br>    <br>    if not options_data or &#39;data&#39; not in options_data:<br>        return []<br><br>    calls = []<br>    for option in options_data[&#39;data&#39;]:<br>        expiration_date = option[&#39;expirationDate&#39;]<br>        expiration = datetime.strptime(expiration_date, &quot;%Y-%m-%d&quot;)<br><br>        # Filter for options expiring within the next 6 months<br>        if expiration &lt;= datetime.now() + timedelta(days=MAX_EXPIRATION_MONTHS * 30):<br>            for call in option[&#39;options&#39;][&#39;CALL&#39;]:<br>                strike = call[&#39;strike&#39;]<br>                bid = call[&#39;bid&#39;]<br>                ask = call[&#39;ask&#39;]<br>                delta = call[&#39;delta&#39;]<br>                iv = call[&#39;impliedVolatility&#39;] * 100  # Convert to percentage<br>                open_interest = call[&#39;openInterest&#39;]<br>                volume = call[&#39;volume&#39;]<br>                theta = call[&#39;theta&#39;]  # Assume theta is provided in the data<br>                gamma = call[&#39;gamma&#39;]  # Assume gamma is provided in the data<br>                contract_name = call[&#39;contractName&#39;]  # Get the contract name<br><br>                # Calculate the percentage difference between strike price and market price<br>                price_diff_percentage = abs(strike - market_price) / market_price<br><br>                # Apply filters based on delta, implied volatility, volume, open interest, and strike proximity<br>                if (DELTA_MIN &lt;= delta &lt;= DELTA_MAX and <br>                    iv &gt;= IV_MIN and <br>                    open_interest &gt;= OPEN_INTEREST_MIN and <br>                    volume &gt;= VOLUME_MIN and <br>                    price_diff_percentage &lt;= STRIKE_PROXIMITY):  # Check if the strike is within 10% of market price<br>                    <br>                    # Calculate median price<br>                    median_price = (bid + ask) / 2<br>                    # Calculate profit if exercised<br>                    profit_if_exercised = (median_price * 100) + (strike * 100 - market_price * 100)<br>                    # Calculate profit if not exercised (premium only)<br>                    profit_if_not_exercised = median_price * 100<br><br>                    # Calculate score based on Greeks<br>                    score = calculate_score(delta, theta, gamma, open_interest, iv)<br><br>                    calls.append({<br>                        &#39;contract_name&#39;: contract_name,  # Store the contract name<br>                        &#39;expiration&#39;: expiration,<br>                        &#39;strike&#39;: strike,<br>                        &#39;bid&#39;: bid,<br>                        &#39;ask&#39;: ask,<br>                        &#39;median_price&#39;: median_price,<br>                        &#39;profit_if_exercised&#39;: profit_if_exercised,<br>                        &#39;profit_if_not_exercised&#39;: profit_if_not_exercised,<br>                        &#39;delta&#39;: delta,<br>                        &#39;iv&#39;: iv,<br>                        &#39;open_interest&#39;: open_interest,<br>                        &#39;volume&#39;: volume,<br>                        &#39;theta&#39;: theta,  # Add theta<br>                        &#39;gamma&#39;: gamma,  # Add gamma<br>                        &#39;score&#39;: score   # Add score<br>                    })<br>    <br>    # Sort calls by score and then by maximum profit if exercised<br>    sorted_calls = sorted(calls, key=lambda x: (x[&#39;score&#39;], x[&#39;profit_if_exercised&#39;]), reverse=True)[:TOP_CANDIDATES]<br>    return sorted_calls<br><br># Main function<br>def main(ticker):<br>    if is_file_outdated(ticker):<br>        print(f&quot;Fetching new data for {ticker}...&quot;)<br>        options_data = get_options_chain(ticker)<br>        if options_data:<br>            save_data(ticker, options_data)<br>    else:<br>        print(f&quot;Using cached data for {ticker}.&quot;)<br><br>    # Get current market price<br>    market_price = get_current_price(ticker)<br><br>    if market_price is None:<br>        print(&quot;Could not retrieve current market price. Exiting.&quot;)<br>        return<br><br>    print(f&quot;Current market price of {ticker}: ${market_price:.2f}&quot;)<br><br>    # Analyze options chain<br>    analyzed_calls = analyze_covered_call(ticker, market_price)<br><br>    # Display results in a table<br>    if analyzed_calls:<br>        table_data = []<br>        for call in analyzed_calls:<br>            table_data.append([<br>                call[&#39;contract_name&#39;],              # Contract Name<br>                call[&#39;expiration&#39;].strftime(&#39;%Y-%m-%d&#39;),<br>                call[&#39;strike&#39;],<br>                round(call[&#39;bid&#39;], 2),<br>                round(call[&#39;ask&#39;], 2),<br>                round(call[&#39;median_price&#39;] * 100, 2),  # Median Price (x100)<br>                round(call[&#39;profit_if_exercised&#39;], 2),<br>                round(call[&#39;profit_if_not_exercised&#39;], 2),<br>                call[&#39;volume&#39;],                    # Add volume to the table<br>                call[&#39;open_interest&#39;],              # Add open interest to the table<br>                round(call[&#39;score&#39;], 2)             # Add score to the table<br>            ])<br>        <br>        headers = [&quot;Contract&quot;, &quot;Exp&quot;, &quot;Strike&quot;, &quot;Bid&quot;, &quot;Ask&quot;, &quot;Med. Price&quot;, &quot;P (exercised)&quot;, &quot;P (not exercised)&quot;, &quot;Vol&quot;, &quot;O. Interest&quot;, &quot;Score&quot;]<br>        print(tabulate(table_data, headers=headers, floatfmt=&quot;.2f&quot;, tablefmt=&quot;grid&quot;))<br>    else:<br>        print(&quot;No suitable call options found.&quot;)<br><br>if __name__ == &quot;__main__&quot;:<br>    ticker_symbol = input(&quot;Enter the ticker symbol: &quot;).strip().upper()<br>    main(ticker_symbol)</pre><p><strong>Minor Improvements</strong></p><p>One thing to note about ChatGPT (and other AIs) is that after a while, it may begin to diverge from the original focus. I sensed this was happening when I wanted to introduce new features.</p><p>What I typically do in such cases is start with a fresh prompt. I provide the entire script and simply say, “Please consider this script without explanations; I will give you instructions later.”</p><p>In this instance, we are going to add functionality to export the data to a .csv file so that it can be</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*ruxSGcRPyXLcqHDr1iaaCQ.png" /></figure><p><em>Please add an export to a Excel file at the end. The Excel filename must contain the ticker name. DO NOT touch the rest of the script. It must reuse the same columns.</em></p><p>You may need to install a library (using pip) depending on your environment, and ChatGPT provides instructions for this.</p><p>In the end, this is what we achieved:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*jxcyVxaiihJ8Ia_cY7U_SA.png" /></figure><pre>import os<br>import json<br>import requests<br>import pandas as pd  # Importing pandas for Excel operations<br>from datetime import datetime, timedelta<br>from tabulate import tabulate<br><br># Constants<br>API_URL_OPTIONS = &quot;https://finnhub.io/api/v1/stock/option-chain&quot;<br>API_URL_QUOTE = &quot;https://finnhub.io/api/v1/quote&quot;<br>API_KEY_FILE = &quot;apikey.txt&quot;<br>DATA_DIR = &quot;options_data&quot;<br>MAX_EXPIRATION_MONTHS = 6<br>TOP_CANDIDATES = 10  # Limit to top 10 candidates<br>DELTA_MIN = 0.40     # Minimum delta threshold<br>DELTA_MAX = 0.70     # Maximum delta threshold<br>IV_MIN = 20          # Minimum implied volatility threshold (in %)<br>OPEN_INTEREST_MIN = 100  # Minimum open interest for liquidity<br>VOLUME_MIN = 100         # Minimum volume for activity<br>STRIKE_PROXIMITY = 0.1  # Maximum percentage difference from current price<br><br># Function to read API key from file<br>def read_api_key():<br>    with open(API_KEY_FILE, &#39;r&#39;) as file:<br>        return file.read().strip()<br><br># Function to get options chain data<br>def get_options_chain(ticker):<br>    api_key = read_api_key()<br>    params = {<br>        &#39;symbol&#39;: ticker,<br>        &#39;token&#39;: api_key<br>    }<br>    response = requests.get(API_URL_OPTIONS, params=params)<br><br>    if response.status_code == 200:<br>        return response.json()<br>    else:<br>        print(f&quot;Error fetching options data: {response.status_code} - {response.text}&quot;)<br>        return None<br><br># Function to get the current market price<br>def get_current_price(ticker):<br>    api_key = read_api_key()<br>    params = {<br>        &#39;symbol&#39;: ticker,<br>        &#39;token&#39;: api_key<br>    }<br>    response = requests.get(API_URL_QUOTE, params=params)<br><br>    if response.status_code == 200:<br>        quote_data = response.json()<br>        return quote_data[&#39;c&#39;]  # Current price<br>    else:<br>        print(f&quot;Error fetching current price: {response.status_code} - {response.text}&quot;)<br>        return None<br><br># Function to save data to a JSON file<br>def save_data(ticker, data):<br>    if not os.path.exists(DATA_DIR):<br>        os.makedirs(DATA_DIR)<br>    <br>    file_path = os.path.join(DATA_DIR, f&quot;{ticker}_options.json&quot;)<br>    with open(file_path, &#39;w&#39;) as json_file:<br>        json.dump(data, json_file)<br>    <br>    print(f&quot;Data saved to {file_path}&quot;)<br><br># Function to check if the file is outdated<br>def is_file_outdated(ticker):<br>    file_path = os.path.join(DATA_DIR, f&quot;{ticker}_options.json&quot;)<br>    if os.path.exists(file_path):<br>        file_mod_time = datetime.fromtimestamp(os.path.getmtime(file_path))<br>        if datetime.now() - file_mod_time &lt; timedelta(hours=4):<br>            return False  # File is not outdated<br>    return True  # File does not exist or is outdated<br><br># Function to calculate score based on Greeks and other parameters<br>def calculate_score(delta, theta, gamma, open_interest, implied_volatility):<br>    # Score calculations based on delta, theta, gamma, open interest, and implied volatility<br>    score_delta = max(0, min((delta - 0.4) / 0.3 * 100, 100) if delta &lt;= 0.7 else 100)<br>    score_theta = max(0, min(theta * 100, 100))  # Assume theta is a positive value<br>    score_gamma = max(0, min((gamma - 0.1) / 0.2 * 100, 100) if gamma &lt;= 0.3 else 100)<br>    score_oi = max(0, min((open_interest - 100) / 900 * 100, 100))<br>    score_iv = max(0, min((implied_volatility - 20) / 80 * 100, 100))<br><br>    # Final score calculation as an average of the individual scores<br>    final_score = (score_delta + score_theta + score_gamma + score_oi + score_iv) / 5<br>    return final_score<br><br># Function to analyze the options chain for covered call strategy<br>def analyze_covered_call(options_data, market_price):<br>    if not options_data or &#39;data&#39; not in options_data:<br>        return []<br><br>    calls = []<br>    for option in options_data[&#39;data&#39;]:<br>        expiration_date = option[&#39;expirationDate&#39;]<br>        expiration = datetime.strptime(expiration_date, &quot;%Y-%m-%d&quot;)<br><br>        # Filter for options expiring within the next 6 months<br>        if expiration &lt;= datetime.now() + timedelta(days=MAX_EXPIRATION_MONTHS * 30):<br>            for call in option[&#39;options&#39;][&#39;CALL&#39;]:<br>                strike = call[&#39;strike&#39;]<br>                bid = call[&#39;bid&#39;]<br>                ask = call[&#39;ask&#39;]<br>                delta = call[&#39;delta&#39;]<br>                iv = call[&#39;impliedVolatility&#39;] * 100  # Convert to percentage<br>                open_interest = call[&#39;openInterest&#39;]<br>                volume = call[&#39;volume&#39;]<br>                theta = call[&#39;theta&#39;]  # Assume theta is provided in the data<br>                gamma = call[&#39;gamma&#39;]  # Assume gamma is provided in the data<br>                contract_name = call[&#39;contractName&#39;]  # Get the contract name<br><br>                # Calculate the percentage difference between strike price and market price<br>                price_diff_percentage = abs(strike - market_price) / market_price<br><br>                # Apply filters based on delta, implied volatility, volume, open interest, and strike proximity<br>                if (DELTA_MIN &lt;= delta &lt;= DELTA_MAX and <br>                    iv &gt;= IV_MIN and <br>                    open_interest &gt;= OPEN_INTEREST_MIN and <br>                    volume &gt;= VOLUME_MIN and <br>                    price_diff_percentage &lt;= STRIKE_PROXIMITY):  # Check if the strike is within 10% of market price<br>                    <br>                    # Calculate median price<br>                    median_price = (bid + ask) / 2<br>                    # Calculate profit if exercised<br>                    profit_if_exercised = (median_price * 100) + (strike * 100 - market_price * 100)<br>                    # Calculate profit if not exercised (premium only)<br>                    profit_if_not_exercised = median_price * 100<br><br>                    # Calculate score based on Greeks<br>                    score = calculate_score(delta, theta, gamma, open_interest, iv)<br><br>                    calls.append({<br>                        &#39;contract_name&#39;: contract_name,  # Store the contract name<br>                        &#39;expiration&#39;: expiration,<br>                        &#39;strike&#39;: strike,<br>                        &#39;bid&#39;: bid,<br>                        &#39;ask&#39;: ask,<br>                        &#39;median_price&#39;: median_price,<br>                        &#39;profit_if_exercised&#39;: profit_if_exercised,<br>                        &#39;profit_if_not_exercised&#39;: profit_if_not_exercised,<br>                        &#39;delta&#39;: delta,<br>                        &#39;iv&#39;: iv,<br>                        &#39;open_interest&#39;: open_interest,<br>                        &#39;volume&#39;: volume,<br>                        &#39;theta&#39;: theta,  # Add theta<br>                        &#39;gamma&#39;: gamma,  # Add gamma<br>                        &#39;score&#39;: score   # Add score<br>                    })<br>    <br>    # Sort calls by score and then by maximum profit if exercised<br>    sorted_calls = sorted(calls, key=lambda x: (x[&#39;score&#39;], x[&#39;profit_if_exercised&#39;]), reverse=True)[:TOP_CANDIDATES]<br>    return sorted_calls<br><br># Function to export analyzed data to Excel<br>def export_to_excel(ticker, analyzed_calls):<br>    excel_file_path = os.path.join(DATA_DIR, f&quot;{ticker}_options.xlsx&quot;)<br>    <br>    # Create a DataFrame from the analyzed calls<br>    df = pd.DataFrame([{<br>        &quot;Contract&quot;: call[&#39;contract_name&#39;],<br>        &quot;Exp&quot;: call[&#39;expiration&#39;].strftime(&#39;%Y-%m-%d&#39;),<br>        &quot;Strike&quot;: call[&#39;strike&#39;],<br>        &quot;Bid&quot;: round(call[&#39;bid&#39;], 2),<br>        &quot;Ask&quot;: round(call[&#39;ask&#39;], 2),<br>        &quot;Med. Price&quot;: round(call[&#39;median_price&#39;] * 100, 2),  # Median Price (x100)<br>        &quot;P (exercised)&quot;: round(call[&#39;profit_if_exercised&#39;], 2),<br>        &quot;P (not exercised)&quot;: round(call[&#39;profit_if_not_exercised&#39;], 2),<br>        &quot;Vol&quot;: call[&#39;volume&#39;],<br>        &quot;O. Interest&quot;: call[&#39;open_interest&#39;],<br>        &quot;Score&quot;: round(call[&#39;score&#39;], 2)<br>    } for call in analyzed_calls])<br>    <br>    # Save the DataFrame to an Excel file<br>    df.to_excel(excel_file_path, index=False)<br>    print(f&quot;Data exported to {excel_file_path}&quot;)<br><br># Main function<br>def main(ticker):<br>    options_data = None<br>    <br>    if is_file_outdated(ticker):<br>        print(f&quot;Fetching new data for {ticker}...&quot;)<br>        options_data = get_options_chain(ticker)<br>        if options_data:<br>            save_data(ticker, options_data)<br>    else:<br>        print(f&quot;Using cached data for {ticker}.&quot;)<br>        # Load cached data from the file<br>        file_path = os.path.join(DATA_DIR, f&quot;{ticker}_options.json&quot;)<br>        with open(file_path, &#39;r&#39;) as json_file:<br>            options_data = json.load(json_file)<br><br>    # Get current market price<br>    market_price = get_current_price(ticker)<br><br>    if market_price is None:<br>        print(&quot;Could not retrieve current market price. Exiting.&quot;)<br>        return<br><br>    print(f&quot;Current market price of {ticker}: ${market_price:.2f}&quot;)<br><br>    # Analyze options chain<br>    analyzed_calls = analyze_covered_call(options_data, market_price)<br><br>    # Display results in a table<br>    if analyzed_calls:<br>        table_data = []<br>        for call in analyzed_calls:<br>            table_data.append([<br>                call[&#39;contract_name&#39;],              # Contract Name<br>                call[&#39;expiration&#39;].strftime(&#39;%Y-%m-%d&#39;),<br>                call[&#39;strike&#39;],<br>                round(call[&#39;bid&#39;], 2),<br>                round(call[&#39;ask&#39;], 2),<br>                round(call[&#39;median_price&#39;] * 100, 2),  # Median Price (x100)<br>                round(call[&#39;profit_if_exercised&#39;], 2),<br>                round(call[&#39;profit_if_not_exercised&#39;], 2),<br>                call[&#39;volume&#39;],                    # Add volume to the table<br>                call[&#39;open_interest&#39;],              # Add open interest to the table<br>                round(call[&#39;score&#39;], 2)             # Add score to the table<br>            ])<br>        <br>        headers = [&quot;Contract&quot;, &quot;Exp&quot;, &quot;Strike&quot;, &quot;Bid&quot;, &quot;Ask&quot;, &quot;Med. Price&quot;, &quot;P (exercised)&quot;, &quot;P (not exercised)&quot;, &quot;Vol&quot;, &quot;O. Interest&quot;, &quot;Score&quot;]<br>        print(tabulate(table_data, headers=headers, floatfmt=&quot;.2f&quot;, tablefmt=&quot;grid&quot;))<br><br>        # Export to Excel<br>        export_to_excel(ticker, analyzed_calls)  # Call the export function<br>    else:<br>        print(&quot;No suitable call options found.&quot;)<br><br>if __name__ == &quot;__main__&quot;:<br>    ticker_symbol = input(&quot;Enter the ticker symbol: &quot;).strip().upper()<br>    main(ticker_symbol)</pre><p><strong>EDIT</strong>: I noticed there was a small bug in the way the caching was done in the first version proposed by ChatGPT, it was not reloading the JSON containing options chain properly. As always, double-check what it is doing, this is where programming skills are still required.</p><p><strong>Final Words</strong></p><p>The final version of our script generates a list of candidates, highlighting those with high scores, particularly for contracts that are close to expiration. We also notice that it proposed some contracts that are slightly in-the-money (ITM), yet not too deep to mitigate potential losses if we need to sell the shares.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SDd08htyaLJEz8WnpGxr6g.png" /></figure><p>By harnessing the capabilities of this Python tool, traders can streamline their analysis and identify the most suitable covered call opportunities with greater efficiency. The tool automates the process of evaluating critical parameters, such as delta, implied volatility, and open interest, enabling users to focus on strategy rather than data collection. As you engage with this resource, remember that while it simplifies the mechanics of option selection, successful trading ultimately hinges on your ability to interpret market signals and make informed decisions.</p><p>With the right tools and insights at your disposal, you can effectively navigate the complexities of the options market, maximizing your potential for income generation while mitigating risks associated with covered calls.</p><p>I hope you have enjoyed this serie of articles. Happy trading!</p><p><strong>Bonus: you can find the PDFs of these articles, the final script as well as additional documentation about covered calls on my Github repository here → </strong><a href="https://github.com/K4096K"><strong>https://github.com/K4096K</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3521ac8302d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-investors-handbook/unlocking-the-power-of-covered-calls-with-chatgpt-part-3-e3521ac8302d">Unlocking the Power of Covered Calls with ChatGPT — Part 3</a> was originally published in <a href="https://medium.com/the-investors-handbook">Investor’s Handbook</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unlocking the Power of Covered Calls with ChatGPT — Part 2]]></title>
            <link>https://medium.com/the-investors-handbook/unlocking-the-power-of-covered-calls-with-chatgpt-part-2-0648e98a72e7?source=rss-c059fd00a0db------2</link>
            <guid isPermaLink="false">https://medium.com/p/0648e98a72e7</guid>
            <category><![CDATA[options]]></category>
            <category><![CDATA[covered-call]]></category>
            <category><![CDATA[options-trading]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[options-greeks]]></category>
            <dc:creator><![CDATA[K4096K]]></dc:creator>
            <pubDate>Tue, 15 Oct 2024 21:26:14 GMT</pubDate>
            <atom:updated>2024-10-23T13:23:03.003Z</atom:updated>
            <content:encoded><![CDATA[<h3>Unlocking the Power of Covered Calls with ChatGPT — Part 2</h3><p>For experienced traders, the <strong>covered call strategy</strong> offers a powerful way to generate additional income while managing risk. This strategy involves owning a stock and selling call options on it, allowing you to benefit from both potential capital appreciation and option premiums. However, selecting the optimal strike price, expiration date, and timing can be challenging, especially in today’s fast-paced markets with numerous variables to consider.</p><p>In <a href="https://medium.com/the-investors-handbook/unlocking-the-power-of-covered-calls-with-chatgpt-part-1-7734deab5421">Part 1</a>, we introduced the covered call strategy and provided guidelines on when it’s appropriate and when it should be avoided. We used a real example of a stock of the US market (Pfizer). In this article, we’ll take a deeper dive, exploring more advanced parameters around options with the help of <strong>ChatGPT</strong> to refine decision-making.</p><p>In<a href="https://medium.com/@k4096k/unlocking-the-power-of-covered-calls-with-chatgpt-part-3-e3521ac8302d"> <strong>Part 3</strong></a>, we’ll go even further by building a simple tool in <strong>Python </strong>that generates option picks for a given ticker based on the criteria we’ve discussed, making it easier to implement the strategies outlined here.</p><p><strong>General Guidelines</strong></p><p>Before going further, let’s recap some general guidelines about covered calls that we mentionned in the first article.</p><ol><li><strong>Capital</strong>: The strategy requires that you have sufficient capital to acquire 100 shares of the stock. This can be an issue and you may be tempted to buy stocks trading at a lower price to fit your financial situation but this may go against the next rule.</li><li><strong>Stock Ownership</strong>: Only use the covered call strategy if you already own (or are comfortable owning) the underlying stock. The strategy works best if you plan to hold the stock for a while, regardless of short-term price fluctuations. Do not buy bad stocks or illiquid assets.</li><li><strong>Strike Price Selection</strong>: Choose a strike price that aligns with your goals. If you’re willing to sell the stock, pick a strike price closer to the current stock price (this is what we did with the $30 strike example). If you prefer to hold the stock, choose a higher strike price to allow for more potential stock appreciation.</li><li><strong>Expiration Date</strong>: Shorter-term options (weekly or monthly) provide more frequent opportunities to generate income, but may result in lower premiums. Longer-term options provide higher premiums but lock you into the strategy for a longer period.</li><li><strong>Market Outlook</strong>: The strategy works well in neutral or slightly bullish markets. If you believe the stock will move sideways or have only modest gains, selling a covered call can provide income through the premium.</li><li><strong>Risk Management</strong>: The premium earned provides some downside protection, but your risk is still tied to the stock’s price. If the stock drops significantly, the premium won’t fully offset those losses.</li><li><strong>Profit Cap</strong>: Understand that a covered call limits your potential gains. If the stock price rises sharply, your upside is capped at the strike price, and you must sell the stock at that price.</li></ol><p><strong>Addressing the Capital Issue</strong></p><p>We will not be addressing all of these points in this article. However, the capital requirement can be managed by using options on lower-priced, high-quality stocks. Another approach is to use ETFs, which typically trade at lower prices than individual stocks, though it’s important to note that not all ETFs offer options or have sufficient liquidity.</p><p>Some products are also made available for traders with a smaller capital, for example the “Cboe Mini-SPX Index option contract” represents 1/10 of a normal S&amp;P 500 contract but still represents a beefy amount of $58k for the shares themselves if you go for a covered call (SPY is trading right now at $5842). Cboe introduced an even smaller piece called the Nano which is 1/100 of the S&amp;P (more info <a href="https://www.cboe.com/insights/posts/making-sense-of-nano-index-options-what-to-know-before-you-trade/">here</a>) making it suitable for most investors.</p><p>Also note that indexes like S&amp;P have european-style options (if exercised, this will be only at expiration) while individual stocks are american-style (can be exercised at any time before exp.)</p><p>Additionally, there’s a strategy known as the “Poor Man’s Covered Call,” which involves buying two call options with different expiration dates, but we won’t cover that strategy here.</p><p>The remainder of the article will focus on optimizing the strike price, selecting the right expiration date, and gaining insight into the associated risks. To do this, we will consider a set of factors known as “the Greeks,” which influence the price and behavior of options.</p><p>In the first part of the article, we used Pfizer stock for our examples. This time, we’ll focus on another stock, Disney (DIS).</p><p><strong>Understanding the Greeks</strong></p><p>The “greeks” can be intimidating at first because many articles are explaining them in a very mathematical ways with lot of formulas. We will try to make it simpler here. The name “Greeks” comes from the fact that they correspond to the greek letters present in the formulas that describe their behavior.</p><p>Each Greek measures sensitivity to a specific factor, like changes in the underlying asset’s price, volatility, time, and interest rates. Let’s list the most important of them:</p><ol><li><strong>Delta (Δ)</strong> — <strong>Price Sensitivity To Underlying Security</strong></li><li><strong>Gamma (Γ)</strong> — <strong>Rate of Change of Delta</strong></li><li><strong>Theta (Θ)</strong> — <strong>Time Decay</strong></li><li><strong>Vega (ν)</strong> — <strong>Sensitivity to Volatility</strong></li></ol><p>There is also rho (sensitivity to interest rates) and other greeks said to be “minors”, we won’t cover them here.</p><p>Before going further, we pay a look at the options chain of our Disney stock (DIS) as provided by the Nasdaq website. The options chain on Yahoo that we used in the first part does not provide a quick access to greeks. At the time this article is written (15th October 2024), DIS trades at exactly <strong>$94.38.</strong> I set the expiration date on 1st November 2024, in two weeks. We will refer to these different entries shortly later. <br><a href="https://www.nasdaq.com/market-activity/etf/schd/option-chain">https://www.nasdaq.com/market-activity/etf/dis/option-chain</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*vj8OHwQ3bYiz5ATgWuxVKQ.png" /></figure><p>As a reminder, we will frequently use the concepts of:</p><ul><li><strong>in-the-money</strong> (ITM): the call could be exercised (market price is above strike)</li><li><strong>out-of-the-money </strong>(OTM): the call would not be exercised (market price is below strike)</li><li><strong>at-the-money (</strong>ATM): option strike corresponds to current market price</li></ul><p>This only applies of course if we did not reach the expiration yet.</p><p>On top of this, there are two concepts that are frequently used with options:</p><ul><li><strong>intrinsic value</strong>: the real, tangible value of an option based on the current price of the underlying asset relative to the option’s strike price. It shows how much profit you could make if you exercised the option right now.</li><li><strong>extrinsic value</strong>: the portion of an option’s price that exceeds its intrinsic value. It reflects the additional value that traders are willing to pay for the potential of the option to gain value in the future. It decreases as time passes.</li></ul><p><strong>Delta (Δ)<br></strong>The delta represents how much the price of an option will change if the underlying changes. For example, if the stock moves by $1, how much will this affect the price of a call option? <strong>If the delta is 0.3, then the option will move by $0.3 when the stock moves by $1.</strong></p><p>Let’s illustrate this with real examples. In the options chain of DIS, we can see some entries with a blue background. Those correspond to the options that are in-the-money (because their strike is below the current trade level of SCHD, at $94.38). The options with a white background are out-of-the-money, because their strike is above the market price of the stock.</p><p>Let’s look at real examples to clarify this. In DIS’s options chain, you’ll notice some entries highlighted with a blue background. These are the <strong>in-the-money</strong> options, meaning their strike prices are below DIS’s current price of $94.38. The options with a white background are <strong>out-of-the-money</strong>, as their strike prices are above the current market price of the stock.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*EKYK_wNNpUKWAbPFH_13bA.png" /><figcaption>Extract of DIS options chain for calls — expiration 1st Nov 24</figcaption></figure><p>We first pick an OTM contract, and we click on its strike price of $95.00. We get a detailed page with the bid, ask, volume, etc. but also a section with the greeks for that particular contract. <strong>The delta is at 0.473, meaning that a $1 move on the ETF will result into $0.473 move on the option price.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/679/1*0ZQBdrAzETqlw6mJ8PhwFw.png" /></figure><p>Now we repeat the same operation but this times, we choose an ITM entry, with the strike at 94. We immediately see that the delta is much higher, about 0.55.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*dmlWQ2GDnfNdRaJ5wlGIZw.png" /></figure><p>We can plot all the deltas for each strike to see how the delta evolves. To make this easier, we will use OptionCharts website: <a href="https://optioncharts.io/options/DIS/greeks?option_type=call&amp;expiration_dates=2024-11-01:w&amp;greek_type=delta">https://optioncharts.io/options/DIS/greeks?option_type=call&amp;expiration_dates=2024-11-01:w&amp;greek_type=delta</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*ZaT03hPm4IiTqpDBOQF2QQ.png" /></figure><p>Don’t be intimidated by the chart or the mathematical complexity it might suggest. The first thing to note is that delta ranges between 1.0 and 0.0. On the left side of the chart, we are in the <strong>in-the-money (ITM)</strong> zone, while on the right, we enter the <strong>out-of-the-money (OTM)</strong> zone. The middle represents the current market price of <strong>$94.38</strong>.</p><p>You’ll notice the curve starts off relatively flat, then steepens sharply as it approaches the current price, crossing at <strong>0.5 delta</strong> — indicating an at-the-money (ATM) option. After that, the curve flattens out again, reflecting how delta approaches <strong>1.0 in ITM</strong> and <strong>0.0 in OTM</strong> scenarios.</p><p>What does this mean? When the option’s strike price is close to the current market price, for each $1 move in the underlying asset, there is about a <strong>50% chance</strong> that the option will move in-the-money (ITM), increasing its price, or move out-of-the-money (OTM), decreasing its price. This is why delta is around <strong>0.5</strong> near the market price — it reflects that balanced probability.</p><p>On the other hand, when the option’s strike price is far from the current market price, a move in the underlying stock is <strong>less likely to shift</strong> the option from OTM to ITM or vice versa. The further away the strike price is, the less responsive the option’s price becomes to small movements in the underlying asset. This is why, when an option is “deep ITM” or “deep OTM,” the delta is very close to <strong>1.0</strong> or <strong>0.0</strong>, respectively.</p><p>For example, in the chart above, if Disney (DIS) were trading at <strong>$120</strong> near the end of the contract (say, the last day of October), it would be very unlikely that a $1 move would bring the option back significantly into the ITM zone. As a result, the option’s price wouldn’t change much, and the delta would be close to <strong>0.0</strong>.</p><p>In summary,<strong> the delta can be considered as a probably of success or failure</strong> for the ITM/OTM criterias.</p><ul><li><strong>ATM delta ≈ 0.5</strong>: The probability of the option expiring ITM is close to 50%, so the option is moderately sensitive to changes in the underlying price.</li><li><strong>ITM delta → 1.0</strong>: The option is almost certain to end ITM, so its price moves almost directly with the underlying.</li><li><strong>OTM delta → 0.0</strong>: The option is unlikely to become ITM, so its price barely moves with changes in the underlying.</li></ul><p><strong>Gamma (Γ)<br></strong>Gamma can be a bit tricky to grasp because it measures how quickly delta changes. A helpful analogy is to think of delta as the speed of a car and gamma as the acceleration. Two cars might both be moving at 20 meters per second (the same delta), but their acceleration differs. After one second, the first car’s speed might increase to 30 meters per second, while the second accelerates faster and reaches 40 meters per second. This difference in acceleration represents the role gamma plays in how fast delta changes.</p><p>Now, let’s illustrate this with the delta curve for Disney (DIS) options on two different expiration dates: <strong>November 1st (17 days until expiration)</strong> and <strong>December 20th, 2024 (66 days until expiration)</strong>. As you’ll notice, the curve for the shorter-term option is steeper, showing that gamma is higher for options closer to expiration. This means delta changes more rapidly with small price movements when the option is nearing its expiration date.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M9_gnMYU5xNq9XXJS0uxAA.png" /><figcaption>Delta curves for a short and longer-expiry contracts</figcaption></figure><p>Imagine a car traveling along a road that represents the delta curve. When it crosses the market price (the vertical line), its delta is 0.5, which you can think of as its velocity. Now, if you wait for the car to reach a delta of 0.25, which car will arrive first? Clearly, the car on the steeper slope is accelerating much faster and will reach 0.25 before the other car. On the right side, the delta of 0.25 is only achieved when the strike price is around 105.</p><p>This illustrates the concept of gamma:</p><ul><li>A <strong>high gamma</strong> indicates that delta will change rapidly, meaning the option is more sensitive to movements in the underlying stock.</li><li>A <strong>low gamma</strong> suggests that delta changes more slowly, making the option price less responsive to stock movements.</li></ul><p>Gamma is a crucial parameter for risk management because it is closely tied to both <strong>volatility</strong> and <strong>expiration</strong>. As expiration approaches, gamma increases, particularly around the current market price. This is important because even a small move in the stock can cause the option to shift between in-the-money (ITM) and out-of-the-money (OTM) status, making the option more “reactive.”</p><p>In contrast, if your option has six months until expiration, it will have lower reactivity. A move in the current market price may not significantly impact the option’s price, as such moves are often just temporary “noise.”</p><p><strong>Mathematical note:</strong> The shape of the gamma curve resembles a bell-shaped curve, similar to a Gaussian distribution. As expiration approaches, the curve becomes narrower, indicating that the option’s sensitivity to underlying price changes is heightened.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*aON2qevuBzV7o_WepuoQUw.png" /></figure><p><strong>Theta (Θ)<br></strong>This greek measures how much an option’s price decreases as it gets closer to its expiration date, reflecting the concept of time decay. It shows how much value an option loses each day, assuming everything else stays the same.</p><p>For most options, theta is negative, meaning that as time passes, the option becomes less valuable because there’s less time for the underlying asset to move in a way that would benefit the option holder. This time decay speeds up as the expiration date approaches, especially for options that are close to being at-the-money.</p><p>In the chart below, you can see how the option’s price is evolving if it’s either ITM, ATM or OTM. The ATM (in green) option is close to the market price so when you are getting closer to its expiration, its value significantly decreases in a steep way because you may finally not get any benefit from using an option, you can just buy the shares on the market. However, it’s important to note that while the option may lose value rapidly, it could still hold its value if the underlying stock moves favorably.</p><p>For the ITM, the price follows a similar shape but less marked in the sense that as you are ITM, the option is more valuable and may still be useful for a trading strategy: it has a mix of intrinsic and extrinsic value.</p><p>For the OTM, the opposite of the ATM happens. The value of the option is decreasing significantly because an OTM is mostly extrinsic (you are expecting it to gain value but as such, if you exercised it, you would get nothing), it does not have an intrinsic value. However as you get close the expiration date, this decay is less significant because here again it could be part of a short-term strategy depending how deep OTM it is.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/0*C55G94O67oH8xBo2" /></figure><p><strong>Vega (ν)<br></strong>This reek that measures an option&#39;s sensitivity to changes in implied volatility rather than changes in the price of the underlying asset, as delta does. It is typically expressed as a positive number for both call and put options. For instance, if a call option has a vega of 0.10, this means that if implied volatility increases by 1%, the option&#39;s price is expected to rise by $0.10.</p><p>In essence, higher volatility (which indicates a &quot;riskier&quot; asset) leads to more expensive options. This is because increased volatility enhances the potential for significant price swings, thereby increasing the likelihood that the option will be profitable at expiration.</p><p>Vega is generally highest for at-the-money (ATM) options and decreases for in-the-money (ITM) and out-of-the-money (OTM) options. Additionally, vega tends to decline as expiration approaches. Its distribution resembles a bell curve, similar to gamma, with the peak diminishing as the expiration date draws near.</p><h3><strong>Asking the AI to shape a Strategy</strong></h3><p>Now that we have a basic understanding of the most important greeks, we can finally ask ChatGPT to provide us some hints to shape our covered call strategy.</p><p><strong>Full chat can be found here → </strong><a href="https://github.com/K4096K/covered_calls/blob/a580da55b7331b86b09f3d24b8823d9c61501ec9/Unlocking%20the%20Power%20of%20Covered%20Calls%20with%20ChatGPT%20%E2%80%94%20Part%202%20-%20conversation.md"><strong>Conversation</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*Uo1dI0rkjLr-o2UZ48Ut2g.png" /><figcaption>Initial prompt</figcaption></figure><p>Extract of the first answer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/1*iTWI00sF72B9n0x1UXgfNA.png" /></figure><p>Let’s analyze the strategy for selecting call options more closely. While it clearly avoids very deep in-the-money (ITM) or out-of-the-money (OTM) calls, it does not strictly adhere to the conventional focus on OTM options. Typically, a covered call strategy would favor calls with a delta between <strong>0.30 and 0.50</strong>. However, allowing for calls with a delta of up to <strong>0.60</strong> provides flexibility, particularly if the investor’s intent is to potentially sell the underlying stock.</p><p>For gamma, it aims at being conservative and took the same path for theta and vega by avoiding highly-volatile options.</p><p>At the end of the discussion, the bot invited us to try with a ticker, so let’s check with Disney:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/302/1*QqUe8QNCEXEsnZK-32UvaA.png" /></figure><p>The bot provides “up-to-date” market data, which honestly surprised me at first. However, when I double-checked the values for the first strike at $95, I found them to be inaccurate. I then asked the bot for additional information, and it returned data from the previous day. So, it’s essential to be cautious with the market data provided, especially for options with short-term expirations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*SckXZOgQMMp3iStp3uDapA.png" /><figcaption>Answer provided by ChatGPT (after US close) on 15th October 2024</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*4sdUziywfFcO0OyICdjiuA.png" /><figcaption>Actual data from Nasdaq for the $95 call</figcaption></figure><p>I then asked the bot to apply its strategy on a set of “well-known US tickers”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*2es5O-GwEXc3bTPHqNsdQg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*djupEe8CjeCcRza1jo203A.png" /></figure><p>I wanted to push the AI further by asking it to quantify the “quality” or “risk” of each of these proposals.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*cwGkNa6IHPf5NBtupssoaQ.png" /></figure><p>It generated the following formula, which appears to assign significant weight to delta, while being primarily countered by gamma. When I inquired about the source of this formula, the bot was unable to provide a clear reference. I suspect it may have been derived from concepts found in advanced options literature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*KR4RPqdXxjStelnl_hImag.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*YWdydfcywjAqB94JnECXpw.png" /></figure><p>About the weights being used:</p><p><em>The assigned weights in the formula were designed to emphasize the Greeks’ relative importance in a covered call strategy, reflecting the critical roles of Delta and Theta in particular. While Gamma is important, especially regarding risk management, and Vega offers insights into premium pricing, they play a slightly less direct role in assessing the “rate of success” for this specific strategy.</em></p><p>In the 3rd article, we will go even further with ChatGPT acting like our custom quant engineer.</p><p><strong>Addenum — A note about liquidity</strong></p><p>I mentioned earlier that you could use options on ETFs but you have to consider their liquidity. Here I picked the options chain for the <a href="https://www.schwabassetmanagement.com/products/schd">Schwab U.S. Dividend Equity ETF</a> with an expiration in 30 days. If you look at the “volume” column, you will see that some strikes do not have any volume. “Open Interest” is an indication of the number of contracts that are “ongoing”, that are yet to be settled or closed. The range between the strikes of $24.00 and $25.33 is virtually dead.<br>Moreover if you look at the first strike at 21.67, you will see a huge spread between the Bid and the Ask, indicating a lower liquidity and less frequent trading (shown by the small open interest of only 3). Those are factors to consider when you want to go into a covered call on a particular asset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*vt0l-JB7afJpCjs0NaDf4Q.png" /></figure><p>Now if you look at a well-known stock, Apple, the situation is totally different with a very liquid options market, again on a 30 days expiration. Spread is thin and volume is significant (obviously smaller in deep ITM or deep OTM entries) with a lot of open interest.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*eQ1pHVt1k8mLE05cU9YFYQ.png" /></figure><h3><strong>Next Part….</strong></h3><p>The proposal by ChatGPT looked promising. In <a href="https://medium.com/@k4096k/unlocking-the-power-of-covered-calls-with-chatgpt-part-3-e3521ac8302d"><strong>Part 3</strong></a>, we’ll go even further by building a simple tool in <strong>Python</strong> that generates option picks for a given ticker based on the criterias we’ve discussed, making it easier to implement the strategies outlined here.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0648e98a72e7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-investors-handbook/unlocking-the-power-of-covered-calls-with-chatgpt-part-2-0648e98a72e7">Unlocking the Power of Covered Calls with ChatGPT — Part 2</a> was originally published in <a href="https://medium.com/the-investors-handbook">Investor’s Handbook</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unlocking the Power of Covered Calls with ChatGPT — Part 1]]></title>
            <link>https://medium.com/the-investors-handbook/unlocking-the-power-of-covered-calls-with-chatgpt-part-1-7734deab5421?source=rss-c059fd00a0db------2</link>
            <guid isPermaLink="false">https://medium.com/p/7734deab5421</guid>
            <category><![CDATA[covered-call-writing]]></category>
            <category><![CDATA[investment]]></category>
            <category><![CDATA[options]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[stocks]]></category>
            <dc:creator><![CDATA[K4096K]]></dc:creator>
            <pubDate>Sun, 13 Oct 2024 20:36:21 GMT</pubDate>
            <atom:updated>2024-10-22T21:00:49.626Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Unlocking the Power of Covered Calls with ChatGPT — Part 1</strong></h3><p>For seasoned traders familiar with options, the <strong>covered call</strong> strategy is a powerful way to generate additional income while managing risk. It combines owning a stock and selling call options, allowing you to profit from both capital appreciation and option premiums. However, choosing the right strike price, expiration date, and timing can be challenging — especially with so many variables to consider in today’s fast-moving markets.</p><p>While we won’t be covering the fundamentals of stocks and options in this article, we’ll assume you have a basic understanding of market mechanics and option terminology. This will allow us to focus on more advanced concepts, such as optimizing a covered call strategy through data-driven insights.</p><p>In parts 2 and 3 — We’ll dive deep into how you can leverage ChatGPT to streamline the process of selecting the parameters for a covered call strategy. We’ll explore how AI can help analyze stock volatility, option premiums, and market conditions in real time. Then, we’ll take it a step further by building a simple tool in Python to automatically identify the most promising entries in the option chain for a given ticker.</p><p>By the end, you’ll have a smarter, more efficient approach to covered calls that puts technology to work for you.</p><p>For simplification reason in this article, I omit the commission and transaction fees that vary between brokers but are supposed to be negligible.</p><p><strong>Normal Long Stock Position</strong></p><p>Before diving into the definition of a covered call, let’s first set the context for the examples we’ll use throughout this article. Suppose we want to invest in <strong>Pfizer stock (PFE)</strong>, which, as of October 12, 2024, is priced at <strong>$29.16</strong>. For simplicity, we’ll round it to <strong>$29</strong> in our calculations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PgD4gWnEu7yBKWvakz6eWg.png" /></figure><p>The first thing we notice is that Pfizer has been trading sideways for several months, with resistance around the <strong>$30–31</strong> range and support in the <strong>$27–28</strong> range. With the current price at <strong>$29</strong>, the stock is sitting near the middle of this range, which presents an interesting setup, as we’ll explore later.</p><p>Imagine now that we simply want to buy the stock at the current price of $29 and hold it with an horizon of time of several weeks or months. Different scenarios may unfold:</p><ul><li><strong>Neutral</strong>: The stock remains relatively flat, oscillating around the <strong>$29</strong> level.</li><li><strong>Weakly Bullish</strong>: The stock experiences a moderate rise, reaching the upper resistance zone of <strong>$30–31 </strong>but failing to breakout.</li><li><strong>Bullish</strong>: The stock rises sharply, breaking through to new levels (e.g., <strong>$33</strong>).</li><li><strong>Weakly Bearish</strong>: The stock declines slightly, approaching the lower support zone of <strong>$27–28</strong> but holding up.</li><li><strong>Bearish</strong>: The stock drops significantly, closing below its recent trading range (e.g., <strong>$25</strong>).</li></ul><p>We can plot a chart to show how our profit/loss is evolving after we bought the stock at $29. Note that we are holding it, so this P/L is virtual. As an example, if the stock reaches $33 on the horizontal axis, our profit will be $4 per share (vertical axis). The chart is limited to the range of $24–34 for the illustration but obviously the stock could in theory crash to 0$ (meaning a max loss of 29$ per share) or sky rocket on the opposite side.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*ou32v85lx1H4Ss7dJoFPnA.png" /></figure><p><strong>Reminder about Call Options</strong></p><p>A little reminder about options before going further.</p><p>A <strong>call option</strong> is a financial contract that grants you the right (but not the obligation) to buy a specific stock at a predetermined price, known as the <strong>strike price</strong>, before a specified date, referred to as the <strong>expiration date</strong>. Each call option typically covers 100 shares of the underlying stock. This means that if you hold a call option and decide to exercise it (before the expiration), you will have the right to purchase 100 shares at the strike price. However, you are not required to do so.</p><p>When you exercise your call option, the seller of the contract is obligated to sell you the 100 shares at the agreed-upon strike price.</p><p>It’s important to note that purchasing a call option is not free. To acquire this right, you must pay the seller a fee known as the <strong>premium</strong>. This premium compensates the seller for granting you the option to buy the stock at the strike price.</p><p>Investors typically buy call options when they have a <strong>bullish outlook</strong> on the stock, meaning they anticipate that the stock price will rise. If the stock does increase in value, the call option can become profitable.</p><p>Pfizer options, like most stock options traded on U.S. exchanges, are <strong>American-style options</strong>. This means they can be exercised at any time before the expiration date. In contrast, <strong>European-style options</strong> can only be exercised on the expiration date itself. American-style options provide more flexibility for the option holder, allowing them to take action (like exercising the option) whenever it becomes profitable before expiration.</p><p>In this series of articles,<strong> I will often simplify the analysis</strong> by concentrating on whether an option is exercised at expiration. However, it’s important to note that options can also be exercised before the expiration date if the necessary conditions are met.</p><p><strong>Call on PFE</strong></p><p>Suppose you buy a call option for Pfizer (PFE) stock, which is currently trading at $29. You select an option with a strike price of $27 and an expiration date set for two months from now. At the time of purchase, the call option is trading at $2.10 per share, meaning the option, which covers 100 shares, will cost you $210 in total.</p><p>By purchasing this option, you gain the right to buy 100 shares of Pfizer at $27 each within the two-month period. However, if you do not exercise your option before the expiration date, you will lose that right and forfeit the $210 you paid for the option.</p><p>Now, let’s assume that PFE rises to $31 the day before the expiration date. The option is said to be “in the money” because as you will see now, you are ending up with a benefit.</p><p>You decide to exercise your call option. The seller is obligated to sell you the 100 shares at the strike price of $27. In this scenario, those shares are currently worth $3,100 on the market (100 shares x $31).</p><p>You have two choices:</p><ol><li><strong>Hold the shares</strong>, anticipating that PFE will continue to rise.</li><li><strong>Sell the shares immediately</strong>, resulting in a profit of $3,100 (market value) — $2,700 (total cost at strike price) = $400.</li></ol><p>However, it’s important to consider the premium you paid for the option, which was $210. After factoring in this cost, your final profit would be $400 minus $210 = $190.</p><p>Now imagine that PFE is $28 the day before the expiration date. You are above the strike price so the option is “in the money”. You still have the possibility to exercise your option, and you can get 100 PFE for $2700. On the market, its value is $2800, you decide to sell the shares, so you get $100 but you have to consider the premium which was $210. You end up with a loss of $110. So even if the share was above your strike price, you still lost money because you need to consider the premium. In our particular example, the breakeven is reached when the stock price is above $27 + the premium per share ($2.10), for a total of $29.1.</p><p>Finally, if PFE is trading below your strike price of $27, then your contract is worthless and you lost $210. It is said to be “out of the money” because exercising it would not bring anything: you don’t want to buy PFE at the strike price because it is currently trading at a lower price directly on the stock market and you could directly buy it there.</p><p>As you can see in the chart below, our maximal loss is $2.1 per share (the flat red line on the bottom left area) and the maximal profit is infinite (as long as the option can be exercised). You will often seen this kind of charts when it comes to options strategies. I recommend that you try to move along the red and green line to properly understand it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*jX_oq-vttxpF5ldmvGsyWQ.png" /><figcaption>Chart for the call profit/loss</figcaption></figure><p><strong>Writing a Call</strong></p><p>The example above considered you as the buyer of a call option. However, every transaction has a counterpart: you can also be the seller of the call option, for which you receive a premium. As mentioned earlier, the seller of a call option has the obligation to sell 100 shares at the strike price if the buyer chooses to exercise their option.</p><p>The behavior of the seller mirrors that of the buyer. For instance, if the stock price of PFE rises to $31 and the option is exercised, you would be forced to sell PFE at the strike price of $27 per share, which is significantly lower than the market price of $31 where you could have made a better deal with a potential buyer. This results in a loss for you as the seller.</p><p>Conversely, if the market turns bearish, the buyer may not exercise the option, allowing you to keep the premium as profit. If the buyer exercises their option when the market price is $28, you will have to sell them the shares at $27, resulting in a loss of $1 per share. However, since you collected a premium of $2.10 per share when you sold the option, your overall profit will be $1.10 per share after accounting for the loss.</p><p>Thus, the breakeven point for both the buyer and the seller is the same, and the two payoff diagrams are essentially mirror images of each other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*GIm1kEeROpnWHiBgjCQlmw.png" /><figcaption>Chart for the call writing profit/loss</figcaption></figure><p>It’s crucial to understand an important aspect of this example: it illustrates a <strong>naked write of a call option</strong>, also known as an <strong>uncovered call</strong>. In this strategy, the investor sells call options without actually owning the underlying asset. This approach carries a significant risk, as potential losses can be unlimited.</p><p>For instance, imagine if PFE skyrockets to $200 overnight because it discovers a universal cure for cancer (though this scenario is highly unlikely). As the seller of the call option, you would still be obligated to sell shares at the strike price of $27. Since you don’t own the shares, you would have to buy them at the current market price of $200 before selling them at the discounted price of $27. This scenario results in a substantial loss, illustrating the inherent risks of naked call writing. <strong>Never sell a naked write without ensuring you have locked the asset first.</strong></p><p>How to fix that big issue? Well we can make it covered! We are going to see what are the benefits of doing so and how we can elaborate a strategy.</p><p><strong>Covered Call</strong></p><p>The main difference between an uncovered (naked) call and a covered call lies in share ownership. With a covered call, you own the underlying shares, meaning you aren’t selling the call “naked.”</p><p>This significantly reduces your risk as the seller. If the option is exercised, you can simply deliver the shares you already own, avoiding the need to buy them at potentially high market prices (as you would with a naked call). However, this also limits your profit potential to the premium received and any gains up to the strike price.</p><p>When selecting the call option to sell in a covered call strategy, you would typically <strong>chooses an out-of-the-money (OTM) or at-the-money (ATM) call</strong> option. An OTM call has a strike price higher than the current stock price, allowing for some potential price appreciation in the underlying stock before the option is exercised. This choice lets you capture gains up to the strike price in addition to the premium. An ATM call has a strike price equal to the stock’s current price, which maximizes the premium collected but offers little to no upside in stock appreciation. The <strong>expiration date of the option also plays a crucial role</strong>; shorter-term options provide frequent opportunities to sell more calls but generate lower premiums, while longer-term options offer higher premiums but lock in the position for an extended period. Covered calls are often based on contracts that expire in a few weeks.</p><p>The investor must balance these factors based on their market outlook and risk tolerance — choosing a strike price and expiration date that best aligns with their goals of generating income while potentially capping gains.</p><p>This may sound complex and confusing. What does this mean in practice? Let’s explore with an example based on real numbers.</p><p><strong>Real Case</strong></p><p>On<strong> 11th October 2024</strong>, we see that the stock is trading at $29.28 and it sounds like a fair price based on the economical news, technical indicators, etc.</p><p><strong>Decision 1: we decide to buy 100 PFE at $29.28 on the market for a total of $2928.</strong></p><p>Before moving on, we pay a look at the options chain of Pfizer. The <strong>options chain</strong> is a listing of all available options contracts for a given underlying asset (like a stock, ETF, or index) that are currently trading. The options chain provides important data for each option. For the time being, we will focus on the expiration date, the strike price and the price of the options. There are other parameters that we will cover in the 2nd part.</p><p>Yahoo and many financial sites provide access to options chain. They are also often part of the platforms provided by brokers. This is how the options chain on Yahoo looks like for our stock.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Hf7Tu1r9XeVhRIheLUZDQ.png" /><figcaption><a href="https://finance.yahoo.com/quote/PFE/options/?date=1731628800&amp;straddle=true">https://finance.yahoo.com/quote/PFE/options/?date=1731628800&amp;straddle=true</a></figcaption></figure><p>At the top, we can select the expiration date we’re interested in. For this example, we choose options expiring on <strong>November 15, 2024</strong> (highlighted in the blue rectangle), which is a little over a month away. We’re only focusing on <strong>call options</strong> (on the left side) and not considering the puts. As mentioned earlier, we need to choose a strike price that is <strong>out-of-the-money (OTM)</strong> or <strong>at-the-money (ATM)</strong> — meaning a strike price higher than the current trading price of Pfizer (PFE), which is $29.16. The strike prices of $30, $31, $32, and so on all meet this criterion.</p><p>But now, which strike price should we choose? Looking at the call option with a $30 strike price (in the purple rectangle), the last traded price is <strong>$0.62</strong> (red rectangle). As the seller, this means you would collect <strong>$62</strong> for selling this option. If we look at the next strike price of $31, the price drops to <strong>$0.33</strong>, meaning you’d receive <strong>$33</strong> for selling that option. The higher the strike price, the lower the premium you receive, so the choice depends on your outlook and goals for the stock.</p><p><strong>Decision 2: we decide to sell a call option, strike 30.0, expiration 15 Nov 2024, for $0.62 per share. The total premium we get is $62.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*lO6Ohn1Fi_UGBolM8qdLCg.png" /><figcaption>This is the payoff figure for the writing of the call (alone). The strike at $30 and the premium of $0.62 means that we start losing money if PFE trades at a higher price than $30.62</figcaption></figure><p>So, what’s the benefit of using this strategy? Let’s consider the scenario where we choose the $30 strike price. Several outcomes are possible. Remember, we currently own 100 shares of Pfizer (PFE), purchased for $2928.</p><p><strong>Scenario 1</strong>: If the price of PFE stays below $30 by the expiration date, the option remains out-of-the-money and is never exercised. In this case, you keep the $62 premium and continue holding your 100 shares, which will still be trading at the market price.</p><p><strong>Scenario 2</strong>: If PFE’s price rises above $30, the option may be exercised, meaning you are obligated to sell your 100 shares at $30. You receive $3,000 for your shares, plus you keep the $62 premium, giving you a total of $3062. This results in a net profit of $134.</p><p><strong>In both cases</strong>, you make money from the premium, which acts similarly to a monthly dividend (earning $62 on a $2928 position represents about a 2.11% return). This is the key appeal of the covered call strategy — it generates income whether or not the option is exercised.</p><p><strong>In the first scenario</strong>, you still own your PFE shares, which may rise or fall in the future. You’ve essentially returned to being a regular stockholder, but with an added bonus of $62 for doing virtually nothing. The stock could drop to $25, but it could also rise to $35, at which point you could sell it at a higher price, enjoying the potential for further gains.</p><p><strong>In the second scenario</strong>, you’ve sold your shares at $30. If PFE continues to rise, you miss out on the additional profit you could have made by holding onto the stock and selling it later at, say, $35. That’s the trade-off with this strategy — your gains are capped at the strike price. However, if PFE drops to $25 a few weeks after you sell, you’d likely feel satisfied with the $3,062 total from the covered call, avoiding the downside of holding a now less-profitable stock. This balance of risk and reward is the key consideration when using covered calls.</p><p>We can represent the whole strategy in a chart.</p><ul><li>In purple, the stock we bought at $29.28</li><li>In blue, the call we sold with a strike at $30 and a premium of $0.62. (this is exactly the same curve as the one in the picture above)</li><li>In thick black, the final covered call payoff. <strong>This is the sum of the purple and the blue lines.</strong></li></ul><p>On the black line, you “start making money” at $28.66 which corresponds to the price at which you bought the stock, minus the premium (29.28–0.62). This is logical as your small loss on the stock is compensated by the premium you captured. This line then continues to rise until it reaches the strike. Then your profit is capped. Regarding the loss area, if you get below $28.66, the premium is not sufficient to compensate and you start losing money on the stock (the call is no more involved).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*8FccvxlD6XOKcDuHGyD8aA.png" /></figure><p>Now, let’s consider a scenario where PFE rises above $30 but doesn’t exceed $31 by the expiration date. In this case, the call option with a $31 strike price could have been a more favorable choice, though it would have offered a lower premium of only $33. Since the $30 call is not exercised, you retain your 100 shares, giving you the opportunity to potentially implement another covered call later in the year, a strategy known as a “rollout.”</p><p>Additionally, it’s worth noting that we could have selected a different expiration date. Options with longer expiration periods generally come with higher premiums. For example, if we had chosen a $30 strike price with an expiration date of <strong>December 20, 2024</strong>, we would have collected a premium of <strong>$89</strong>. If we opted for an even later expiration, like <strong>January 17, 2025</strong>, the premium would be <strong>$112</strong>. This illustrates how the choice of expiration date can significantly impact the income generated from selling covered calls.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yIz0MhFozGEfk9y5qqlvQw.png" /><figcaption>List of options with strike $30 and the different available expiration dates.</figcaption></figure><p><strong>The Investor is the Judge</strong></p><p>These examples illustrate that various outcomes can occur depending on market conditions and the specific options chosen. As an investor engaging in call options, your experience and adherence to certain guidelines can greatly influence your decision-making. Ultimately, you are the judge of whether a covered call is suitable for your strategy, whether it’s more advantageous to hold onto the stock, or if simply doing nothing and investing elsewhere would be a better option.</p><p>That said, we can provide some foundational guidelines to consider, which we will refine further in the second part of this discussion:</p><p>Here are some general guidelines for using covered calls:</p><ol><li><strong>Capital</strong>: The strategy requires that you have sufficient capital to acquire 100 shares of the stock. This can be an issue and you may be tempted to buy stocks trading at a lower price to fit your financial situation but this may go against the next rule.</li><li><strong>Stock Ownership</strong>: Only use the covered call strategy if you already own (or are comfortable owning) the underlying stock. The strategy works best if you plan to hold the stock for a while, regardless of short-term price fluctuations. Do not buy bad stocks or illiquid assets.</li><li><strong>Strike Price Selection</strong>: Choose a strike price that aligns with your goals. If you’re willing to sell the stock, pick a strike price closer to the current stock price (this is what we did with the $30 strike example). If you prefer to hold the stock, choose a higher strike price to allow for more potential stock appreciation.</li><li><strong>Expiration Date</strong>: Shorter-term options (weekly or monthly) provide more frequent opportunities to generate income, but may result in lower premiums. Longer-term options provide higher premiums but lock you into the strategy for a longer period.</li><li><strong>Market Outlook</strong>: The strategy works well in neutral or slightly bullish markets. If you believe the stock will move sideways or have only modest gains, selling a covered call can provide income through the premium.</li><li><strong>Risk Management</strong>: The premium earned provides some downside protection, but your risk is still tied to the stock’s price. If the stock drops significantly, the premium won’t fully offset those losses.</li><li><strong>Profit Cap</strong>: Understand that a covered call limits your potential gains. If the stock price rises sharply, your upside is capped at the strike price, and you must sell the stock at that price.</li></ol><p><strong>Next Parts….</strong></p><p>In the <a href="https://medium.com/@k4096/unlocking-the-power-of-covered-calls-with-chatgpt-part-2-0648e98a72e7">parts 2</a> and 3 of this article, we will try to address these questions in a more formal way, based on the additional parameters bound to options (the famous “greeks”). We’ll dive deep into how you can leverage ChatGPT to improve the selection guidelines of the right options. We’ll also take it a step further by building a simple tool in Python to automatically identify the most promising entries in the option chain for the ticker of your choice.</p><p><em>*** Disclaimer: The information provided in this article is for educational purposes only. It is not intended as financial advice, and readers are encouraged to seek professional guidance before making any investment decisions.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7734deab5421" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-investors-handbook/unlocking-the-power-of-covered-calls-with-chatgpt-part-1-7734deab5421">Unlocking the Power of Covered Calls with ChatGPT — Part 1</a> was originally published in <a href="https://medium.com/the-investors-handbook">Investor’s Handbook</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>