<?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 Financial Python on Medium]]></title>
        <description><![CDATA[Stories by Financial Python on Medium]]></description>
        <link>https://medium.com/@financial_python?source=rss-3f9596d610ea------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*nVbaXO_r_wzg-dHfYaBNgA.png</url>
            <title>Stories by Financial Python on Medium</title>
            <link>https://medium.com/@financial_python?source=rss-3f9596d610ea------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 15:59:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@financial_python/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[How to plot Bollinger Bands in Python]]></title>
            <link>https://medium.com/@financial_python/how-to-plot-bollinger-bands-in-python-1d7cc95ad9af?source=rss-3f9596d610ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d7cc95ad9af</guid>
            <category><![CDATA[plotly]]></category>
            <category><![CDATA[technical-analysis]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[bollinger-bands]]></category>
            <dc:creator><![CDATA[Financial Python]]></dc:creator>
            <pubDate>Fri, 06 Oct 2023 19:30:57 GMT</pubDate>
            <atom:updated>2023-10-06T19:30:57.342Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hh-52WgHzxbI8g3sfDolwA.png" /></figure><h3>Introduction</h3><p>Bollinger Bands are a popular technical indicator used by traders and investors to analyze price volatility and potential price reversals. In this article, we’ll explore how to calculate Bollinger Bands in Python using AAPL stock data from yfinance with a 1-hour timeframe. We’ll also discuss how to interpret and use Bollinger Bands as a tool for trading and investment decisions.</p><h3>Step 1: Fetching AAPL Stock Data from yfinance</h3><p>Let’s use yfinance to fetch AAPL stock data with a 1-hour timeframe. Import the required libraries and fetch the data:</p><pre>import yfinance as yf<br><br># Fetch AAPL stock data with a 1-hour timeframe<br>aapl = yf.Ticker(&quot;AAPL&quot;)<br>data = aapl.history(period=&quot;60d&quot;, interval=&quot;1h&quot;)  # Adjust the period as needed</pre><h3>Step 2: Calculating Bollinger Bands</h3><p>Bollinger Bands consist of three lines:</p><ol><li><strong>Middle Band (MA)</strong>: This is the simple moving average (SMA) of the closing prices over a specified period. A common choice is a 20-period SMA.</li><li><strong>Upper Band (UB)</strong>: This is the sum of the 20-period SMA and two times the 20-period standard deviation (SD) of the closing prices.</li><li><strong>Lower Band (LB)</strong>: This is the 20-period SMA minus two times the 20-period SD of the closing prices.</li></ol><p>Let’s calculate Bollinger Bands in Python:</p><pre># Calculate the 20-period Simple Moving Average (SMA)<br>data[&#39;SMA&#39;] = data[&#39;Close&#39;].rolling(window=20).mean()<br><br># Calculate the 20-period Standard Deviation (SD)<br>data[&#39;SD&#39;] = data[&#39;Close&#39;].rolling(window=20).std()<br><br># Calculate the Upper Bollinger Band (UB) and Lower Bollinger Band (LB)<br>data[&#39;UB&#39;] = data[&#39;SMA&#39;] + 2 * data[&#39;SD&#39;]<br>data[&#39;LB&#39;] = data[&#39;SMA&#39;] - 2 * data[&#39;SD&#39;]</pre><h3>Step 3: Interpreting Bollinger Bands</h3><p>Bollinger Bands can be interpreted as follows:</p><ul><li>When the price moves close to the upper band (UB), it may indicate overbought conditions, suggesting a potential price reversal to the downside.</li><li>Conversely, when the price approaches the lower band (LB), it may indicate oversold conditions, suggesting a potential price reversal to the upside.</li><li>The middle band (MA) represents the average price over the specified period and can serve as a reference point.</li></ul><p>Traders often look for price crossovers of the bands or significant price deviations from the bands as potential trading signals.</p><h3>Step 4: Visualizing Bollinger Bands with Plotly</h3><p>To gain better insights from the Bollinger Bands, let’s visualize them alongside the price chart using Plotly. Plotly is a versatile Python library for interactive data visualization. If you haven’t already, install Plotly with:</p><pre>pip install plotly</pre><p>Now, let’s create a Plotly chart that displays the price chart along with the Upper Bollinger Band (UB), Lower Bollinger Band (LB), and the Middle Band (MA):</p><pre>import plotly.graph_objs as go<br><br># Create a Plotly figure<br>fig = go.Figure()<br><br># Add the price chart<br>fig.add_trace(go.Scatter(x=data.index, y=data[&#39;Close&#39;], mode=&#39;lines&#39;, name=&#39;Price&#39;))<br><br># Add the Upper Bollinger Band (UB) and shade the area<br>fig.add_trace(go.Scatter(x=data.index, y=data[&#39;UB&#39;], mode=&#39;lines&#39;, name=&#39;Upper Bollinger Band&#39;, line=dict(color=&#39;red&#39;)))<br>fig.add_trace(go.Scatter(x=data.index, y=data[&#39;LB&#39;], fill=&#39;tonexty&#39;, mode=&#39;lines&#39;, name=&#39;Lower Bollinger Band&#39;, line=dict(color=&#39;green&#39;)))<br><br># Add the Middle Bollinger Band (MA)<br>fig.add_trace(go.Scatter(x=data.index, y=data[&#39;SMA&#39;], mode=&#39;lines&#39;, name=&#39;Middle Bollinger Band&#39;, line=dict(color=&#39;blue&#39;)))<br><br># Customize the chart layout<br>fig.update_layout(title=&#39;AAPL Stock Price with Bollinger Bands&#39;,<br>                  xaxis_title=&#39;Date&#39;,<br>                  yaxis_title=&#39;Price&#39;,<br>                  showlegend=True)<br><br># Show the chart<br>fig.show()</pre><p>In this code:</p><ul><li>We create a Plotly figure (fig) and add traces for the price chart, Upper Bollinger Band (UB), Lower Bollinger Band (LB), and Middle Bollinger Band (MA).</li><li>We use the fill option in the Lower Bollinger Band (LB) trace (tonexty) to fill the area between the LB and the x-axis, effectively shading it.</li><li>Each trace uses go.Scatter to create a line chart, with different line colors and names for clarity.</li><li>We customize the chart layout, including the title and axis labels.</li><li>Finally, we use fig.show() to display the interactive Plotly chart.</li></ul><p>And this is what it looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZtsqLb5KFeO1avyZY2NA5Q.png" /></figure><h3>Conclusion</h3><p>In this article, we’ve coded a Bollinger Bands indicator in Python using AAPL stock data with a 1-hour timeframe. We’ve also discussed how to interpret and use Bollinger Bands for trading and investment decisions. Bollinger Bands are a valuable tool for assessing price volatility and identifying potential reversal points in the market.</p><p>Feel free to adapt this code for other stocks, timeframes, or additional trading strategies.</p><p>Hope you learned something.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d7cc95ad9af" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a MACD Indicator in Python]]></title>
            <link>https://medium.com/@financial_python/building-a-macd-indicator-in-python-190b2a4c1777?source=rss-3f9596d610ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/190b2a4c1777</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[macd-indicator]]></category>
            <category><![CDATA[technical-analysis]]></category>
            <category><![CDATA[macd]]></category>
            <dc:creator><![CDATA[Financial Python]]></dc:creator>
            <pubDate>Fri, 22 Sep 2023 16:20:53 GMT</pubDate>
            <atom:updated>2023-09-22T16:20:53.857Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*naAwUWire5A4op38r3JJ4g.png" /></figure><h3>Introduction</h3><p>The Moving Average Convergence Divergence (MACD) is a widely used technical indicator in trading and investing. It helps traders identify potential trends, reversals, and momentum in an asset’s price. In this article, we’ll delve into coding a MACD indicator in Python using AAPL stock data from yfinance with a 1-hour timeframe. We’ll calculate both the MACD line and the Signal line, and we’ll also print if a cross above or below happened in the last two rows. We’ll use common values for the EMA short-term (12-period) and long-term (26-period) components of MACD and explain why these values are popular choices.</p><h3>Step 1: Fetching AAPL Stock Data from yfinance</h3><p>Let’s use yfinance to fetch AAPL stock data with a 1-hour timeframe. Import the required libraries and fetch the data:</p><pre>import yfinance as yf<br><br># Fetch AAPL stock data with a 1-hour timeframe<br>aapl = yf.Ticker(&quot;AAPL&quot;)<br>data = aapl.history(period=&quot;60d&quot;, interval=&quot;1h&quot;)  # Adjust the period as needed</pre><h3>Step 2: Calculating MACD and Signal Line</h3><p>In this step, we’ll calculate the Moving Average Convergence Divergence (MACD) indicator and the Signal Line. The MACD is derived from two Exponential Moving Averages (EMAs): a short-term EMA and a long-term EMA. Commonly, a 12-period EMA is used for the short-term component, and a 26-period EMA is used for the long-term component.</p><p><strong>Why 12-Period and 26-Period EMAs?</strong></p><p>The choice of these specific periods is grounded in the following principles:</p><ul><li><strong>Sensitivity</strong>: The 12-period EMA is more responsive to recent price changes, providing sensitivity to short-term price movements. In contrast, the 26-period EMA is smoother and reacts more slowly, capturing longer-term trends. This combination helps the MACD identify potential shifts in momentum across various timeframes.</li><li><strong>Convergence and Divergence</strong>: The MACD’s name itself reflects its capacity to detect both convergence (when the MACD line crosses above the Signal Line) and divergence (when it crosses below the Signal Line). This duality makes it a versatile tool for traders interested in both trend-following and reversal strategies.</li></ul><p>Now, let’s delve into the Python code for calculating the MACD and Signal Line using the AAPL stock data:</p><pre># Calculate the 12-period EMA<br>data[&#39;EMA12&#39;] = data[&#39;Close&#39;].ewm(span=12, adjust=False).mean()<br><br># Calculate the 26-period EMA<br>data[&#39;EMA26&#39;] = data[&#39;Close&#39;].ewm(span=26, adjust=False).mean()<br><br># Calculate MACD (the difference between 12-period EMA and 26-period EMA)<br>data[&#39;MACD&#39;] = data[&#39;EMA12&#39;] - data[&#39;EMA26&#39;]<br><br># Calculate the 9-period EMA of MACD (Signal Line)<br>data[&#39;Signal_Line&#39;] = data[&#39;MACD&#39;].ewm(span=9, adjust=False).mean()</pre><p>In the code above:</p><ul><li>We calculate the 12-period EMA (Short-Term EMA) using the ewm() method, specifying a span of 12. This method applies exponential smoothing to the closing prices.</li><li>Similarly, we calculate the 26-period EMA (Long-Term EMA) with a span of 26.</li><li>The MACD is determined as the difference between the Short-Term EMA (EMA12) and the Long-Term EMA (EMA26).</li><li>Lastly, we calculate the Signal Line, which is the 9-period EMA of the MACD.</li></ul><p>This code effectively computes the MACD and Signal Line for the given stock data. You can read more about the pandas ewm() method here: <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.ewm.html">https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.ewm.html</a></p><h3>Step 3: Detecting Crossings and Printing Alerts</h3><p>We want to check if the MACD line crosses above or below the Signal Line in the last two rows of the data. We’ll implement this logic:</p><pre># Check for MACD and Signal Line crossovers in the last two rows<br>last_row = data.iloc[-1]<br>second_last_row = data.iloc[-2]<br><br>if second_last_row[&#39;MACD&#39;] &gt; second_last_row[&#39;Signal_Line&#39;] and last_row[&#39;MACD&#39;] &lt; last_row[&#39;Signal_Line&#39;]:<br>    print(&#39;Cross Below Signal Line&#39;)<br>elif second_last_row[&#39;MACD&#39;] &lt; second_last_row[&#39;Signal_Line&#39;] and last_row[&#39;MACD&#39;] &gt; last_row[&#39;Signal_Line&#39;]:<br>    print(&#39;Cross Above Signal Line&#39;)<br>else:<br>    print(&#39;No Crossover&#39;)</pre><p>Here we are just printing whether or not a cross over happened, but there are many things we can do with this. We can send an email or a text message to alert ourselves if this happened, or we can implement this logic as part of a trading bot. Those are just two suggestions, but you get the idea.</p><h3>Conclusion</h3><p>In this article, we’ve coded a MACD indicator in Python using AAPL stock data with a 1-hour timeframe. We’ve also explained why the common values of 12-period and 26-period EMAs are used in MACD calculations. The MACD indicator is a valuable tool for traders and investors to identify potential trends and reversals in price movements.</p><p>Feel free to adapt this code for other stocks, timeframes, or additional trading strategies.</p><p>Hope you learned something</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=190b2a4c1777" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a VWAP Indicator in Python]]></title>
            <link>https://medium.com/@financial_python/building-a-vwap-indicator-in-python-81ff9157fb13?source=rss-3f9596d610ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/81ff9157fb13</guid>
            <category><![CDATA[vwap-indicator]]></category>
            <category><![CDATA[vwap]]></category>
            <category><![CDATA[technical-analysis]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[pandas]]></category>
            <dc:creator><![CDATA[Financial Python]]></dc:creator>
            <pubDate>Fri, 22 Sep 2023 15:53:32 GMT</pubDate>
            <atom:updated>2023-10-25T16:54:18.253Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hBCveL8L0CVMlp-pleazaw.png" /></figure><p>The Volume Weighted Average Price (VWAP) is a popular trading indicator used by traders and investors to assess the average price of a security based on both its price and trading volume. In this article, we’ll walk through how to code a VWAP indicator in Python using AAPL stock data with a 15-minute timeframe. We’ll also implement a check to alert us when the stock price crosses above or below the VWAP.</p><h3>Step 1: Fetching Stock Data from yfinance</h3><p>We’ll use yfinance to fetch AAPL stock data with a 15-minute timeframe. Import the required libraries and fetch the data:</p><pre>import yfinance as yf<br><br># Fetch AAPL stock data with a 15-minute timeframe<br>aapl = yf.Ticker(&quot;AAPL&quot;)<br>data = aapl.history(period=&quot;60d&quot;, interval=&quot;15m&quot;)</pre><h3>Step 2: Calculating VWAP</h3><p>To calculate the VWAP, we’ll use the following formula:</p><pre>VWAP = Σ(Pi * Vi) / ΣVi</pre><p>Where:</p><ul><li>Pi is the average price at each data point.</li><li>Vi is the corresponding trading volume at each data point.</li></ul><p>Let’s implement this calculation:</p><pre># Calculate VWAP<br>data[&#39;VWAP&#39;] = (((data[&#39;High&#39;] + data[&#39;Low&#39;] + data[&#39;Close&#39;]) / 3) * data[&#39;Volume&#39;]).cumsum() / data[&#39;Volume&#39;].cumsum()</pre><p>In the above code, we use the cumsum() method to perform cumulative summation on the data. Let’s break down how this calculation works:</p><ul><li>cumsum() stands for &quot;cumulative sum.&quot; It&#39;s a pandas DataFrame method that calculates the cumulative sum of values along a specified axis, typically used along columns (axis 0) or rows (axis 1).</li><li>((data[&#39;High&#39;] + data[&#39;Low&#39;] + data[&#39;Close&#39;]) / 3) * data[&#39;Volume&#39;] calculates the cumulative sum of the product of the average price (calculated as the average of high, low, and close prices) and trading volumes. This represents the cumulative sum of the total traded value, a crucial component in VWAP calculation.</li><li>data[&#39;Volume&#39;] calculates the cumulative sum of trading volumes. This cumulative sum of trading volumes serves as the denominator in the VWAP formula.</li><li>To obtain the VWAP at each data point, we divide the cumulative sum of the total traded value by the cumulative sum of trading volumes. This calculation results in the VWAP values stored in the ‘VWAP’ column of the DataFrame.</li></ul><p>The cumsum() method is a powerful tool for performing cumulative operations on data, making it particularly useful for financial and time-series data analysis. Read more about it here: <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.cumsum.html">https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.cumsum.html</a></p><h3>Step 3: Detecting Crossings and Printing Alerts</h3><p>We want to check if the stock price crosses above or below the VWAP in the last two rows of the data. We’ll implement this logic:</p><pre># Check for crossovers in the last two rows<br>last_row = data.iloc[-1]<br>second_last_row = data.iloc[-2]<br><br>if second_last_row[&#39;Close&#39;] &gt; second_last_row[&#39;VWAP&#39;] and last_row[&#39;Close&#39;] &lt; last_row[&#39;VWAP&#39;]:<br>    print(&#39;Price Cross Below VWAP&#39;)<br>elif second_last_row[&#39;Close&#39;] &lt; second_last_row[&#39;VWAP&#39;] and last_row[&#39;Close&#39;] &gt; last_row[&#39;VWAP&#39;]:<br>    print(&#39;Price Cross Above VWAP&#39;)<br>else:<br>    print(&#39;No Crossover&#39;)</pre><p>Here we are just printing whether or not a cross over happened, but there are many things we can do with this. We can send an email or a text message to alert ourselves if this happened, or we can implement this logic as part of a trading bot. Those are just two suggestions, but you get the idea.</p><h3>Conclusion</h3><p>In this article, we’ve coded a VWAP indicator in Python using AAPL stock data with a 15-minute timeframe. We’ve also implemented a check to alert us when the stock price crosses above or below the VWAP. This combination of technical analysis and automation can be a powerful tool for traders and investors.</p><p>Feel free to adapt this code for other stocks, timeframes, or additional trading strategies.</p><p>Hope you learned something</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=81ff9157fb13" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Coding and Visualizing a Stock Price Crossing a Moving Average in Python]]></title>
            <link>https://medium.com/@financial_python/coding-and-visualizing-a-stock-price-crossing-a-moving-average-in-python-ad877bac0005?source=rss-3f9596d610ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad877bac0005</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[plotly]]></category>
            <category><![CDATA[technical-analysis]]></category>
            <dc:creator><![CDATA[Financial Python]]></dc:creator>
            <pubDate>Tue, 12 Sep 2023 15:26:55 GMT</pubDate>
            <atom:updated>2023-09-13T17:42:42.808Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y8IQwRXARyTZUw2qyT31ZA.png" /></figure><h3><strong>Introduction</strong></h3><p>In the world of finance, understanding stock price movements is essential for making informed decisions. One valuable tool for this purpose is the Simple Moving Average (SMA), particularly the SMA over 50 days (SMA50). In this article, we’ll explore how to use Python, the yfinance library to fetch stock data, and Plotly for data visualization. We’ll create an interactive chart that displays moments when the stock price of Apple Inc. ($AAPL) crosses above or below its SMA50.</p><h3><strong>Step 1: Installing Dependencies</strong></h3><p>Make sure you have the required Python libraries installed using pip:</p><pre>pip install yfinance pandas plotly</pre><p>We will use yfinance to download the stock data, pandas to manage the dataframe of stock data, and plotly to display the final chart</p><h3><strong>Step 2: Setting Up Your Development Environment</strong></h3><p>To get started, set up your development environment. Use your preferred text editor or integrated development environment (IDE). Here’s an example of how to set up your Python script:</p><pre># Import necessary libraries<br>import yfinance as yf<br>import plotly.graph_objs as go<br>from plotly.subplots import make_subplots</pre><h3>Step 3: Fetching Stock Price Data with yfinance</h3><p>Fetch historical $AAPL stock price data using yfinance. Make sure you have your Yahoo Finance API key ready:</p><pre>yahooData = yf.download(tickers=&#39;AAPL&#39;, interval=&#39;1d&#39;, period=&#39;2y&#39;)</pre><p>This will pull down 2 years worth of $AAPL stock historical price data into a pandas dataframe. The columns retrieved will be the Open, High, Low, Close, Adj Close, and Volume. We will use the Adj Close moving forward.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wVOv66RhdLcakIH0aOVneQ.png" /></figure><h3>Step 4: Calculating the SMA50</h3><p>Calculate the Simple Moving Average (SMA) over 50 days (SMA50) locally using pandas:</p><pre>yahooData[&#39;SMA50&#39;] = yahooData[&#39;Close&#39;].rolling(window=50).mean()</pre><p>rolling() is a pandas Dataframe method which calculates the rolling price based on the window value provided. We provide 50 here for the sma50. This value can be changed based on the size of the moving average you wish to use.</p><h3><strong>Step 5: Identifying Price Crossing the MA</strong></h3><p>In this step, we’re going to identify specific moments in our stock price data when the price crosses above or below the Simple Moving Average over 50 days (SMA50). These crossings are essential indicators for traders and investors, as they often signify shifts in the stock’s trend.</p><pre>yahooData[&#39;Crossings&#39;] = 0<br>crossing_indices_below = (yahooData[&#39;Close&#39;] &gt; yahooData[&#39;SMA50&#39;]) &amp; (yahooData[&#39;Close&#39;].shift(-1) &lt; yahooData[&#39;SMA50&#39;].shift(-1))<br>crossing_indices_above = (yahooData[&#39;Close&#39;] &lt; yahooData[&#39;SMA50&#39;]) &amp; (yahooData[&#39;Close&#39;].shift(-1) &gt; yahooData[&#39;SMA50&#39;].shift(-1))<br>yahooData.loc[crossing_indices_below, &#39;Crossings&#39;] = -1<br>yahooData.loc[crossing_indices_above, &#39;Crossings&#39;] = 1</pre><p>Here’s a breakdown of how we’ll identify these crossings:</p><ul><li>We begin by creating a new column in our dataset called ‘Crossings’ to mark these events. This column will help us distinguish between three scenarios: no crossing (0), crossing below SMA50 (-1), and crossing above SMA50 (1).</li><li>To find crossings below SMA50 (when the stock price moves from above to below the SMA50), we use the following logic:</li><li>crossing_indices_below = (data[&#39;Close&#39;] &gt; data[&#39;SMA50&#39;]) &amp; (data[&#39;Close&#39;].shift(-1) &lt; data[&#39;SMA50&#39;].shift(-1))</li><li>This code snippet compares the closing price of the current day with the SMA50 and checks if the closing price of the next day is below the SMA50. When both conditions are met, it indicates a crossover from above to below the SMA50, and we mark it as -1 in the ‘Crossings’ column.</li><li>To find crossings above SMA50 (when the stock price moves from below to above the SMA50), we use a similar logic:</li><li>crossing_indices_above = (data[&#39;Close&#39;] &lt; data[&#39;SMA50&#39;]) &amp; (data[&#39;Close&#39;].shift(-1) &gt; data[&#39;SMA50&#39;].shift(-1))</li><li>This code snippet compares the closing price of the current day with the SMA50 and checks if the closing price of the next day is above the SMA50. When both conditions are met, it indicates a crossover from below to above the SMA50, and we mark it as 1 in the ‘Crossings’ column.</li></ul><p>By employing these logical conditions, we accurately pinpoint the moments when the stock price crosses above or below the SMA50. These are vital signals for traders and investors, helping them make informed decisions about buying or selling stocks.</p><h3>Step 6: Creating the Plotly Chart</h3><p>In this step, we’ll use the Plotly library to create an interactive chart that visualizes the $AAPL stock price and highlights key moments when it crosses above or below the Simple Moving Average over 50 days (SMA50). This chart provides a clear visual representation of important trading signals for investors and traders.</p><pre># Initialize a Plotly figure with subplots<br>fig = make_subplots(rows=1, cols=1, shared_xaxes=True)<br><br># Add the stock price and SMA50 lines<br>stock_price_line = go.Scatter(x=yahooData.index, y=yahooData[&#39;Close&#39;], mode=&#39;lines&#39;, name=&#39;Stock Price&#39;, line=dict(color=&#39;blue&#39;))<br>sma50_line = go.Scatter(x=yahooData.index, y=yahooData[&#39;SMA50&#39;], mode=&#39;lines&#39;, name=&#39;SMA50&#39;, line=dict(color=&#39;orange&#39;))<br>fig.add_trace(stock_price_line)<br>fig.add_trace(sma50_line)<br><br># Add markers for crossings<br>cross_below = go.Scatter(x=yahooData[yahooData[&#39;Crossings&#39;] == -1].index, y=yahooData[yahooData[&#39;Crossings&#39;] == -1][&#39;SMA50&#39;],<br>    mode=&#39;markers&#39;, name=&#39;Price Crosses Below SMA50&#39;, marker=dict(color=&#39;red&#39;, size=10))<br>fig.add_trace(cross_below)<br><br># Add markers for crossings above SMA50<br>cross_above = go.Scatter(x=yahooData[yahooData[&#39;Crossings&#39;] == 1].index, y=yahooData[yahooData[&#39;Crossings&#39;] == 1][&#39;SMA50&#39;],<br>    mode=&#39;markers&#39;, name=&#39;Price Crosses Above SMA50&#39;, marker=dict(color=&#39;green&#39;, size=10))<br>fig.add_trace(cross_above)<br><br># Customize the layout<br>fig.update_layout(title=&#39;AAPL Stock Price and SMA50 Crossings&#39;,<br>    xaxis_rangeslider_visible=False, xaxis_title=&#39;Date&#39;,<br>    yaxis_title=&#39;Price&#39;, showlegend=True)<br><br># Show the chart<br>fig.show()</pre><p>Here’s a breakdown of how we construct this dynamic chart:</p><ul><li>We start by initializing a Plotly figure using make_subplots(). This sets up the foundation for our chart, allowing us to create multiple plots within a single figure if needed. In our case, we&#39;ll create a single plot.</li><li>Next, we define two line plots using the go.Scatter trace type: one for the stock price and one for the SMA50. These lines will help us visualize the historical price movements and the SMA50&#39;s trend.</li><li>stock_price_line represents the stock price line, displayed in blue.</li><li>sma50_line represents the SMA50 line, displayed in orange.</li><li>Both lines are set to mode=&#39;lines&#39;, ensuring a smooth line graph representation.</li><li>We add these two lines to our Plotly figure using fig.add_trace(). This step places the lines on the chart for further customization.</li><li>To make our chart more informative, we also add markers at the specific moments when the stock price crosses above or below the SMA50. These markers serve as visual indicators of significant events.</li><li>We create two marker plots, cross_below and cross_above, using go.Scatter with mode=&#39;markers&#39;.</li><li>cross_below is used to mark points when the price crosses below SMA50. These points are displayed as red dots with a size of 10.</li><li>cross_above is used to mark points when the price crosses above SMA50. These points are displayed as green dots with a size of 10.</li><li>Just like the line plots, we also add these marker plots to our Plotly figure using fig.add_trace().</li><li>Finally, we customize the chart’s layout. We set the title, label the x-axis and y-axis, and specify whether to display the legend. We also hide the x-axis range slider, as it’s not needed for this specific chart.</li><li>Once our figure is fully configured, we use fig.show() to display the interactive chart. This chart will allow users to explore the stock price and SMA50 trends and visually identify significant crossing points.</li></ul><p>By creating this Plotly chart, we provide a powerful visual tool for investors and traders to make data-driven decisions based on the stock’s historical performance in relation to the SMA50. The green and red dots serve as actionable signals, making it easier to time investments effectively.</p><p>Here is what the end result looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fC1imjgLbRUXs1iJ-rdfow.png" /></figure><h3>Conclusion</h3><p>In this article, we’ve explored how to use Python, yfinance, and Plotly to create an interactive chart that highlights moments when the $AAPL stock price crosses above or below its SMA50. This project demonstrates the power of Python in financial analysis and data visualization, empowering you to make informed investment decisions.</p><p>Hope you learned something</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad877bac0005" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Send Emails with Python]]></title>
            <link>https://medium.com/@financial_python/how-to-send-emails-with-python-663924806fb1?source=rss-3f9596d610ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/663924806fb1</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[smtplib]]></category>
            <dc:creator><![CDATA[Financial Python]]></dc:creator>
            <pubDate>Wed, 19 Jul 2023 15:17:03 GMT</pubDate>
            <atom:updated>2023-07-19T15:17:03.012Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kRa7x3TnrXYrRwth_IiHaQ.png" /></figure><p>Sending emails programmatically can greatly enhance your productivity and automation capabilities. In this tutorial, we will explore how to send emails using Python, leveraging the power of the smtplib and email libraries. Whether you&#39;re automating email notifications or building personalized email campaigns, Python provides a straightforward and efficient solution. Let&#39;s dive in and discover how to harness the potential of Python for sending emails.</p><h3>SMTP Config</h3><p>Before we dive into the code, it’s important to make your Gmail account compatible with SMTP for sending emails. By default, Gmail has strict security measures that may prevent the use of your account with certain applications. However, you can easily overcome this by generating an app password specifically for SMTP access. Here’s how to do it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3_kQ5k_uMGc2ZjpXt1ipEg.png" /></figure><ol><li>Open your web browser and navigate to <a href="https://myaccount.google.com/apppasswords">https://myaccount.google.com/apppasswords</a>. Sign in with your Gmail account credentials if prompted.</li><li>Under the “Select the app and device you want to generate the app password for” section, choose “Other (custom name)” from the dropdown list. Enter the name of your application.</li><li>Click the “Generate” button. Google will generate a unique 16-character app password for you.</li><li>Make a note of the app password as you will need it later in the code. Take care to keep it secure, as this password grants access to your Gmail account.</li></ol><h3><strong>Code</strong></h3><p>To demonstrate the process of sending emails, we’ll use a simple Python script. Here’s the code that sets up the email configuration and sends the email:</p><pre>#MAIN FILE<br><br>from email.mime.multipart import MIMEMultipart<br>from email.mime.text import MIMEText<br>import smtplib<br>from string import Template<br><br>MAIL_SMTP_SERVER = &#39;smtp.gmail.com&#39;<br>MAIL_SMTP_PORT = 587<br>MAIL_SMTP_USERNAME = &#39;&#39;  # Your email address<br>MAIL_SMTP_PASSWORD = &#39;&#39;  # Your email password<br>MAIL_DISPLAY_NAME = &#39;&#39;  # Your desired display name<br><br>def main():<br>    # Load the email template from a file<br>    with open(&#39;email_template.html&#39;) as file:<br>        template_content = file.read()<br><br>    template = Template(template_content)<br><br>    # Set up the email body using the template and dynamic data<br>    context = {<br>        &#39;dynamic_string_one&#39;: &#39;this is a test&#39;,<br>        &#39;dynamic_string_two&#39;: &#39;this is another test&#39;<br>    }<br><br>    email_body = template.substitute(context)<br><br>    # Create the email message<br>    message = MIMEMultipart()<br>    message[&#39;From&#39;] = f&quot;{MAIL_DISPLAY_NAME} &lt;{MAIL_SMTP_USERNAME}&gt;&quot;<br>    message[&#39;To&#39;] = &#39;recipient@example.com&#39;  # Replace with the recipient&#39;s email address<br>    message[&#39;Subject&#39;] = &#39;Testing&#39;  # Set the email subject<br><br>    # Attach the email body as HTML<br>    message.attach(MIMEText(email_body, &#39;html&#39;))<br><br>    # Send the email using the SMTP server<br>    with smtplib.SMTP(MAIL_SMTP_SERVER, MAIL_SMTP_PORT) as server:<br>        server.starttls()<br>        server.login(MAIL_SMTP_USERNAME, MAIL_SMTP_PASSWORD)<br>        server.sendmail(MAIL_SMTP_USERNAME, [message[&#39;To&#39;]], message.as_string())<br><br>    print(&#39;Email sent successfully.&#39;)<br><br><br>if __name__ == &#39;__main__&#39;:<br>    main()</pre><pre>&lt;!-- EXAMPLE EMAIL TEMPLATE --&gt;<br>&lt;html&gt;<br>  &lt;head&gt;<br>    &lt;style&gt;<br>      body {<br>        max-width: 1000px;<br>      }<br>      @font-face {<br>        font-family: &#39;Roboto&#39;;<br>        src: url(https://medium.com/&#39;https://fonts.googleapis.com/css?family=Roboto&amp;display=swap&#39;);<br>      }<br>      table {<br>        font-family: &#39;Roboto&#39;, sans-serif;<br>        border-collapse: collapse;<br>        width: 100%;<br>        border-collapse: collapse;<br>        margin: 0 auto;<br>      }<br>      th,<br>      td {<br>        text-align: left;<br>        padding: 8px;<br>        border: 1px solid #ddd;<br>        font-size: 14px;<br>      }<br>      th {<br>        background-color: #f2f2f2;<br>      }<br>    &lt;/style&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;p&gt;First dynamic string: ${dynamic_string_one}&lt;/p&gt;<br>    &lt;p&gt;second dynamic string: ${dynamic_string_two}&lt;/p&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><h3>Explanation</h3><ol><li>We begin by importing necessary modules from the email.mime and smtplib libraries.</li><li>Next, we define the configuration variables required for the email setup, such as the SMTP server, port, credentials, and display name.</li><li>In the main function, we load the email template from a file and set up the email body using the Template class from the string module. You can customize the dynamic data in the context dictionary to personalize your emails.</li><li>We create an instance of MIMEMultipart to construct the email message and set the necessary fields like the sender, recipient, and subject. We use this email type because it allows for the addition of an HTML email body, which is what we are using here</li><li>The email body, in this case, an HTML template, is attached to the message using MIMEText.</li><li>Finally, we establish a connection to the SMTP server, login with the provided credentials, and use sendmail to send the email.</li></ol><h3><strong>Conclusion</strong></h3><p>Congratulations! You have now learned how to send emails using Python. With this knowledge, you can automate email communications, create personalized campaigns, and integrate email functionality into your projects. Python’s simplicity and powerful libraries like smtplib and email make it an ideal choice for handling email operations programmatically. So go ahead, explore the possibilities, and unlock the potential of automated email communication with Python.</p><p>Remember to adapt the code according to your specific email provider’s SMTP settings and customize the email template to suit your needs.</p><p>Hopefully you found this helpful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=663924806fb1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Uploading Files to AWS S3 using Python and Boto3]]></title>
            <link>https://medium.com/@financial_python/uploading-files-to-aws-s3-using-python-and-boto3-622efbe1af5c?source=rss-3f9596d610ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/622efbe1af5c</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[boto3]]></category>
            <category><![CDATA[aws-s3]]></category>
            <dc:creator><![CDATA[Financial Python]]></dc:creator>
            <pubDate>Sun, 09 Jul 2023 16:31:49 GMT</pubDate>
            <atom:updated>2023-07-09T16:31:49.934Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G4LoifEywngTiP6n1bfHKA.png" /></figure><p>Hey all. Today, I am going to walk you through uploading files to Amazon Web Services (AWS) Simple Storage Service (S3) using Python and Boto3. We’ll break it down step by step so you can follow along and build a robust solution for your AWS applications. Let’s get started.</p><h3>Step 1: Creating an S3 Bucket</h3><p>First things first. We need to create an S3 bucket to store our files. Here’s how to do it:</p><ol><li>Log in to your AWS Management Console.</li><li>Navigate to the S3 service.</li><li>Click on the “Create bucket” button.</li><li>Fill in the “Bucket name” field and choose the appropriate region for your bucket. The region will be defaulted to your current region, and you can most likely leave that as is.</li><li>The remaining settings can be left at their default values for this tutorial, but feel free to adjust them as per your project requirements.</li><li>Click on the “Create bucket” button at the bottom of the page.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*8AQ3nnW7F7jFin8zZEIydA.png" /></figure><p>Now, we have an S3 bucket ready to store our files!</p><h3>Step 2: Creating an IAM Policy</h3><p>Next, we need to create an Identity and Access Management (IAM) policy that will permit our Python script to interact with our S3 bucket. Here’s how to do it:</p><ol><li>Navigate to the IAM service within your AWS Console.</li><li>On the left sidebar, click on “Policies.”</li><li>Click on the “Create policy” button.</li><li>Switch to the “JSON” tab.</li><li>Paste the following policy, replacing ‘&lt;bucket_name&gt;’ with the name of the S3 bucket you created:</li></ol><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: &quot;s3:*&quot;,<br>            &quot;Resource&quot;: &quot;arn:aws:s3:::&lt;bucket_name&gt;/*&quot;<br>        }<br>    ]<br>}</pre><ul><li>What this is basically saying is — Allow any user that has this policy to perform all s3 ‘Actions’ on the ‘Resource’, which in this case the bucket and all of its content</li></ul><p>6. Click on the “Review policy” button.</p><p>7. Fill in the “Name” field and (optionally) the “Description” field, then click “Create policy.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*ZKHmCJjW4biPauptlx_9FQ.png" /></figure><p>With the IAM policy in place, we can create an IAM user and attach the policy to it.</p><h3>Step 3: Creating an IAM User</h3><p>To securely interact with AWS services, we need to create an IAM user. Follow these steps:</p><ol><li>On the IAM service page, click on “Users” on the left sidebar.</li><li>Click on the “Add user” button.</li><li>Fill in the “User name” field.</li><li>Click on the “Next” button.</li><li>On the permissions page, click on the “Attach policies directly” tab.</li><li>Search for the policy you created in the previous step and check the box next to it.</li><li>After reviewing, click on the “Create user” button.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G0shm5Ua00kAWA2I5WHmUQ.png" /></figure><h3>Step 4: Accessing Your User Security Credentials</h3><p>Upon creating the IAM user, you can click into the user record and navigate to the ‘Security credentials’ tab. There you will see an option to ‘Create access key’. Clicking this will give you both an access key and a secret key. Copy them down, you will need both.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AKkwQ_oIEdtwaaOk4UaVsA.png" /></figure><h3>Step 5: Writing the Python Script</h3><p>With our AWS setup ready, let’s dive into the Python part of the tutorial. We’ll use the Boto3 library to interact with our S3 bucket.</p><p>First, install Boto3 if you haven’t already by running pip3 install boto3 in your command line.</p><p>Below is a simple Python script that uses Boto3 to upload a file to our S3 bucket. Replace the placeholder values with your actual bucket name, region, access key, and secret key.</p><p>The <strong>LOCAL_FILE</strong> variable represents the actual file from your local directory that you wish to upload. The <strong>NAME_FOR_S3</strong> variable represents what you want the file to be called when it is inserted into the s3 bucket</p><pre>import boto3<br><br>AWS_S3_BUCKET_NAME = &#39;&lt;bucket_name&gt;&#39;<br>AWS_REGION = &#39;&lt;your_aws_region&gt;&#39;<br>AWS_ACCESS_KEY = &#39;&lt;iam_user_access_key&gt;&#39;<br>AWS_SECRET_KEY = &#39;&lt;iam_user_secret_key&gt;&#39;<br><br>LOCAL_FILE = &#39;test_file.txt&#39;<br>NAME_FOR_S3 = &#39;test_file.txt&#39;<br><br>def main():<br>    print(&#39;in main method&#39;)<br><br>    s3_client = boto3.client(<br>        service_name=&#39;s3&#39;,<br>        region_name=AWS_REGION,<br>        aws_access_key_id=AWS_ACCESS_KEY,<br>        aws_secret_access_key=AWS_SECRET_KEY<br>    )<br><br>    response = s3_client.upload_file(LOCAL_FILE, AWS_S3_BUCKET_NAME, NAME_FOR_S3)<br><br>    print(f&#39;upload_log_to_aws response: {response}&#39;)<br><br>if __name__ == &#39;__main__&#39;:<br>    main()</pre><p>Just run the script, and it will upload the specified local file to your S3 bucket. Note: the upload_file function does not return any value when the upload is successful; it will raise an exception if there is an error.</p><p>And that’s it! You have successfully uploaded a file to your AWS S3 bucket using Python and Boto3.</p><p>Hopefully you found this helpful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=622efbe1af5c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Get Stock Share Borrowing Data with iBorrowDesk and Python]]></title>
            <link>https://medium.com/@financial_python/get-stock-share-borrowing-data-with-python-and-iborrowdesk-77d6d41b82af?source=rss-3f9596d610ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/77d6d41b82af</guid>
            <category><![CDATA[short-squeeze]]></category>
            <category><![CDATA[technical-analysis]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Financial Python]]></dc:creator>
            <pubDate>Thu, 25 May 2023 14:23:09 GMT</pubDate>
            <atom:updated>2023-06-04T16:45:23.256Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S5qjC8tPFSIqLwX2Mz5D2g.png" /></figure><p>One often overlooked but significant aspect of stock analysis is the availability and borrowing costs of shares. Understanding the stock borrowing landscape provides valuable insights into market sentiment, short-selling trends, and potential trading opportunities. By delving into the realm of borrowing data, traders, investors, and financial analysts can gain a competitive edge by uncovering hidden patterns and signals that can impact stock prices and overall market dynamics.</p><p>This article explores how you can leverage iBorrowDesk, a platform that provides comprehensive stock share borrowing information, to get share borrow data in a Python method. This data can be used as part of a trading bot, or for display on a website, as is the case on mine: <a href="https://www.financialpython.com/">FinancialPython.com</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*1HHqsQq02gnn5gtcFCdz4w.png" /></figure><p>I’m using this stock $LEO as an example because, as of this writing on 5–24–23, we are seeing it’s borrow costs increasing and available shares decreasing. This could indicate a potential short squeeze in the future. So let’s talk about how we get the borrow data.</p><p><strong>iBorrowDesk</strong></p><p>A Gateway to Stock Share Borrowing Data, <a href="https://iborrowdesk.com/">iBorrowDesk</a> offers a valuable service by providing information on the availability, fees, and rebates associated with borrowing stock shares.</p><p>To retrieve stock borrow data from iBorrowDesk in a Python method, we can utilize the hidden iBorrowDesk API. You’ll understand shortly why I say ‘hidden’. Here’s a step-by-step guide on how to accomplish this:</p><ol><li>Open your browser and navigate to the iBorrowDesk report page for a specific stock, such as LEO (<a href="https://iborrowdesk.com/report/LEO">https://iborrowdesk.com/report/LEO</a>).</li><li>Open the browser developer tools:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qcmWlVmcNIHQ5BB0JYeVww.png" /><figcaption>Chrome Example</figcaption></figure><p>3. Within the Inspector, switch to the “Network” tab to monitor the network requests. You may need to refresh the page to see the network requests come in.</p><p>4. Search for the API request responsible for fetching the stock share borrowing data. You can do this by filtering by the stock name:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aJMpaZRND0AAUu2mDEt6Ig.png" /></figure><p>5. You can see from the example above that this is a get request coming from ‘https://iborrowdesk.com/api/ticker/LEO’. Opening this in your browser or in the preview tab, you can see that this request returns a JSON object containing a list of records named ‘daily’:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*y4Ck3lLbfb4VOZD0U97j3A.png" /></figure><p>The structure of a record looks lie this:</p><pre>{<br>  &quot;available&quot;: 100000,<br>  &quot;date&quot;: &quot;2022-05-24&quot;,<br>  &quot;fee&quot;: 894.2238,<br>  &quot;high_available&quot;: 100000,<br>  &quot;high_fee&quot;: 894.2238,<br>  &quot;high_rebate&quot;: -877.3997,<br>  &quot;low_available&quot;: 100000,<br>  &quot;low_fee&quot;: 882.4597,<br>  &quot;low_rebate&quot;: -889.1538,<br>  &quot;rebate&quot;: -889.1538<br>}</pre><p>6. Make a request in python</p><pre>def get_borrow_data(ticker):<br>    #https://iborrowdesk.com/api/ticker/LEO<br>    print(f&quot;in get borrow data for {ticker}&quot;)<br><br>    url = &quot;https://iborrowdesk.com/api/ticker/&quot; + ticker.upper()<br>    headers = {&#39;User-Agent&#39;: &#39;Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36&#39;}<br>    r = requests.get(url, headers=headers)<br><br>    if not r.ok:<br>        print(&#39;request failure in get_borrow_data&#39;)<br>        print(r)<br>    try:<br>        result = r.json()[&#39;daily&#39;]<br>        return result[-10:]<br>    except Exception as e:<br>        print(&#39;error in get_borrow_data&#39;)<br>        print(e)</pre><p>In this method, we pass in a ticker, make a request, and return the 10 latest daily records. Be sure to include the necessary headers to mimic a browser making the request and not a script.</p><p><strong>That’s pretty much it.</strong></p><p>Now you can do whatever you want with the data. You can cherry-pick the fields that are most relevant to your requirements. By analyzing how these values fluctuate, you can gain insights into market dynamics and potentially use this information to develop trading strategies or feed indicators into your trading bot.</p><p>As I mentioned, I display it on my website for each stock, but I’m also experimenting with using this data in trading bots. This dataset goes back a year, so I am able to backtest a bit and see how the changes in the number of available shares and associated fees over time effect the stock price.</p><p>Of course I wouldn’t make a bot with this as the only indicator and you shouldn’t either. But adding this to a bot may prove to be valuable.</p><p>Thanks for reading and hopefully you found this helpful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77d6d41b82af" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Use ChatGPT API for Sentiment Analysis in Python]]></title>
            <link>https://medium.com/@financial_python/use-chatgpt-api-for-sentiment-analysis-in-python-5a152ddb3238?source=rss-3f9596d610ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a152ddb3238</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[sentiment-analysis]]></category>
            <dc:creator><![CDATA[Financial Python]]></dc:creator>
            <pubDate>Wed, 05 Apr 2023 19:31:50 GMT</pubDate>
            <atom:updated>2023-04-11T14:39:20.862Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lrE5us86Aq7kXYSUcgDCbg.png" /></figure><p>Sentiment analysis is a popular application of natural language processing that involves analyzing the emotional tone of a piece of text. By determining whether a text is positive, negative, or neutral, sentiment analysis can be used for a variety of purposes, such as tracking brand reputation, gauging customer feedback, or monitoring social media sentiment.</p><p>One way to perform sentiment analysis is by using the ChatGPT API, a powerful language model created by OpenAI that can generate natural language text in response to various prompts. In this tutorial, we’ll show you how to use the ChatGPT API for sentiment analysis in Python.</p><p><strong>Step 1: Sign Up for the OpenAI API and Obtain an API Key</strong></p><p>To use the ChatGPT API, you’ll first need to sign up for the OpenAI API and obtain an API key. You can do this by visiting the OpenAI website and following the instructions there. Once you have your API key, be sure to keep it secure and confidential, as it grants access to your OpenAI account and usage limits.</p><p><strong>Step 2: Install the OpenAI Python Library</strong></p><p>Next, you’ll need to install the OpenAI Python library, which provides a simple interface for interacting with the OpenAI API. You can install the library by running the following command in your terminal or command prompt:</p><pre>pip install openai</pre><p><strong>Step 3: Create a Sentiment Analysis Prompt</strong></p><p>To perform sentiment analysis using the ChatGPT API, we’ll need to create a prompt that the API can use to generate a sentiment score for a given text. Here’s an example prompt that we can use:</p><pre>Sentiment analysis of the following text: &#39;I am bullish on $AAPL&#39;<br><br>Sentiment score:</pre><p>In this prompt, we’re simply asking the ChatGPT API to perform sentiment analysis on the text “I am bullish on $AAPL”, and we’re leaving a blank space for the sentiment score to be generated.</p><p><strong>Step 4: Call the ChatGPT API for Sentiment Analysis</strong></p><p>Now that we have a prompt, we can use the OpenAI Python library to call the ChatGPT API and generate a sentiment score for a given text. Here’s an example Python script that does this:</p><pre>import openai<br>openai.api_key = &quot;YOUR_API_KEY_HERE&quot;<br><br>text = &quot;I am bullish on $AAPL&quot;<br>response = openai.Completion.create(<br>    engine=&quot;text-davinci-003&quot;,<br>    prompt=(f&quot;Sentiment analysis of the following text: &#39;{text}&#39;\n\nSentiment score: &quot;),<br>    temperature=0,<br>    max_tokens=1<br>)<br><br>sentiment = response.choices[0].text.strip()<br>print(sentiment)</pre><p>In this script, we’re using the openai.Completion.create() method to send a prompt to the ChatGPT API. We&#39;re passing in the prompt we created earlier, along with several parameters that control how the API generates its response. Specifically:</p><ul><li>engine: This parameter specifies which language model to use. We&#39;re using the davinci model, which is the most powerful and versatile model available.</li><li>temperature: This parameter controls the creativity of the response. We&#39;re setting it to 0, which means that the API will always generate the most likely response.</li><li>max_tokens: This parameter sets the maximum length of the response. We&#39;re setting it to 1, which means that the API will only generate a response that is max 1 word. This is enough size to get back ‘Positive’, ‘Negative’, or some sort of unknown value — we don’t want any more than that right now.</li></ul><p>After we send the request, we extract the sentiment from the response by taking the first choice in the response.choices list and removing any whitespace using the strip() method.</p><p><strong>Step 5: Use the Sentiment Score in Your Code</strong></p><p>As I said before, the values we would get back are ‘Positive’, ‘Negative’, or a third random string indicating that GPT isn’t sure. We can code different scenarios based on each response:</p><pre>if sentiment == &quot;Positive&quot;:<br>    print(&quot;😊&quot;)<br>elif sentiment == &quot;Negative&quot;:<br>    print(&quot;😔&quot;)<br>else:<br>    print(&quot;😐&quot;)</pre><p>Hopefully you found this helpful. <a href="https://gist.github.com/financial-python/d0034c44728f3a71a4904e70a2a77668">Here is a link to the gist if you would like</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a152ddb3238" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to code an EMA crossover in Python]]></title>
            <link>https://medium.com/@financial_python/how-to-code-an-ema-crossover-in-python-96ecd22ae252?source=rss-3f9596d610ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/96ecd22ae252</guid>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[matplotlib]]></category>
            <category><![CDATA[technical-analysis]]></category>
            <dc:creator><![CDATA[Financial Python]]></dc:creator>
            <pubDate>Fri, 24 Mar 2023 18:12:52 GMT</pubDate>
            <atom:updated>2023-03-28T14:35:45.357Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8bqzu_S4YwBLpp8gyCmcqg.png" /></figure><p>If you’re interested in technical analysis, you may have heard of the exponential moving average (EMA) crossover strategy. This popular trading strategy uses two EMAs of different periods to identify potential changes in a stock’s trend. In this tutorial, we’ll show you how to calculate an EMA crossover using a stock dataframe downloaded from yfinance.</p><p><strong>Step 1: Import yfinance and pandas libraries</strong></p><p>The first step is to import the necessary libraries. We’ll use the yfinance library to download stock data, and the pandas library to manipulate the data.</p><pre>import yfinance as yf<br>import pandas as pd</pre><p><strong>Step 2: Download stock data using yfinance</strong></p><p>Next, we’ll download historical stock data for a particular stock using the yfinance library. In this example, we’ll download data for Apple Inc. (AAPL) for the last 5 years.</p><pre>aapl_df = yf.download(&quot;AAPL&quot;, start=&quot;2018-03-24&quot;, end=&quot;2023-03-24&quot;)</pre><p><strong>Step 3: Calculate the short-term and long-term EMAs</strong></p><p>The next step is to calculate the short-term and long-term EMAs. In this example, we’ll use a 20-day EMA as the short-term EMA and a 50-day EMA as the long-term EMA.</p><pre>aapl_df[&#39;ema_short&#39;] = aapl_df[&#39;Close&#39;].ewm(span=20, adjust=False).mean()<br>aapl_df[&#39;ema_long&#39;] = aapl_df[&#39;Close&#39;].ewm(span=50, adjust=False).mean()</pre><p><strong>Step 4: Calculate the EMA crossover signals</strong></p><p>Now that we’ve calculated the short-term and long-term EMAs, we can use them to generate EMA crossover signals. A bullish crossover occurs when the short-term EMA crosses above the long-term EMA, while a bearish crossover occurs when the short-term EMA crosses below the long-term EMA.</p><p>To do this, we will maintain a column in the dataframe called ‘bullish’. It will hold a value of 1.0 when the ema_short is greater than the ema_long, and a value of 0.0 when ema_short is lower than ema_long. Another column called ‘crossover’ will tell us when the crossover actually happened — when the ema_short crossed above or below the ema_long.</p><pre>aapl_df[&#39;bullish&#39;] = 0.0<br>aapl_df[&#39;bullish&#39;] = np.where(aapl_df[&#39;ema_short&#39;] &gt; aapl_df[&#39;ema_long&#39;], 1.0, 0.0)<br>aapl_df[&#39;crossover&#39;] = aapl_df[&#39;bullish&#39;].diff()</pre><p>The crossover column will hold 1.0 on a cross above, and -1.0 on a cross below. It will hold 0.0 when no cross happens in that dataframe row.</p><p><strong>Step 5: Visualize the EMA crossover signals</strong></p><p>Finally, we can visualize the EMA crossover signals using a line chart. We’ll use the “crossover” column we created in step 4 to plot the actual buy and sell signals.</p><pre>import matplotlib.pyplot as plt<br><br>fig = plt.figure(figsize=(12,8))<br>ax1 = fig.add_subplot(111, ylabel=&#39;Price in $&#39;)<br><br>aapl_df[&#39;Close&#39;].plot(ax=ax1, color=&#39;b&#39;, lw=2.)<br>aapl_df[&#39;ema_short&#39;].plot(ax=ax1, color=&#39;r&#39;, lw=2.)<br>aapl_df[&#39;ema_long&#39;].plot(ax=ax1, color=&#39;g&#39;, lw=2.)<br><br>ax1.plot(aapl_df.loc[aapl_df.positions == 1.0].index, <br>         aapl_df.Close[aapl_df.positions == 1.0],<br>         &#39;^&#39;, markersize=10, color=&#39;g&#39;)<br>ax1.plot(aapl_df.loc[aapl_df.positions == -1.0].index, <br>         aapl_df.Close[aapl_df.positions == -1.0],<br>         &#39;v&#39;, markersize=10, color=&#39;r&#39;)<br>plt.legend([&#39;Close&#39;, &#39;EMA Short&#39;, &#39;EMA Long&#39;, &#39;Buy&#39;, &#39;Sell&#39;])<br>plt.title(&#39;AAPL EMA Crossover&#39;)</pre><p>And here is the resulting graph:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wSVmeOhf-k6xx1qQwKSkhg.png" /></figure><p>Hopefully you found this helpful. <a href="https://gist.github.com/financial-python/d1a085d1f87c7d8aee4d935631f02e91">Here is a link to the gist if you would like</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96ecd22ae252" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to get trending stock tickers from Reddit using Praw and Python]]></title>
            <link>https://medium.com/@financial_python/how-to-get-trending-stock-tickers-from-reddit-using-praw-and-python-1fccc7f06748?source=rss-3f9596d610ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/1fccc7f06748</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[reddit]]></category>
            <category><![CDATA[praw]]></category>
            <dc:creator><![CDATA[Financial Python]]></dc:creator>
            <pubDate>Sun, 12 Mar 2023 20:46:54 GMT</pubDate>
            <atom:updated>2023-03-16T13:56:30.639Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R18xG7rKLRVXDZJkBwLfVQ.png" /></figure><p>Reddit is a popular social media platform where users can post and discuss various topics, including finance and stocks. In recent years, Reddit has become a significant source of information for stock traders and investors. Subreddits such as “wallstreetbets,” “stocks,” “investing,” and “StockMarket” have become go-to resources for market insights and investment advice. In this article, we will explore how to use Python and the <strong>PRAW (Python Reddit API Wrapper)</strong> library to extract data from these subreddits and determine which stock tickers are being mentioned most frequently.</p><p>Before getting started, you will need to install the PRAW package:</p><pre>pip install praw</pre><h3>Getting Started</h3><p>First, we need to create a Reddit account and get an API key to access the Reddit API. Once you have created an account, you can obtain an API key by following these steps:</p><ol><li>Go to <a href="https://ssl.reddit.com/prefs/apps/">https://ssl.reddit.com/prefs/apps</a></li><li>Scroll down to “Developed Applications” and click “Create App”</li><li>Choose “Web app” and give your app a name and description.</li><li>Set “About url” and “Redirect uri” to “<a href="http://localhost:8000/">http://localhost:8000</a>&quot;</li><li>Click “Create app” and copy the “client_id” and “client_secret” values. (client_id will be right under your app name)</li></ol><p>Once you have the API key, you can start coding.</p><h3>Extracting Data from Reddit</h3><p>The PRAW library provides a simple interface to extract data from Reddit. To use PRAW, you need to create an instance of the Reddit class and pass your API key to it. Here’s how you can create a Reddit instance:pythonCopy code</p><pre>import praw<br><br>reddit = praw.Reddit(<br>    client_id=&quot;your_client_id&quot;,<br>    client_secret=&quot;your_client_secret&quot;,<br>    username=&quot;your_reddit_username&quot;,<br>    password=&quot;your_reddit_password&quot;,<br>    user_agent=&quot;your_user_agent&quot;,<br>)</pre><p>In this example, we pass the “client_id” and “client_secret” values that we obtained earlier to the Reddit constructor. We also set “username” and “password” to our Reddit account credentials. Finally, we set the “user_agent” to a custom string that identifies our script to Reddit. This can be anything we want.</p><p>Now that we have a Reddit instance, we can extract data from subreddits. To extract data from a subreddit, you need to create an instance of the Subreddit class and pass the subreddit name to it. Here’s an example:</p><pre>subreddit = reddit.subreddit(&quot;wallstreetbets&quot;)</pre><p>In this example, we create a Subreddit instance for the “wallstreetbets” subreddit. Because we don’t want to just check one subreddit, we will make a list of subreddits and loop through them:</p><pre>subreddits_to_parse = [&#39;wallstreetbets&#39;, &#39;stocks&#39;, &#39;investing&#39;, &#39;StockMarket&#39;]<br><br>#loop through the subreddits<br>for sub in subreddits_to_parse:<br><br>  #create instance of the subreddit class<br>  subreddit_instance = reddit.subreddit(subreddit)<br>  <br>  #sort by hot and get the most recent 50 submissions<br>  submissions = reddit.subreddit(subreddit_instance).hot(limit=50):</pre><p>Now you will have a list of Submission type objects. You can find more about the PRAW Submission class here: <a href="https://praw.readthedocs.io/en/stable/code_overview/models/submission.html">https://praw.readthedocs.io/en/stable/code_overview/models/submission.html</a></p><h3>Find Stock Tickers from Data</h3><p>At this point, you can print out the title and comments of a submission and see what it contains:</p><pre>for submission in submissions:<br>  print(f&quot;submission title: {submission.title}&quot;)<br><br>  #we can also look through the comments to see what words they contain:<br>  for top_level_comment in comments[:1]:<br>    print(f&quot;top_level_comment: {top_level_comment}&quot;)</pre><p>The comments here are an instance of the <a href="https://praw.readthedocs.io/en/stable/code_overview/models/comment.html">PRAW Comment</a> class</p><p>An example title or comment might be “What are your thoughts on TSLA?”. This contains the stock ticker for TESLA INC., and that is what we would want to parse.</p><p>To do this, we would need to split the title into words, and store each word in a list. Our logic would currently look like this:</p><pre>subreddits_to_parse = [&#39;wallstreetbets&#39;, &#39;stocks&#39;, &#39;investing&#39;, &#39;StockMarket&#39;]<br><br>#list to contain all of the words in a submission title or comment<br>word_collection = []<br><br>#loop through the subreddits<br>for sub in subreddits_to_parse:<br><br>  #create instance of the subreddit class<br>  subreddit_instance = reddit.subreddit(sub)<br>  <br>  #sort by hot and get the most recent 50 submissions<br>  submissions = subreddit_instance.hot(limit=50):<br><br>  for submission in submissions:<br>    print(f&quot;submission title: {submission.title}&quot;)<br>    title_words = submission.title.split()<br>    word_collection.extend(title_words)<br>  <br>    #we can also look through the comments to see what words they contain:<br>    submission.comments.replace_more(limit=0)  # flatten tree<br>    comments = submission.comments.list()  # all comments<br><br>    for top_level_comment in comments[:1]:<br>      print(f&quot;top_level_comment: {top_level_comment}&quot;)<br>      comment_words = top_level_comment.body.split()<br>      word_collection.extend(comment_words)</pre><p>Now that we have all of the words in a list, we need to loop through them and perform a few functions. First, we would need to remove any punctuation and Emojis. Going back to our example, the word list would look like this:</p><pre>word_collection = [&#39;What&#39;,&#39;are&#39;,&#39;your&#39;,&#39;thoughts&#39;,&#39;on&#39;,&#39;TSLA?&#39;]</pre><p>The problem here is that the TSLA symbol has a question mark, so we wouldn’t be able to properly match it.</p><p>Aside from the punctuation and Emojis, we want to check a few more things on each word to know if it is a stock ticker or not. We also want to check if the full word is capitalized. I know this may limit some tickers if they appear as ‘aapl’, but the Reddit standard is capitalizing ticker symbols. So we should get pretty close. We also do not want the word to contain any numbers. This could confuse words such as ‘EMA9’ and ‘SMA50’, which we do not want to consider as potential stock tickers.</p><p>The logic would look like this:</p><pre>potential_stock_symbols = [] #list to hold words that may be stock tickers <br><br>for word in word_collection:<br>  cleaned_word = remove_punc(word)<br>  cleaned_word = remove_emoji(cleaned_word)<br>  if cleaned_word.isupper() and not containsNumber(cleaned_word):<br>      potential_stock_symbols.append(cleaned_word)<br><br><br>&quot;&quot;&quot;<br>  checks each character in word to see if it is punctuation<br>  returns word without punctuation<br>&quot;&quot;&quot;<br>def remove_punc(word):<br>    test_punc_remove = [<br>        char for char in word if char not in string.punctuation]<br>    test_punc_remove_join = &#39;&#39;.join(test_punc_remove)<br>    return test_punc_remove_join<br><br>&quot;&quot;&quot;<br>  uses the regular expression (re) package to match and remove any emojis<br>  returns word without emojis<br>&quot;&quot;&quot;<br>import re<br><br>def remove_emoji(word):<br>    emoji_pattern = re.compile(&quot;[&quot;<br>                           u&quot;\U0001F600-\U0001F64F&quot;  # emoticons<br>                           u&quot;\U0001F300-\U0001F5FF&quot;  # symbols &amp; pictographs<br>                           u&quot;\U0001F680-\U0001F6FF&quot;  # transport &amp; map symbols<br>                           u&quot;\U0001F1E0-\U0001F1FF&quot;  # flags (iOS)<br>                           u&quot;\U00002702-\U000027B0&quot;<br>                           u&quot;\U000024C2-\U0001F251&quot;<br>                           &quot;]+&quot;, flags=re.UNICODE)<br>    return emoji_pattern.sub(r&#39;&#39;, word)<br><br>&quot;&quot;&quot;<br>  checks each character in word is a number<br>  returns True if number is found, False if there are no numbers<br>&quot;&quot;&quot;<br>def containsNumber(word):<br>    for character in word:<br>        if character.isdigit():<br>            return True<br>    return False</pre><p>Just using the logic we have right now, we would be left with TSLA in the potential_stock_symbols list, which is what we want. However, there is one more thing we are missing. There is a possibility that users may capitalize words that are not stocks. Words that do not contain numbers, that can be confused for stock symbols. Here is an example title of what I’m talking about:</p><p>“HOLY SHIT did you see the movement on TSLA today?”</p><p>Obviously, in this case, we do not want the words ‘HOLY’ and ‘SHIT’ to end up in our potential_stock_symbols list. So what we can do is create a list of words that we know are not stocks, and add standard Reddit terminology to it:</p><pre>KNOWN_NOT_STOCKS = [&#39;HOLY&#39;, &#39;SHIT&#39;, &#39;UPVOTE&#39;, &#39;DOWNVOTE&#39;, <br>&#39;YOLO&#39;, &#39;USA&#39;, &#39;MEME&#39;, &#39;GAIN&#39;, &#39;LOSS&#39;]</pre><p>Obviously, this list would be long and ever changing. You could also add any stocks that you do not want to track. In our logic, we can add a check to ensure the word is not in this list:</p><pre>potential_stock_symbols = [] #list to hold words that may be stock tickers <br><br>for word in word_collection:<br>  cleaned_word = remove_punc(word)<br>  cleaned_word = remove_emoji(cleaned_word)<br>  if cleaned_word.isupper() and not containsNumber(cleaned_word) and cleaned_word not in KNOWN_NOT_STOCKS:<br>      potential_stock_symbols.append(cleaned_word)</pre><p>What we are left with is a list of words that are potentially stock tickers.</p><p>We could even add some logic to determine how often the tickers appear in the list. Maybe we are checking thousands of submissions and want to only see the stocks that appear more than 50 times? To do that, we can use the Counter dict subclass from the python collections package:</p><pre>from collections import Counter<br><br>cnt = Counter(potential_stock_symbols)<br>trending_tickers = [k for k, v in cnt.items() if v &gt; 50]</pre><p>What you are left with is a list called ‘trending_tickers’, which contains all of the stock tickers that appear in the potential_stock_symbols list more than 50 times.</p><p>Hopefully you found this helpful. <a href="https://gist.github.com/financial-python/1fdd810266da876c274362fb046d7ebc">Here is a link to the gist if you would like</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1fccc7f06748" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>