<?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 IsEngineNear on Medium]]></title>
        <description><![CDATA[Stories by IsEngineNear on Medium]]></description>
        <link>https://medium.com/@IsEngineNear?source=rss-6489b67714cd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*P9g1Y0lNf4VGn__KM782Gg@2x.jpeg</url>
            <title>Stories by IsEngineNear on Medium</title>
            <link>https://medium.com/@IsEngineNear?source=rss-6489b67714cd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 21:34:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@IsEngineNear/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[Algorithmic Trading using Python, Python_Pandas, and Alpaca API — Part 4]]></title>
            <link>https://medium.com/@IsEngineNear/algorithmic-trading-using-python-python-pandas-and-alpaca-api-part-4-423eeeb125d0?source=rss-6489b67714cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/423eeeb125d0</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[investing]]></category>
            <category><![CDATA[stock-market]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[trading]]></category>
            <dc:creator><![CDATA[IsEngineNear]]></dc:creator>
            <pubDate>Wed, 23 Nov 2022 00:13:07 GMT</pubDate>
            <atom:updated>2022-11-23T00:13:07.051Z</atom:updated>
            <content:encoded><![CDATA[<h3><a href="https://medium.com/trading-data-analysis/algorithmic-trading-using-python-python-pandas-and-alpaca-api-part-3-14e8310e796d?source=your_stories_page-------------------------------------">Algorithmic Trading using Python, Python_Pandas, and Alpaca API — Part </a>4</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GF7MnSo64fv2mn7t13Qvaw.jpeg" /></figure><p>I want to thank everyone that has followed me and read my stories, I can’t believe the amount of support and responses I’ve received. Thank you!</p><p>If you want to read the previous posts please click on any of the following links:</p><ul><li><a href="https://medium.com/trading-data-analysis/algorithmic-trading-using-python-pandas-and-alpaca-api-part-1-61236754b02d">Part 1</a></li><li><a href="https://medium.com/trading-data-analysis/algorithmic-trading-using-python-pandas-and-alpaca-api-part-2-d065b47373ef">Part 2</a></li><li><a href="https://medium.com/trading-data-analysis/algorithmic-trading-using-python-python-pandas-and-alpaca-api-part-3-14e8310e796d">Part 3</a></li></ul><p>As always, if you have any comments or suggestions I am forever grateful for the feedback. I have changed my code several times due to the suggestions I’ve received writing these stories. I appreciate it, and my tiny <a href="https://medium.com/u/af642aaa17a0">Raspberry Pi 3</a> server appreciates it!</p><p>Continuing from <a href="https://medium.com/trading-data-analysis/algorithmic-trading-using-python-python-pandas-and-alpaca-api-part-3-14e8310e796d">part 3</a>, I will define and explain the functions used and paste the code for the whole script in this story.</p><p><strong>DISCLAIMER: </strong>This is not financial advice, nor am I teaching about the strategies used. This is to show how to use the strategies in a python script. This is about the methods and tools used in the script, I repeat this is not financial advice in any way, shape, or form.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d865d5aa5d6beabd8e866931bf5a127/href">https://medium.com/media/2d865d5aa5d6beabd8e866931bf5a127/href</a></iframe><p>I’ve made some changes to the original script based on some suggestions and responses from the previous stories. I will be going through every function in the script in order to make what each function does as clear as possible.</p><h3>Function getDateTime()</h3><p>This returns the string of the exact date and time from the machine.</p><h3>Function addToEmail()</h3><p>This appends the string parameter passed to the file “emailfile.txt”. This file will be read and the contents will be emailed to user of this script.</p><h3>Function dbconnection()</h3><p>Establishes a connection to the sqlite3 database created in the trading_data.py script.</p><h3>Function key_id()</h3><p>Selects the key id from the sqlite3 database where the base url equals the parameter baseURL. The function returns the key id selected from the database.</p><h3>Function secret_key()</h3><p>Selects the secret_key from the sqlite3 database where the base url equals the parameter baseURL. The function returns the secret key selected from the database.</p><h3>Function alpacaConnection()</h3><p>Establishes a connection to the <a href="https://medium.com/u/648225f0e33d">Alpaca</a> API associated to the keyID and the secretKey passed. Returns the connection. This is using the new alpaca-py API.</p><h3>Function getCurrentPositions()</h3><p>Using the <a href="https://medium.com/u/648225f0e33d">Alpaca</a> API established previously, this function returns the current account positions. This means it will return the stocks held and the quantity of shares held by the account.</p><h3>Function buyOrder()</h3><p>This starts by adding a string to signal the function is being executed. Using the new Alpaca-py API the function creates an order for the symbol <em>sym, </em>quantity <em>qty, </em>using the <a href="https://medium.com/u/648225f0e33d">Alpaca</a> api connection <em>apiConn. </em>Then on line 63, the function submits the order created previously. Finally the function ends by adding a string to the file that will be emailed indicating the function completed successfully. This function returns the market order created.</p><h3>Function sellOrder()</h3><p>This starts by adding a string to signal the function is being executed. Using the new Alpaca-py API the function creates an order for the symbol <em>sym, </em>quantity <em>qty, </em>using the <a href="https://medium.com/u/648225f0e33d">Alpaca</a> api connection <em>apiConn. </em>Then on line 75, the function submits the order created previously. Finally the function ends by adding a string to the file that will be emailed indicating the function completed successfully. This function returns the market order created.</p><h3>Function strategyStochOsc()</h3><p>This starts by adding a string to signal the function is being executed. The function then reads the CSV files created in the trading_data.py script and assigns it to the respective variables: <em>lowDatadf, highDatadf, closeDatadf. </em>The link to the complete <em>trading_data.py </em>script will be added to the end of this story, scroll all the way to the bottom of this story find it. I learned about this momentum indicator from <a href="https://www.alpharithms.com/stochastic-oscillator-in-python-483214/">alpharithms</a>. The function uses a “fast” 14 day period and a “slow” 3 day period using the <em>dataframe.rolling “min/max”</em> function to calculate the min/max for that <em>“fast/slow”</em> period. These new values called “nhighdf” and “nlowdf” are used to calculate the <em>k</em> value and the <em>d</em> value representing the “fast” line and “slow” line respectively. The “algorithm” part of algo-trading follows. If the <em>k</em> value is greater than 80, and the <em>d</em> value is greater than 80, and <em>k &lt; d</em> then the signal should be to <em>sell</em>. Alternatively, if the <em>k</em> value is less than 20, and the <em>d</em> value is less than 20, and <em>k &gt; d</em> then the signal should be to <em>buy</em>. <a href="https://medium.com/u/697c18011fda">Seeking Alpha</a> has some great articles regarding this momentum trading indicator. Ultimately, this function returns the last row of the <em>rsilastrow</em> data frame, which indicates whether to buy or sell based on the latest data.</p><h3>Function strategyRSI()</h3><p>This starts by adding a string to signal the function is being executed. Relative Strength Index (RSI) is a momentum indicator used in technical analysis. It measures the speed and magnitude of a security’s recent price changes to evaluate overvalued (&gt; 70) or undervalued (&lt; 30) conditions in the price of that security. The function starts by reading the CSV file for the closing data created by the <em>trading_data.py</em> script. The data is passed to the variable stockDatadf, a pandas dataframe. The difference is calculated using the previous day’s closing price, this is accomplished using the diff() function on the dataframe. The negative (&lt; 0) differences are trimmed using the clip() method given a minimum of 0. The positive (&gt; 0) differences are trimmed using the clip() method given a maximum of 0. I learned how to use the clip() method from <a href="https://www.geeksforgeeks.org/python-pandas-dataframe-clip/">GeeksforGeeks</a>. After trimming the values, an exponentially weighted mean (EWM) is calculated on the positive and negative values using a 15 day period on the closing price data. The relative strength (RS) data frame (rsdf) is then calculated by dividing the positive changes by the negative changes of the closing data. I then calculate the relative strength index (RSI) using the formula:</p><p>RSI = 100 — (100/(1+RS))</p><p>The ‘buy’ or ‘sell’ signal is generated by the following logic. If the RSI is ≥ 70 the signal is ‘sell’. If the RSI is &lt;70 and &gt;30, do nothing. If the RS is ≤ 30 the signal is ‘buy’. Finally the function returns a dataframe from the last date of the data with the ‘buy’ or ‘sell’ signals.</p><h3>Function strategyPPO()</h3><p>This starts by adding a string to signal the function is being executed. I learned about this strategy from <a href="https://medium.com/u/9809a7c9065e">Investopedia</a>. <a href="https://www.investopedia.com/terms/p/ppo.asp">Percentage Price Oscillator</a> (PPO) strategy is based on two signals just like in the stochastic oscillator strategy. This strategy focuses on the closing data rather than also taking into account the low and high data. The function starts by reading the CSV file for the closing data created by the <em>trading_data.py</em> script. The next step is to calculate the exponentially weighted mean (EWM) using the <em>short</em> and <em>long </em>period of the closing data, in this case 12 and 26 days respectively. The the PPO dataframe is created by subtracting the long EWM from the short EWM, multiplying it by 100 and dividing it by the long EWM. After the dataframe has been created, the signal line must be calculated. This is what is going to prompt a ‘buy’ or ‘sell’. The signal line is the EWM of the PPO dataframe over a 9 day period. If the PPO value is greater than the signal value, then the action will be to ‘buy’. If the PPO value is less than the signal value, then the action will be to ‘sell’. Finally this function returns a signal or action to be taken related to each stock analyzed, i.e. a ‘buy’ or ‘sell’.</p><p>These are the main strategies used for this script so far, I am always looking to add more strategies as I learn a bit more about them. Ultimately I would like to add a machine learning aspect to this script, but I am still studying this. I will go into the peripheral functions in the next article, I don’t want to make this so long that no one will read it. Thank you for your support and as promised, the full code for the <em>trading_data.py</em> script is below.</p><p>Please follow me for notifications of my next story, and again all comments are welcome.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/36458bb644d9a0816188e9e194e20423/href">https://medium.com/media/36458bb644d9a0816188e9e194e20423/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=423eeeb125d0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Algorithmic Trading using Python, Python_Pandas, and Alpaca API — Part 3]]></title>
            <link>https://medium.com/trading-data-analysis/algorithmic-trading-using-python-python-pandas-and-alpaca-api-part-3-14e8310e796d?source=rss-6489b67714cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/14e8310e796d</guid>
            <category><![CDATA[stock-market]]></category>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[IsEngineNear]]></dc:creator>
            <pubDate>Fri, 28 Oct 2022 04:13:10 GMT</pubDate>
            <atom:updated>2022-11-02T14:06:54.169Z</atom:updated>
            <content:encoded><![CDATA[<h3>Algorithmic Trading using <a href="https://medium.com/u/845dbbffa85e">Python</a>, <a href="https://medium.com/u/ab2427c95fde">Python_Pandas</a>, and <a href="https://medium.com/u/648225f0e33d">Alpaca</a> API — Part 3</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*mLuAZHSPYap6aQOtGEfoxA.png" /></figure><p>Thank you to everyone who has read the past stories, <a href="https://trading-data-analysis.pro/algorithmic-trading-using-python-pandas-and-alpaca-api-part-1-61236754b02d">part 1</a> and <a href="https://trading-data-analysis.pro/algorithmic-trading-using-python-pandas-and-alpaca-api-part-2-d065b47373ef">part 2</a>. I started this project because I love testing my knowledge and adding to it. This trading script is just the beginning, from this, I want to expand it to a web-based application using <a href="https://medium.com/u/845dbbffa85e">Python</a> Django (which I am learning) and keep adding strategies to it. Eventually, I will want to test these strategies separately, but concurrently, I will need to find a way to do this. As always, I am open to any comments or suggestions for the code or my writing. Please don’t hesitate to send me a message or write a note on the story.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/abb4f30bf178415241696980328a7fd1/href">https://medium.com/media/abb4f30bf178415241696980328a7fd1/href</a></iframe><p>Start by importing pandas, obviously to deal with the amount of data we gather in the script trading_data.py. The next3 lines are to import the email module to email the results of the script to myself. Then the <a href="https://medium.com/u/648225f0e33d">Alpaca</a>-py API to make the trades and get account data. Finally, I import SQLite to get the keyID and secret key for the alpaca account.</p><p>On to the main function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/942f74783b6b321a25dd427429b68430/href">https://medium.com/media/942f74783b6b321a25dd427429b68430/href</a></iframe><p>I start by writing to a file stored in a variable called emailfile. This is the file that stores the contents of the email the script sends to me at the end. The next step is to start the connection to the alpaca paper trading account. The closeDataFile variable stores the location of the file made in the previous part of this series. Then I start analyzing the data, calculating the Relative Strength Index and the Percentage Price Oscillator. I feed the data frames generated from strategyRSI and strategyPPO into the function getAllSignals to put together the list of all instruments with their respective ‘buy’, ‘sell’, and ‘none’ signals. On line 26 I get the <a href="https://medium.com/u/648225f0e33d">Alpaca</a> account information, then I generate the sell list based on the signals and the current positions since I am not shorting any stocks. This is only if the account has not been flagged for day trading. Once the sell orders are placed the script sleeps for 5 minutes to allow for all the orders to go through because then I can count on the cash from those sales to start buying. The topPrice variable stores the price limit for the proposed stocks to buy. I get the totalCash from the <a href="https://medium.com/u/648225f0e33d">Alpaca</a> account, meaning the total buying power. I feed that into the toBuy function, the instrument and signal list,and the price limit. If the account has more than $1.00, then I submit the buy orders on <a href="https://medium.com/u/648225f0e33d">Alpaca</a>. I then finish the script by emailing a file containing all the information the script did, and at what time to me.</p><p>In the next part, I will do a deep dive into the functions used in the main function. Please share, read, comment, and question the code or the story. I am always looking to be better.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14e8310e796d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/trading-data-analysis/algorithmic-trading-using-python-python-pandas-and-alpaca-api-part-3-14e8310e796d">Algorithmic Trading using Python, Python_Pandas, and Alpaca API — Part 3</a> was originally published in <a href="https://medium.com/trading-data-analysis">Trading Data Analysis</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Algorithmic Trading using python, pandas, and alpaca API — Part 2]]></title>
            <link>https://medium.com/trading-data-analysis/algorithmic-trading-using-python-pandas-and-alpaca-api-part-2-d065b47373ef?source=rss-6489b67714cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/d065b47373ef</guid>
            <category><![CDATA[stock-market]]></category>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[alpacafinance]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[IsEngineNear]]></dc:creator>
            <pubDate>Wed, 19 Oct 2022 19:25:12 GMT</pubDate>
            <atom:updated>2022-10-27T16:21:09.577Z</atom:updated>
            <content:encoded><![CDATA[<h3>Algorithmic Trading using python, pandas, and alpaca API — Part 2</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o6CX1NIURPflT6QLhH6O1Q.jpeg" /></figure><p>First, thank you to everyone who read <a href="https://medium.com/@IsEngineNear/algorithmic-trading-using-python-pandas-and-alpaca-api-part-1-61236754b02d">part 1</a> of this series. Second, please follow me to get an email for every story in this series.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2638630c24be156d2cd163a6f24eb043/href">https://medium.com/media/2638630c24be156d2cd163a6f24eb043/href</a></iframe><p>Picking up from the last story, I can start downloading stock data after verifying a successful connection to the <a href="https://alpaca.markets/">Alpaca</a> API.</p><p>After publishing the first story I got some suggestions from a few friends about the format. I took their suggestions, researched formatting best practices, and re-formatted the entire code. I split the main_trader.py code into two files: main_trader.py and trading_data.py.</p><p>Into the nitty gritty then.</p><p>The first part of the file is always going to be the imports.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fbb5c942bbfbd2d3b8aeb5bae62405fc/href">https://medium.com/media/fbb5c942bbfbd2d3b8aeb5bae62405fc/href</a></iframe><p>Then I create a getDateTime function to return a string of the current date and time. This function was created to be used throughout the file to mark the steps and how much time each one is taking. After this function, the downloadLists function is created to download a list of companies from the FTP (File Transfer Protocol) server “ftp.nasdaqtrader.com”.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7802ae292c7d369fe920acca8d899267/href">https://medium.com/media/7802ae292c7d369fe920acca8d899267/href</a></iframe><p><strong>Line 1–2: </strong>getDateTime function to return a string of the current date and time.</p><p><strong>Line 4: </strong>Create a downloadLists function that takes in a file parameter.</p><p><strong>Line 8–10: </strong>Set the FTP server variable listSite, the server allows anonymous logins with an email provided as the password. In trading_data_2.py the sitePass is the password that will be used to login into the server.</p><p><strong>Line 12,16: </strong>Start the connection to the server with the variables set above. On line 16, after a successful connection, change the working directory to Symboldirectory. This is where the desired files are stored.</p><p><strong>Line 18–21: </strong>Create the file passed to the function in the local current working directory and pass it to the variable listfile. Line 19 retrieves the file from the FTP server and writes it to the local file listfile. Line 20 closes the file, and line 21 disconnects from the FTP server.</p><p>The FTP server has two files of importance that are downloaded, nasdaqlisted.txt and otherlisted.txt.</p><p>Once the files are downloaded, the data in the files need to be stripped of excess information and cleaned. I do this in the getInstrumentList function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e9980ccb6bdaec05d54623767813895f/href">https://medium.com/media/e9980ccb6bdaec05d54623767813895f/href</a></iframe><p>The function takes 3 parameters: a database connection, a database cursor, and a list of files to analyze.</p><p>In line 6 I start by looping through the file list, I open the item in the list as a file, loop through every line, strip the line of white spaces, and split the line by the separator “|”. After stripping and splitting the line in the file I filter the first part of the line, which is the tickers, and filter the tickers by length. When I initially started writing this program, I learned that a ticker should not be longer than 4 letters. If it is longer, then the 5th letter denotes an issue with the company. The 5-letter tickers are not useful and will return NaN (Not a Number) when trying to pull stock data. The filtered symbols are then placed into the sqlite3 database ‘companies’. Then, a pandas dataframe is created from the table in the database and the function returns a pandas dataframe of the tickers.</p><p>Finally, a function (getClosingData) is created to download the stock data and create a CSV file for the closing data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ffe219362878049f4dd1d990aad9bb8/href">https://medium.com/media/4ffe219362878049f4dd1d990aad9bb8/href</a></iframe><p>The function takes 3 parameters: a list of companies, a start date, and an end date. The list of companies is generated in the getInstrumentList function. The start date is generated in the startDate function and returns a string with the format YYYY-MM-DD, the start date is the date when the data will start to be pulled from. The end date is the latest date to pull data from and is generated as a string in the function endDate in the same format as the start date.</p><p>On line 17, I use the DataReader function from pandas_datareader to pull data from “Yahoo” from the start date to the end date. The list of tickers generated from the previous function is a little over 9,000 tickers long so this function takes a little over 4 hours long to execute. Once the data is downloaded, it is written to a CSV file called ‘stock_data.csv’. Then the data is filtered to the closing data in line 19, getting rid of any columns with NaN. The close data is written to ‘close_data.csv’. The reason for creating this file is to be able to analyze it at a later time when the trades will take place using the file ‘main_trader.py’.</p><p>Full script below. Subscribe to get notifications when the next story is published.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a900fe075ea6443184bcee0b17fae04d/href">https://medium.com/media/a900fe075ea6443184bcee0b17fae04d/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d065b47373ef" width="1" height="1" alt=""><hr><p><a href="https://medium.com/trading-data-analysis/algorithmic-trading-using-python-pandas-and-alpaca-api-part-2-d065b47373ef">Algorithmic Trading using python, pandas, and alpaca API — Part 2</a> was originally published in <a href="https://medium.com/trading-data-analysis">Trading Data Analysis</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Algorithmic Trading using python, pandas, and alpaca API — Part 1]]></title>
            <link>https://medium.com/trading-data-analysis/algorithmic-trading-using-python-pandas-and-alpaca-api-part-1-61236754b02d?source=rss-6489b67714cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/61236754b02d</guid>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[algorithmic-trading]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[IsEngineNear]]></dc:creator>
            <pubDate>Thu, 13 Oct 2022 23:11:52 GMT</pubDate>
            <atom:updated>2022-10-21T11:32:41.468Z</atom:updated>
            <content:encoded><![CDATA[<h3>Algorithmic Trading using python, pandas, and alpaca API — Part 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BGrAiMbvwRMwooideKpFbg.jpeg" /></figure><p>I am a chemical engineer by day, an aspiring programmer at night (whenever my kids fall asleep). I read a story here in Medium in 2019 related to algorithmic trading using python. I had only dabbled in python up to that point, but I like a challenge so I figured that would be a great project. I don’t have a server, and I was not going to pay for one so I used a raspberry pi 3 with an ARM image of Ubuntu server. Anyway, I finished the script late 2019 right before the pandemic. It traded quite well, my paper trading account ended in the green before I abandoned the script, server, and account when the pandemic started. Skip to 2022, I am hoping to get back to programming and maybe get a certification or two to use it as a “side hustle”. I remembered the script I made in 2019 and thought about reviving it, luckily I still had the repository on @GitHub. I cloned the repository and opened the files but to my surprise I could not understand any of it. It was all in shorthand, because obviously I would always remember everything. So I decided to rewrite the script using some of the latest knowledge I gained. Anyway let’s get to the code.</p><p>I am by no means a professional software engineer, so if anyone has any suggestions on how to make this code more efficient please contact me through Medium or leave a comment. Also, this is not financial advice this is my own experience and my code.</p><h3>Alpaca</h3><p>First thing I had to do was make sure my account was still active. I logged into <a href="https://app.alpaca.markets/">Alpaca</a>, to the traders site and verified my account was still active and ready to start paper trading. I had reset my account back in 2020, so I had to get new API keys for the paper trading account.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*JBMLd70IDNefCMJPvsI1Ww.png" /><figcaption>Click View or it may say Generate Keys</figcaption></figure><p>I copied my keyID, secret key, and the base url. Then I created a sqlite3 database to pull these from whenever needed. But first these are all the imports needed for this script.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/513d60f0531f1e8715ff8d888bb7b11a/href">https://medium.com/media/513d60f0531f1e8715ff8d888bb7b11a/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c95a7853fe09eec88d40e5c13642f8c/href">https://medium.com/media/0c95a7853fe09eec88d40e5c13642f8c/href</a></iframe><p>In line 3, a printout of the date and time goes out to the console. This is more for debugging and efficiency purposes so that I know how long each function or section of the script took to execute. As you’ll see in a later part, some sections take a very long time since it is being done on a raspberry pi. The functions <em>key_id and secret_key </em>take a sqlite3 database cursor, the base URL for the trading account and returns the <em>keyID</em> and <em>secret key</em> for the <strong>Alpaca paper trading account</strong>. The reason for this is that once I am confident in this script I can switch the account to a live trading account by only changing the URL. Line 22 creates the API connection using the keyID, secret key, and base url. Line 24 gets the account status using the API connection. Finally we access the trading account status using <em>tradeAccount.status. </em>The last line logs the account status to the log file created for the script, this is for debugging purposes.</p><p>This is the first part of the journey to creating an algo trading python script using pandas. Stay tuned for the next part in the next few days.</p><p><strong>Edit: </strong>After getting some comments back from some friends on the code main_trader_alpaca.py I have edited the code to follow best practices, according to what I could find online. Also, the alpaca_trade_api is deprecated and being replaced with alpaca-py. See the edited code below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c1d0e5fae23f0b4a624d13a414f1953/href">https://medium.com/media/9c1d0e5fae23f0b4a624d13a414f1953/href</a></iframe><p>The overall imports for the script have changed since I split the file in two parts, one to get the close data and the other to analyze the data and submit the orders. Below are the overall imports for the data analysis file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a31b9e7ecd18060d8e1d36b630006720/href">https://medium.com/media/a31b9e7ecd18060d8e1d36b630006720/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61236754b02d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/trading-data-analysis/algorithmic-trading-using-python-pandas-and-alpaca-api-part-1-61236754b02d">Algorithmic Trading using python, pandas, and alpaca API — Part 1</a> was originally published in <a href="https://medium.com/trading-data-analysis">Trading Data Analysis</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>