<?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 Jachowski on Medium]]></title>
        <description><![CDATA[Stories by Jachowski on Medium]]></description>
        <link>https://medium.com/@Jachowskii?source=rss-16b7721ccfe1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ACwKgFpfwKbQJHyR3am92w@2x.jpeg</url>
            <title>Stories by Jachowski on Medium</title>
            <link>https://medium.com/@Jachowskii?source=rss-16b7721ccfe1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 22:12:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@Jachowskii/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 Define a Function in Python to Pick a Random Stock from the S&P500]]></title>
            <link>https://medium.com/@Jachowskii/how-to-define-a-function-in-python-to-randomly-pick-a-stock-from-the-s-p500-4ad937e914c4?source=rss-16b7721ccfe1------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ad937e914c4</guid>
            <dc:creator><![CDATA[Jachowski]]></dc:creator>
            <pubDate>Fri, 01 Jul 2022 09:44:07 GMT</pubDate>
            <atom:updated>2022-07-04T10:03:18.545Z</atom:updated>
            <content:encoded><![CDATA[<p>Define a function to randomly pick (without repetition) a stock from the S&amp;P500</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AX8stjiFqP5QQdTnn_ohnA.jpeg" /></figure><p>Let’s suppose you have created a <strong>trading strategy</strong> and you tested it on a <em>specific </em>stock on which the strategy performed brilliantly. First steps done, good for you, buddy!</p><p>At this point, you need to see if the strategy would show good results on other stocks too. In this sense, you have some paths to follow, one of them concerns the possibility to <strong>test your strategy on random stocks. </strong>In this way, you <strong>avoid mental biases</strong>, such as the confirmation bias and, in addition to that, you have the chance to randomly <strong>get stocks subject to a constrain</strong>, for example you could import only those stocks on which your strategy would produce at least <em>n</em> signals in a specific period.</p><p>Let’s see how.</p><p>Basically, we’re going to:</p><ul><li>Read all tickers’ stocks belonging to the S&amp;P500 from <a href="https://en.wikipedia.org/wiki/List_of_S%26P_500_companies">Wikipedia</a>,</li><li>Store them in a list,</li><li>Randomly pick one of them,</li><li>Import the random stock data,</li><li>Store it in a dataset.</li></ul><p>Let’s get into code stuff!</p><h4>Import the Libraries</h4><p>We need four libraries for this operation:</p><ul><li><a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/"><strong>BeautifulSoup</strong></a><strong> </strong>to pull data out of HTML files,</li><li><a href="https://docs.python-requests.org/en/latest/"><strong>Requests</strong></a><strong> </strong>to grab the source code from Wikipedia’s page,</li><li><strong>YahooFinance </strong>to get stock data and</li><li><strong>Random</strong> to generate <a href="https://www.pcmag.com/encyclopedia/term/pseudo-random-numbers">pseudo-random numbers</a>.</li></ul><p>If you have never installed them, copy and paste the following code:</p><pre>pip install beautifulsoup4<br>pip install requests<br>pip install yfinance<br>pip install random</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6eQ43tAWIv8KteCGLKTa8Q.jpeg" /></figure><p>After that, we can import them. Said and done:</p><pre>import bs4 as bs<br>import requests<br>import yfinance as yf<br>from random import randrange </pre><h4>Get S&amp;P500 Tickers from Wikipedia</h4><p>As stated before, we firstly need to import S&amp;P500 data from Wikipedia and store the tickers of those 500 stocks in a list. Here it is how:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d121576c3eaaef4460d767c43d13fc33/href">https://medium.com/media/d121576c3eaaef4460d767c43d13fc33/href</a></iframe><p>Basically, in line 5 we visit the <a href="https://en.wikipedia.org/wiki/List_of_S%26P_500_companies">Wikipedia </a>page related to the components of the S&amp;P500. In line 6, we create a BeautifulSoup object that parses HTML the way a web browser does. In the 7th line, we find the table we’re looking for, i.e. the Wikipedia table that contains S&amp;P500 stocks’ data. After that, from line 11 to line 13, we create a for loop iterating over the table, focusing on the left column of the table, that is Symbol, through which we import those symbols (MMM, AOS, ABT, etc.) and store them into the list tickers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*baOWKrnQmWBg1c1YdpoKmw.png" /></figure><p>In line 16, we perform a data cleaning operation: each symbol was imported as a string with the new line character (\n), so we replace it with the empty space (’’).</p><p>Great then, 50% of work done!</p><p><strong>Note: </strong>If you are interested in getting all S&amp;P500 stock data, I recommend you ro read <a href="https://wire.insiderfinance.io/how-to-get-all-stocks-from-the-s-p500-in-python-fbe5f9cb2b61">this article</a> I wrote.</p><h4>Randomly Select a Stock</h4><p>Now, we have to define a function that is able to randomly select one of those symbols, and we just need 3 lines of code. Here it is:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc0ec653e7232a2ceae1ee8bbaef6e46/href">https://medium.com/media/cc0ec653e7232a2ceae1ee8bbaef6e46/href</a></iframe><p>In line 4, we apply the function we have created before, i.e. get_tickers(). Then, in line 5, we exploit the randrange() function: randrange basically returns <em>a random number</em> <em>from a specified range </em>which, in our case, corresponds to the length of the list in which we have stored the 500 tickers. Lastly, we select <em>a random ticker </em>through list indexing. The function will then return the random ticker selected.</p><p>Here, as said before, we are randomly picking a stock <strong>without repetition </strong>(or<strong> without replacement</strong>), implying that each stock may be chosen only once. However, in the <strong>Note* </strong>below, it is showed how to replicate such a random experiment.</p><p>The last step concerns the stock data import. Data are imported from <strong>Yahoo Finance </strong>in a very concise way:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/17d97b52225b7db656f8a73bde6a6f68/href">https://medium.com/media/17d97b52225b7db656f8a73bde6a6f68/href</a></iframe><p>Inside the function yfinance.download() the first argument we pass is the random_picker() that, again, returns a random ticker as a string. Then, the other two arguments concern the time period, that is the start date and the end date: here, we chose 20 years of data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*CdUXZlOQB0akabGIivZaVw.png" /></figure><p>Let’s find out which stock we have imported…</p><pre>print(‘\nThe stock randomly picked is ‘ + str(random_picker()))</pre><p>Drrrrrrrrrrrrrrrum roll…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*Du6p-j4RioAdSFamF1uZag.png" /></figure><p>Alaska Air Group, whose ticker is in fact ALK.</p><p><strong>Note*:</strong> If you want <strong>to replicate the random experiment</strong> so that the same stock is always chosen you just need to set the seed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*67qdUnD3vFsanCMcNnCytw.png" /></figure><p>Now, the seed 10 is “associated” with the ticker ALK.</p><p>In the following script it is showed how it is possible to enrich a basic function as the random_picker() one is:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c96a9cf1e49ee5e5d399647fe19856ad/href">https://medium.com/media/c96a9cf1e49ee5e5d399647fe19856ad/href</a></iframe><p>Basically, I apply a trading strategy I have created — the so-called Hammer Swing Strategy — and I only take into consideration 10 stocks amongst the 500 of the S&amp;P on which the strategy produces <em>at least</em> 20 signals (lines 26–30).</p><p>That’s all for this article. Hope it will be useful for many of you as it was for me. If you need clarification or you have advice, feel free to contact me:</p><p><a href="https://t.me/Jachowksi">Jachowski</a></p><p>Cheers 🍻</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ad937e914c4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Get All Stocks from the S&P500 in Python]]></title>
            <link>https://wire.insiderfinance.io/how-to-get-all-stocks-from-the-s-p500-in-python-fbe5f9cb2b61?source=rss-16b7721ccfe1------2</link>
            <guid isPermaLink="false">https://medium.com/p/fbe5f9cb2b61</guid>
            <category><![CDATA[stocks]]></category>
            <category><![CDATA[import]]></category>
            <category><![CDATA[algorithmic-trading]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[sp500]]></category>
            <dc:creator><![CDATA[Jachowski]]></dc:creator>
            <pubDate>Sun, 24 Apr 2022 14:36:20 GMT</pubDate>
            <atom:updated>2022-04-30T17:15:37.027Z</atom:updated>
            <content:encoded><![CDATA[<p>Get all stocks from the S&amp;P500 in less than a minute</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*F1Rm0sZMdF_5ee_xsieKTw.jpeg" /></figure><p>Look how many people. Just imagine how much<strong> time</strong> would you spend in identifying each of them and storing their names in a dataset. I don’t know what we could do with them, but for stocks, there’s a very concise <strong>solution</strong>.</p><p>Basically, we’re going to:</p><ul><li>Read all tickers’ stocks belonging to the S&amp;P500 from <a href="https://en.wikipedia.org/wiki/List_of_S%26P_500_companies">Wikipedia</a>,</li><li>Store them in a list,</li><li>Download each stock from Yahoo Finance in less than a minute and</li><li>Save all data in a Pandas dataframe.</li></ul><p>Let’s get into code stuff!</p><h4>Import the Libraries</h4><p>We need four libraries for this operation:</p><ul><li><a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/"><strong>BeautifulSoup</strong></a><strong> </strong>to pull data out of HTML files,</li><li><a href="https://docs.python-requests.org/en/latest/"><strong>Requests</strong></a><strong> </strong>to grab the source code from Wikipedia’s page,</li><li><strong>YahooFinance </strong>to get stock data and</li><li><strong>Datetime</strong> to deal with datetime objects.</li></ul><p>If you have never installed them, copy and paste the following code:</p><pre>pip install beautifulsoup4<br>pip install requests<br>pip install yfinance<br>pip install datetime</pre><p>After that, we can import them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*yQ6Z2wA-kn19FqMpuw0INw.jpeg" /></figure><p>Said and done:</p><pre>import bs4 as bs<br>import requests<br>import yfinance as yf<br>import datetime</pre><h4>Get S&amp;P500 Tickers from Wikipedia</h4><p>Here it is:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/69dcbabb42a53bb03e88477acd8ae617/href">https://medium.com/media/69dcbabb42a53bb03e88477acd8ae617/href</a></iframe><p>In the first line, we visit the Wikipedia page we’re interested in.</p><p>In the second line, we create a BeautifulSoup object that parses HTML the way a web browser does.</p><p>In the third line, we find the table we’re looking for, i.e. the Wikipedia table containing S&amp;P500 stocks data.</p><p><strong>Note:</strong> In Wikipedia, all table contents are under the class <em>‘wikitable sortable’ : </em>so we have to specify it in order to move through a table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/759/1*RJoa2HfQa6d0wrlyDRP_9A.png" /></figure><p>At this point, we create an empty list and populate it using a for loop by which we iterate through the table:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/387bd6fd5089789e2a90102fa64ead6c/href">https://medium.com/media/387bd6fd5089789e2a90102fa64ead6c/href</a></iframe><p>For each row (tr stands for <em>table row</em>), after the header row — that’s why we’re looping with [<strong>1</strong>:] — we grab the ticker and append it to the list.</p><p>We stored all symbols in the list tickers. Let’s have a look.</p><pre>print(tickers)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*xdQVfLR5r-mS3PKuUphPAg.png" /></figure><p>Every symbol was imported and stored with the new line character (\n): we need to remove it. Something easy with list comprehension:</p><pre>tickers = [s.replace(&#39;\n&#39;, &#39;&#39;) for s in tickers]</pre><p>Let’s check again.</p><pre>print(tickers)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*qrw36qdw58Hbpqz_SEJMlA.png" /></figure><p>Much better, uh?</p><h4>Import S&amp;P500 Stocks</h4><p>After setting the time period, i.e. the start date and the end date, we can easily download all stocks with yfinance.</p><pre>start = datetime.datetime(2020, 1, 1)<br>end = datetime.datetime(2022, 1, 1)<br>data = yf.download(tickers, start=start, end=end)</pre><p><strong>Note: </strong>It can happen that in output you receive such a message:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/1*3B10PHDqK5r8P_6reCuC0g.png" /></figure><p>Nothing deadly serious. It simply means that those stocks are not included in the dataframe.</p><p>Let’s move forward. data is a Pandas DataFrame. If we inspect it, that’s what it looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F28rX7-OyAHg_pxELn-_gw.png" /></figure><p>It’s not beautiful as the soup we made before. But with just two lines of code it could be much better:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b4a0f954016836ed08d65f54cd399d51/href">https://medium.com/media/b4a0f954016836ed08d65f54cd399d51/href</a></iframe><p>The basic operation is .stack() that stacks the column headers into a multiindex. This multiindex is then converted to columns (reset_index()) which then get proper names. After that, data are sorted by Symbol and Date. Finally, we set Date as the index.</p><p>Here is how the dataframe looks now:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*nRoSzS6KuZVqNNR3f4fbSw.png" /></figure><p><strong>Way better</strong>. Now, we have symbols on rows and for each date are indicated the daily values. If you scroll down, once you reach the end date, i.e. 2021–12–31, you find the second stock, followed by all others.</p><p>In case you’re going to re-use the same dataframe again and again, be sure to save it in a csv file:</p><pre>df.to_csv(&#39;sp500_stocks.csv&#39;)</pre><p>That’s all for this article. Hope it will be useful for many of you as it was for me. If you need clarification or you have advice, feel free to contact me:</p><p><a href="https://t.me/Jachowksi">Jachowski</a></p><p>Cheers 🍻</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fbe5f9cb2b61" width="1" height="1" alt=""><hr><p><a href="https://wire.insiderfinance.io/how-to-get-all-stocks-from-the-s-p500-in-python-fbe5f9cb2b61">How to Get All Stocks from the S&amp;P500 in Python</a> was originally published in <a href="https://wire.insiderfinance.io/">InsiderFinance Wire</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Build a Backtesting Engine in Python Using Pandas]]></title>
            <link>https://medium.com/@Jachowskii/how-to-build-a-backtesting-engine-in-python-using-pandas-bc8e532a9e95?source=rss-16b7721ccfe1------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc8e532a9e95</guid>
            <category><![CDATA[backtesting]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[algorithmic-trading]]></category>
            <category><![CDATA[trading-system]]></category>
            <dc:creator><![CDATA[Jachowski]]></dc:creator>
            <pubDate>Fri, 22 Apr 2022 16:43:15 GMT</pubDate>
            <atom:updated>2022-05-07T00:56:45.517Z</atom:updated>
            <content:encoded><![CDATA[<p>A simple way to build an easily scalable backtesting engine to test your Trading Systems in Python using only Pandas and Numpy</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rhe4px2Vs_kdXASpJgjRYQ.jpeg" /></figure><p><a href="https://www.investopedia.com/terms/b/backtesting.asp"><strong>Backtesting</strong></a> is a crucial step in designing your <strong>Trading Systems</strong>, I would say that it is <em>the </em>crucial step given that it assesses the viability of your strategies.</p><p>Just imagine: Earth, 2050. The first flying car ever is released on the markek but it’s never been tested. Would you buy it? I think (hope) no.</p><p>This simple analogy intends to highlight the importance of backtesting: before investing through a whatever <strong>algorithmic model</strong>, test it, again and again, even if your favourite financial guru on YouTube says that a certain strategy will provide a 100% return in less than a year.</p><h4>Believe in what you see, not in what they tell you to see.</h4><p>In this sense, it’s not the best idea to use a pre-built engine for backtesting using libraries such as <strong>Backtrader</strong> for many reasons: you can’t neither properly see what is going on in there nor modify it as much as you want.</p><p>Remember, the second principle of the <a href="https://peps.python.org/pep-0020/">Zen of Python</a> states that <strong>“Explicit is better than implicit”</strong>. If you can build explicit functions by your own instead of using black-box pre-built ones, go for it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/997/1*0yEmMn468-AP-0XEhbHpqQ.png" /></figure><p>Oh, and the third principle says that “<strong>Simple is better than complex</strong>”. Let’s see how easily you can backtest your strategies with Pandas.</p><h4>The Idea</h4><p>This is what we’re going to do:</p><ol><li>Import the libraries</li><li>Import stock data</li><li>Define a trading strategy</li><li>Define a market position function</li><li>Define a backtesting function</li></ol><p>Let’s get into code stuff!</p><h4>1. Import the Libraries</h4><p>Let’s import the three libraries we need. Said and done:</p><pre>import numpy as np<br>import pandas as pd<br>import yfinance as yf</pre><h4>2. Import Stock Data</h4><p>Let’s download 20 years of Amazon (ticker AMZN) stock data.</p><pre>amzn = yf.download(&#39;AMZN&#39;, &#39;2000-01-01&#39;, &#39;2020-01-01&#39;)</pre><h4>3. Define a Trading Strategy</h4><p>In this case, we’re going to test one of the most popular strategies: the <a href="https://www.investopedia.com/articles/active-trading/052014/how-use-moving-average-buy-stocks.asp"><strong>Double Moving Averages Crossover</strong></a>.</p><p>First of all, we have to define two Simple Moving Averages. That’s how:</p><pre>def SMA(array, period):<br>    return array.rolling(period).mean()</pre><p>That is, this function has three arguments:</p><ul><li><em>dataset</em> is the dataframe that contains the stock data we previously imported (AMZN stock data),</li><li><em>array </em>is the series we will apply the function on (Close Prices) and</li><li><em>period </em>is the lenght of our moving averages (e.g. 14 and 200 days).</li></ul><p>The function returns a <a href="https://www.geeksforgeeks.org/python-pandas-dataframe-rolling/#:~:text=rolling()%20function%20provides%20the,desired%20mathematical%20operation%20on%20it.">sliding window</a> (.rolling()) of a desired lenght ((period)) of an array (array) on which it is computed the arithmetic mean (.mean()).</p><p>Let’s define the two moving averages we will use. The first is the shorter-term (14 days), while the second is the longer-term (200 days):</p><pre>sma14 = SMA(amzn[&#39;Close&#39;], 14)    <br>sma200 = SMA(amzn[&#39;Close&#39;], 200)</pre><p>This is what we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*K21fwxkz3RCRBzJCOzsbag.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*UW96PbQ8kgEQqtiFYLxGRQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/230/1*tub_l5o94crIjDAp5lVZFg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/233/1*hE-emYMSU0LQSoNTLFC2eQ.png" /></figure><p>Now, we need to define the <strong>entry rules</strong> and <strong>exit rules</strong> of our strategy, which are the <em>crossover</em> and the <em>crossunder</em>, respectively.</p><p>In other words, we get an:</p><ul><li><strong>entry </strong>(buy)<strong> signal </strong>when<strong> </strong>the shorter-term moving average (14 days) crosses <em>above</em> the lower-term moving average (200 days)</li><li><strong>exit </strong>(sell)<strong> signal</strong> when<strong> </strong>the shorter-term moving average (14 days) crosses <em>below </em>the longer-term (200 days).</li></ul><pre>def crossover(array1, array2):<br>    return array1 &gt; array2</pre><pre><br>def crossunder(array1, array2):<br>    return array1 &lt; array2</pre><p>And after that we assign <em>crossover </em>to the enter rules and <em>crossunder </em>to the exit rules:</p><pre>enter_rules = crossover(sma14, sma200)</pre><pre>exit_rules = crossunder(sma14, sma200)</pre><p>Basically, we obtain two boolean series (True or False):</p><ul><li>enter_rules is True whenever sma14 &gt; sma200 while</li><li>exit_rules is True whenever sma 14 &lt; sma200.</li></ul><p>Hence, looking at the images above of the series sma14 and sma200, we expect to find False on the enter_rules on the 13th of October, 2000, since 33.5714 &lt; 51.9385, i.e. sma14 &lt; sma200.</p><p>Let’s check for it:</p><pre>check = enter_rules[enter_rules.index == &#39;2000-10-13&#39;]<br>print(check)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*YocrdhIZpF2A_T1BoGLRLw.png" /></figure><p>This is the starting point.</p><p><strong>Now we fly</strong>. But not with that never tested flying car.</p><h4>4. Define a Market Position Function</h4><p>Here, we’re going to create a function that defines the ongoing trades: to achieve this, we will create a <strong>switch</strong> that:</p><ul><li><strong>turns on</strong> if enter_rules is True <em>and </em>exit_rules is False and</li><li><strong>turns off</strong> if exit_rules is True.</li></ul><p>Here it is the function:</p><pre>def marketposition_generator(dataset, enter_rules, exit_rules):<br>    <br>    dataset[&#39;enter_rules&#39;] = enter_rules<br>    dataset[&#39;exit_rules&#39;] = exit_rules<br>    <br>    status = 0<br>    mp = []<br>    for (i, j) in zip(enter_rules, exit_rules):<br>        if status == 0:<br>            if i == 1 and j != -1:<br>                status = 1 <br>        else:<br>            if j == -1:<br>                status = 0<br>        mp.append(status)<br>        <br>    dataset[&#39;mp&#39;] = mp<br>    dataset[&#39;mp&#39;] = dataset[&#39;mp&#39;].shift(1)<br>    dataset.iloc[0,2] = 0<br>    <br>    return dataset[&#39;mp&#39;]</pre><p>It takes three arguments:</p><ul><li><em>dataset</em> is the dataframe that contains the stock data we previously imported (AMZN stock data),</li><li><em>enter_rules </em>is the boolean series containing the entry signals and</li><li><em>exit_rules </em>is the boolean series containing the exit signals.</li></ul><p>On the first two rows we copy on our dataset the exit and the entry rules. status is the <strong>switch</strong> and<strong> </strong>mp is an empty list that will be populated with the resulting values of status.</p><p>At this point, we create a for loop with <a href="https://realpython.com/python-zip-function/#:~:text=Python&#39;s%20zip()%20function%20is,%2C%20sets%2C%20and%20so%20on.">zip</a> that works like a… ye, a zipper, enabling us to do a parallel iteration on both enter_rules and exit_rules simultaneously: it will return a single iterator object with all values finally stored into mp that will be:</p><ul><li>mp= 1 (<strong>on</strong>) whenever enter_rules is True <em>and </em>exit_rules is False and</li><li>mp= 0 (<strong>off</strong>) whenever exit_rules is True.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*RszurTnvNp2ALa1wu3RwKQ.jpeg" /></figure><p><strong>Note: </strong>in Python, True corresponds to 1 but here, in the if j == -1 statement related to the exit_rules, True is -1. Later on it will be clear the reason of that.</p><p>In the last three lines, we add mp to our dataset, we forward shift its values by one period so that the trade starts the day after we received the signal and in the last line we substitute the nan value, subsequent to the shift operation, with 0. The function returns the mp series.</p><h4>5. Define a Backtesting Function</h4><p>Last step. We’re close to the end, hang on!</p><p>First of all, we have to define some <strong>parameters</strong> such as:</p><ul><li><strong>COSTS</strong>: fixed costs per trade (i.e. transactions’ fee)</li><li><strong>INSTRUMENT</strong>: type of instrument (1 for stocks, 2 for futures, etc.)</li><li><strong>OPERATION_MONEY</strong>: initial investment</li><li><strong>DIRECTION</strong>: long <em>or</em> short</li><li><strong>ORDER_TYPE</strong>: type of order (market, limit, stop, etc.)</li><li><strong>ENTER_LEVEL</strong>: entry price</li></ul><pre>COSTS = 0.50<br>INSTRUMENT = 1 <br>OPERATION_MONEY = 10000<br>DIRECTION = &quot;long&quot;<br>ORDER_TYPE = &quot;market&quot;<br>ENTER_LEVEL = amzn[&#39;Open&#39;]</pre><p>We’re assuming that:</p><ul><li><strong>COSTS</strong>: every operation will cost us <em>50 cents</em>, 25 to buy and 25 to sell</li><li><strong>INSTRUMENT</strong>: the system will be tested on a <em>stock</em> (AMZN)</li><li><strong>OPERATION_MONEY</strong>: the initial capital is <em>10k dollars</em></li><li><strong>DIRECTION</strong>: the strategy will be tested for <em>long trades</em></li><li><strong>ORDER_TYPE</strong>: the strategy will process <em>market orders</em></li><li><strong>ENTER_LEVEL</strong>: the entry price corresponds to the <em>open price</em></li></ul><p>And here it is the best part:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/81adbe2186015c870876ac894a1c7ae9/href">https://medium.com/media/81adbe2186015c870876ac894a1c7ae9/href</a></iframe><p>Let’s analyze the function line by line.</p><p>From line 3 to line 5 we add the two boolean series and the market position function to the dataset.</p><p><strong>Note: </strong>In the previous note, I told you that everything would have been clear: in the lambda function of exit_rules, all values equal True are assigned to -1 while False values are assigned to 0. Thanks to that, marketposition_generator runs wonderfully.</p><p>From line 7 to line 12 we define <a href="https://www.investopedia.com/terms/m/marketorder.asp">market orders</a> for stocks:</p><ul><li>In lines 7–9 we define the entry_price: if the previous value of mp was zero and the present value is one, i.e. we received a signal, we open a trade at the open price of the next day;</li><li>In lines 10–12 we define number_of_stocks, that is the amount of shares we buy, as the ratio between the initial capital (10k) and the entry_price;</li></ul><p>In line 14 we forward propagate the value of the entry_price ;</p><p>In lines 16–17 we round number_of_stocks at the integer value and forward propagate its value as well;</p><p>In line 20 we associate the label &#39;entry&#39; to &#39;events_in&#39; every time mp moves from 0 to 1;</p><p>From line 22 to line 27 we define the long trades:</p><ul><li>In line 24 we compute open_operations, i.e. the profit;</li><li>In line 25 we adjust the previous computation of open_operations whenever we exit the trade: whenever we receive an exit signal, the trade is closed the day after at the open price. Here, <a href="https://www.investopedia.com/terms/r/rttc.asp">round turn costs</a> are included;</li></ul><p>From line 28 to line 33 we replicate for short trades what was said for long trades: to test <em>short trades </em>you just have to set DIRECTION = ‘short&#39;;</p><p>In line 35 we assign open_operations equal 0 whenever there is no trade in progress;</p><p>In line 36 we associate the label &#39;exit&#39; to &#39;events_out&#39; every time mp moves from 1 to 0, i.e. we receive an exit signal;</p><p>In lines 37–38 we associate the value of open_operations to operations only when we’re exiting a trade, otherwise nan: by doing so, it will be very easy to aggregate data;</p><p>In line 39 we define the equity_line for close operations and in line 40 it is defined the equity_line for open operations;</p><p>In line 42 we save the resulting dataset in a csv file.</p><p>Let’s call the function and inspect the results.</p><pre>COSTS = 0.50<br>INSTRUMENT = 1 <br>OPERATION_MONEY = 10000<br>DIRECTION = &quot;long&quot;<br>ORDER_TYPE = &quot;market&quot;<br>ENTER_LEVEL = amzn[&#39;Open&#39;]</pre><pre>trading_system = apply_trading_system(amzn, DIRECTION, ORDER_TYPE, ENTER_LEVEL, enter_rules, exit_rules)</pre><p>These are two <em>long trades</em> registered by the Trading System:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_4Z0QH6EO3beWChy5zlgxA.png" /></figure><p>To check if the Trading Strategy— the<strong> </strong>Double Moving Averages Crossover — produced profitable <em>long trades</em> in the time period considered for that stock, you can just digit:</p><pre>net_profit = trading_system[&#39;closed_equity&#39;][-1] - OPERATION_MONEY<br>print(round(net_profit, 2))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*4ua0TkU9kIxF2GGFVYLvLw.png" /></figure><p>A return of almost 500% in 20 years. Not suprising considered that Amazon stock increased by 2400% in those 20 years and we used a <em>trend-following </em>strategy.</p><p>That’all for this article. Hope you’ll find it helpful.</p><p>Let me know if you could be interested in seeing extensions of this backtesting engine, for example how to implement <em>limit orders</em>.</p><p>In case you need clarification or you have advices, feel free to contact me on Telegram:</p><p><a href="https://t.me/Jachowksi">Jachowski</a></p><p>Cheers 🍻</p><h4>Reference:</h4><p>Trombetta, Giovanni, <em>Strategie di Trading con Python, </em>Hoepli, 2020</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc8e532a9e95" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Get Stock Historical Data with Python in One Line of Code]]></title>
            <link>https://medium.com/@Jachowskii/get-stock-historical-data-with-python-in-one-line-of-code-491541c31403?source=rss-16b7721ccfe1------2</link>
            <guid isPermaLink="false">https://medium.com/p/491541c31403</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[import-stock]]></category>
            <category><![CDATA[one-line]]></category>
            <category><![CDATA[stock-market]]></category>
            <category><![CDATA[get-stock-data]]></category>
            <dc:creator><![CDATA[Jachowski]]></dc:creator>
            <pubDate>Sun, 10 Apr 2022 19:39:55 GMT</pubDate>
            <atom:updated>2022-04-11T06:36:28.404Z</atom:updated>
            <content:encoded><![CDATA[<p>Create a function to download whatever stock in your Python script</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s7Sc3JvYTPXE3hRnEbX_5Q.jpeg" /></figure><h4>“In God we trust, all others must bring data.”</h4><p>Every kind of <em>data analysis</em> starts with… guess what? Yeah buddy, <em>data</em>.</p><p>Once we get data, we can carry out any data analysis process we want. Moreover, data should be clean, well-ordered and complete, i.e. without <em>missing values</em>.</p><p>In this sense, when it comes to financial data, after years and years using it, I consider <strong>Yahoo Finance</strong> the most reliable <strong>free data source</strong> out there: you can easily get, especially if you use Python, both economical and financial data. In this article, we will focus on this second one.</p><p>Let’s get into code stuff!</p><h4>Import the Libraries</h4><p>Actually, we need only one library : yfinance, i.e. the Python library that gives you easy access to financial data available on Yahoo Finance.</p><p>If you have <em>not</em> installed yfinance, you can just copy and paste the following piece of code into your script:</p><pre>$ pip install yfinance --upgrade --no-cache-dir</pre><p>After that, we have to import yfinance in our script: yf is the acronym tipycally used for yfinance. Said and done:</p><pre>import yfinance as yf</pre><h4>Define the Function</h4><p>In order to download historical data related to a certain stock we <em>always </em>need two (or, better saying, three) elements:</p><ol><li>The ticker, and</li><li>The time period you want to focus on, i.e. the start date and the end date</li></ol><p>So let’s define a function that takes these two (three) elements as arguments:</p><pre>def stock_import(ticker, start_date, end_date):<br>    ticker = ticker<br>    start_date = start_date<br>    end_date = end_date</pre><p>Then, we simply have to use the <strong>Yahoo Finance API</strong> to get the data:</p><pre>stock = yf.download(ticker, start=start_date, end=end_date)</pre><p><strong>Note: </strong>the arguments must be passed as strings, i.e. in quotation marks!</p><p>Finally, we decide to make the function returns the dataset itself.</p><pre>return stock</pre><p>Here it is the <strong>complete code</strong>:</p><pre>import yfinance as yf</pre><pre>def stock_import(ticker, start_date, end_date):<br>    ticker = ticker<br>    start_date = start_date<br>    end_date = end_date<br>    <br>    stock = yf.download(ticker, start=start_date, end=end_date)<br>    <br>    return stock</pre><p>Now, we have a very simple and versatile function that can be used again and again! Let’s provide an example.</p><h4>Example</h4><p>Let’s import 30 years data for Apple stock (ticker ‘AAPL’).</p><p>The variable aapl will be a <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.html">pd.DataFrame</a> we can easily work with.</p><pre>aapl = stock_import(&#39;AAPL&#39;, &#39;1992-01-01&#39;, &#39;2022-01-01&#39;)</pre><p>Amongst our variables there will be the resulting dataset containing Apple data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*bmhmuXd7chDJlA1nmAX4NA.png" /></figure><p>And here it is the complete dataset! Pretty nice, uh?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*rH5JjzXeJ7MMCd9488THHQ.png" /></figure><p>That’s all for this article, hope you will find it helpful!</p><p>Cheers 🍻</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=491541c31403" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>