<?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 @amor71 on Medium]]></title>
        <description><![CDATA[Stories by @amor71 on Medium]]></description>
        <link>https://medium.com/@amor71?source=rss-e10d677bab73------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*gR1qFGq7YOeUodPPUnu99w.jpeg</url>
            <title>Stories by @amor71 on Medium</title>
            <link>https://medium.com/@amor71?source=rss-e10d677bab73------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 10:12:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@amor71/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[Are we Quantum Computers?]]></title>
            <link>https://amor71.medium.com/are-we-quantum-computers-c5e457fd31df?source=rss-e10d677bab73------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5e457fd31df</guid>
            <category><![CDATA[quantum-computing]]></category>
            <category><![CDATA[consciousness]]></category>
            <category><![CDATA[quantum-physics]]></category>
            <category><![CDATA[phylosophy]]></category>
            <category><![CDATA[existentialism]]></category>
            <dc:creator><![CDATA[@amor71]]></dc:creator>
            <pubDate>Sat, 04 Mar 2023 17:32:47 GMT</pubDate>
            <atom:updated>2023-03-04T17:32:47.546Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fzbSixHIJHnSrgGw" /><figcaption>Photo by <a href="https://unsplash.com/@reims?utm_source=medium&amp;utm_medium=referral">Karlis Reimanis</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Science avoids the question of “What is Consciences?”; this question and other existential questions are left to Philosophers and meta-physics. Religion avoids these questions, too.</p><p>One way to tackle the question and bind several disciplines is to think of our brains as Quantum Computers and model our free-will choices as <a href="https://en.wikipedia.org/wiki/Quantum_decoherence">quantum decoherence</a>. In other words, our choices “collapse” the multi-verse into our perceived reality.</p><p>There needs to be scientific proof for this <a href="https://en.wikipedia.org/wiki/Analytic_philosophy">Analytic</a> approach to <a href="https://en.wikipedia.org/wiki/Existentialism">Existentialism</a>. Neither is it proved that it is possible to choose a collapse of a wave function. Following this thinking, our choices may be more random than we think.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5e457fd31df" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How-to setup your Trading Platform — Part I]]></title>
            <link>https://amor71.medium.com/how-to-setup-your-trading-platform-part-i-64ea8ea828bb?source=rss-e10d677bab73------2</link>
            <guid isPermaLink="false">https://medium.com/p/64ea8ea828bb</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[algorithmic-trading]]></category>
            <category><![CDATA[crypto]]></category>
            <dc:creator><![CDATA[@amor71]]></dc:creator>
            <pubDate>Fri, 21 Jan 2022 20:12:10 GMT</pubDate>
            <atom:updated>2022-01-21T20:12:10.946Z</atom:updated>
            <content:encoded><![CDATA[<h3>How-to setup your Trading Platform — Part I</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MZ9uc3TaM24Ovpez" /><figcaption>Photo by <a href="https://unsplash.com/@jeremybezanger?utm_source=medium&amp;utm_medium=referral">Jeremy Bezanger</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>There are quite a few articles on trading ideas and algorithmic samples. Sadly, there are only a handful of step-by-step guides on creating an automated/autonomous trading platform. I am trying to fill this avoid with this short series of articles. By the end of this, you should have a good idea of what the &quot;retail&quot; algo-trading platform looks like how to set it up yourself.</p><p>I am going to break the series into two parts:</p><ul><li>Part I: prerequisite, high-level setup details, setup details, backtesting a Crypto strategy.</li><li>Part II: Completing the setup. Autonomous trading on a paper account, Moving to production.</li></ul><p>The target audience of this series are developers with an understanding of algo-trading basics, intermediary knowledge of Python, and adventures flare for &quot;DevOps.&quot;</p><p>I&#39;m going to use <a href="https://github.com/amor71/LiuAlgoTrader">LiuAlgoTrader</a>, as the backtesting and trading platform of choice. However, many of the concepts apply to other platforms, as well as your home-grown codebase.</p><p>If you haven&#39;t done so, I recommend reading and trying the previous series: <a href="https://amor71.medium.com/liualgotrader-part-i-3334a27edd4b">LiuAlgoTrader Part I </a>(background) and <a href="https://amor71.medium.com/liualgotrader-part-ii-putting-it-all-together-1d447650808b">LiuAlgoTrader Part II</a> (example).</p><p>For this guide, we&#39;ll be using a simple Crypto trading algo that had excellent returns in 2021:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*ce7eBgPwIg6Um5tf6rCVlw.png" /><figcaption><strong>Fig 1</strong> Crypt Trading using SMA &amp; MACD</figcaption></figure><p>You can find details of the tear sheet <a href="https://amor71.github.io/LiuAlgoTrader/ts-crypto-v1-Jan-21-Jan-22.html">here</a> and the code sample <a href="https://github.com/amor71/trading_strategies/blob/master/strats/crypto.py">here</a>.</p><p>Disclaimer: The material in this article has no regard to the specific investment objectives, financial situation, or particular needs of any user. This article is presented solely for informational and entertainment purposes. It is not to be construed as a recommendation, solicitation, or an offer to buy or sell / long or short any securities commodities.</p><p>Before we start:</p><ol><li>Make sure you have registered with <a href="https://alpaca.markets/">Alpaca.Markets</a> obtained API Keys.</li><li>You have a local setup that includes: Python 3.9+, an installed design of <a href="https://github.com/amor71/LiuAlgoTrader">LiuAlgoTrader</a>, and have a local script w/ the relevant environment variables. If you do not have this setup ready, please refer to the links at the head of this article.</li><li>Decide where to host your automated trading platform. For the past couple of years, I have been running my setup on <a href="https://console.cloud.google.com/">Google Cloud Platform</a> (GCP for short), and I will be using it in the examples. However, you may choose any cloud or on-premise setup. As long as you have the account/keys set up, you should be good to go. If you decide to use GCP, sign up and go through the billing steps.</li><li>[Optional] Depending on your local hardware setup, search online how to install the psql application (PostgreSQL command-line tool). I know it&#39;s hardcore, and most IDEs have Database connectivity tools. However, since I occasionally connect to the Database from a remote machine, I prefer to get familiar with the bare-bones toolset. Once you get used to it, you&#39;ll go Phhhh each time you see someone using one of these fancy Database connectivity tools.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*buM8WCM4KJDv0p0tSF7RRw.png" /></figure><p>Figure 2 shows the schematics of my setup:</p><ul><li>Centralized Postgre SQL instance, running a production database instance, and a paper-trading one. I use the GCP <a href="https://cloud.google.com/sql/docs/postgres/">SQL service</a> for hosting my data instance(s).</li><li>GCP hosted <a href="https://cloud.google.com/compute/">Compute Engine Instance</a>. The instance is automatically started and stopped using <a href="https://cloud.google.com/scheduler/">Cloud Scheduler</a> &amp; <a href="https://cloud.google.com/functions/">Cloud Functions</a>.</li><li>The server instance is running Debian Linux. Once the server starts, the <strong>Trader </strong>application is automatically triggered by the System V init system.</li><li><strong>LiuAlgoTrader</strong> comes pre-installed w/ <a href="https://en.wikipedia.org/wiki/Stackdriver">StackDriver</a>, sending logging to GCP central logging service. Performance tracing Metrics, if enabled, are transmitted using <a href="https://opentelemetry.io/">OpenTelemetry</a> (also pre-installed) to GCP Trace. GCP Monitoring can be used for <em>Observability</em>.</li><li>I use my laptop for backtesting strategies, and for long-running backtesting, I fire up an additional Compute Engine instance on GCP.</li><li>Using GCP keys and running a local DB proxy, I can access the Database from my laptop.</li></ul><p>It sounds a lot more complex than it is. In this guide, I will walk you step-by-step through the setup of each of these components.</p><p>AWS, Azure, Alibaba, Oracle, and other cloud providers all have equivalents to the above components. It is also possible to run everything on a single on-premise server or even your laptop. To do that, I would refer you back to an earlier <a href="https://amor71.medium.com/liualgotrader-part-ii-putting-it-all-together-1d447650808b">article</a>.</p><p>In the rest of this article, I will explain how to set the Database, configure the local environment to use the remote Database and logging, and run a backtesting session.</p><p>In the following article, we will set up the instance on GCP and configure it as an automated trading instance.</p><p>Step #1: Setting up the Database instance. <a href="https://youtu.be/35w-Vi6rJzY">This 2-minutes video</a> shows the steps to create a new Database on GCP. As you can see in the video, for our purposes and to keep costs at bay, we select a minimal configuration that uses a single availability zone with minimal capabilities and set it up with automatic backups.</p><p>Figure 3 shows the Database dashboard post-installation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K6w3U5QJhCQt4p2Zv1uuyQ.png" /><figcaption><strong>Fig 3 </strong>my-paper Database instance dashboard</figcaption></figure><p>It is now time to create the tradedb database that will host <strong>LiuAlgoTrader</strong> schema &amp; data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k_cQ6ysvaAO8JErEL59tig.png" /><figcaption><strong>Fig 4 </strong>Create database</figcaption></figure><p>Lastly, we need to create the database application user:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ckDmAWLI6GdC0nsRvgyE5A.png" /><figcaption><strong>Fig 5 </strong>Create a database user</figcaption></figure><p>Step #2: Connect the local environment to GCP. This step is a bit convoluted, but it only needs to be set up once. First,<a href="https://cloud.google.com/sdk/gcloud/"> install the GCP CLI</a> gcloud . Second, we need to install and configure a proxy service to GCP SQL. The proxy creates a tunnel from your local machine to our database instance on GCP. Once the tunnel runs, we can connect to the Database to connect to a local PostgreSQL instance. You can find detail on the proxy and download information <a href="https://cloud.google.com/sql/docs/postgres/sql-proxy">here</a>.</p><p>Before we can run the proxy, we need to know the Database connection string:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-qkJ3z__Fx6Jumt4TacuBA.png" /><figcaption><strong>Fig 6 </strong>Locate the Connection name on the Database instance Overview page</figcaption></figure><p>To run the proxy type:</p><blockquote>cloud_sql_proxy -instances=algo2–260618:us-east4:my-paper=tcp:5432</blockquote><p>The output should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qLJi9uGoKLXWb4x-OoPqpg.png" /><figcaption><strong>Fig 7 </strong>Example of `cloud_sql_proxy` output</figcaption></figure><p>Finally, to connect to the database type:</p><blockquote>\psql -h localhost -p 5432 -U liu tradedb</blockquote><p>Once you enter the password, the output should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/459/1*mBrvWycrEMtUN0_IoSoqZg.png" /><figcaption><strong>Fig 8 </strong>Look, Mom! I managed to connect to the Database on GCP!</figcaption></figure><p>Step #3 Create the database schema. LiuAlgoTrader Database schema is downloadable from <a href="https://github.com/amor71/LiuAlgoTrader/blob/master/database/schema.sql">here</a>. All you need to do is copy and paste the schema psql and hit the RETURN key. You should see a list similar to the below progressing:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/139/1*1Yb3Wi73UaDIKYeFBwlvow.png" /><figcaption><strong>Fib 9 </strong>Schema is created.</figcaption></figure><p>Once completed, you should type:</p><blockquote>\d</blockquote><p>This command lists the table; the list should be somewhat similar to:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/1*n3FadFET7JQIXvfJuV2IeA.png" /><figcaption><strong>Fig 10 </strong>Listing LiuAlgoTrader schema</figcaption></figure><p>Take a deep breath. You are almost there!</p><p>Step #4 Running backtesting. This step assumes that you have <strong>LiuAlgoTrader </strong>already installed, your environment variables for Alpaca and LiuAlgoTrader set. We are ready to go!</p><p>You can download the BTCUSD scanner and the Crypto strategy that we will be using <a href="https://github.com/amor71/trading_strategies/blob/master/strats/crypto.py">here</a> (reminder: make sure you have TA-LIB installed, you checkout my <a href="https://github.com/amor71/trading_strategies">readme</a>).</p><p>Create a portfolio for backtesting:</p><blockquote>portfolio create 5000 500 CRYPTO</blockquote><p>The tradeplan.toml would be something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*9dUvuux5oeeP7BhZlGO9Rw.png" /><figcaption><strong>Fig 11 </strong>the <strong>tradeplan.toml</strong> file used for backtesting (and later, trading)</figcaption></figure><p>To run the backtester type:</p><blockquote>backtester from 2021–01–01 — scanners=BTCUSD — strats=Crypto — asset=crypto — scale=day</blockquote><p>You should see output similar to:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bxxtauf07sWbmitZekvKcA.png" /><figcaption><strong>Fig 12</strong> Running the <strong>backtester</strong> session</figcaption></figure><p>Depending on your hardware setup and network connectivity, the year-long backtest session should run for a few minutes.</p><p>Step #5 Watch the performance. You&#39;ve done it! You created a cloud-based setup for your trading, you connected your local environment to your cloud setup, you configured a scanner and strategy for crypto trading, and you ran a full year backtesting session. Thank you for getting thus far!</p><p>Now l see how it all comes together. First, let us go back to GCP. This time we&#39;ll be looking for the logs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VL3oeQBtzg_NI4nIvp8Kww.png" /><figcaption><strong>Fig 13 </strong>Viewing the logs</figcaption></figure><p><strong>LiuAlgoTrader</strong> and the strategies I write use the platform tlog module to write records. The tlog The module uses StackDriver, and aside from writing to the standard output, logs are sent to GCP for later viewing. It is super helpful when your autonomous algo trading platform is doing its own thing, and you want to view the execution logs (as well as <a href="https://amor71.medium.com/liualgotrader-internals-performance-tuning-4cbb24fb7eba">Tracing</a>) at some point.</p><p>It is now time to view the results. We will be using the platform <strong>Jupyter Notebooks </strong>to check out our performance. Type:</p><blockquote>jupyter notebook</blockquote><p>Browse to &quot;analysis/notebooks&quot; as shown in Figure 14, and select portfolio_analysis.ipynb .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*v40nFMi-BSLx2XKgEuXi-g.png" /><figcaption><strong>Fig 14 </strong>Select the portfolio analysis notebook.</figcaption></figure><p>Once the notebook comes up, select the portfolio-id you created previously (you can find it in the tradeplan.toml file):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OTtOjoTl_t3O0PdwT9-rYA.png" /><figcaption><strong>Fig 15 </strong>Select the portfolio_id</figcaption></figure><p>Let it run. It will be several minutes for the trading details to be loaded and compared with the S&amp;P 500 since early 2021. Once completed, you can scroll down the see the final results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*COpEN3yJ1Fw3P3CLA1IdEw.png" /><figcaption><strong>Fig 16 </strong>Your friendly tear-sheet</figcaption></figure><p>Thank you for reading, and looking forward to seeing you in the following article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64ea8ea828bb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Emergent Properties in Markets?]]></title>
            <link>https://amor71.medium.com/emergent-properties-in-markets-406d212164ed?source=rss-e10d677bab73------2</link>
            <guid isPermaLink="false">https://medium.com/p/406d212164ed</guid>
            <category><![CDATA[financial-markets]]></category>
            <category><![CDATA[complex-systems-science]]></category>
            <category><![CDATA[complex-systems]]></category>
            <category><![CDATA[philosophy]]></category>
            <category><![CDATA[algorithmic-trading]]></category>
            <dc:creator><![CDATA[@amor71]]></dc:creator>
            <pubDate>Sat, 23 Oct 2021 08:03:43 GMT</pubDate>
            <atom:updated>2021-10-23T10:56:12.934Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6gOSFwxQbeQhjZkk" /><figcaption>Photo by <a href="https://unsplash.com/@dirtjoy?utm_source=medium&amp;utm_medium=referral">Zoe Schaeffer</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>It has been a surprisingly busy post-summer. I am slowly but surely progressing with a significant release of <a href="https://github.com/amor71/LiuAlgoTrader">LiuAlgoTrader</a>, which supports Crypto trading. Few more weeks. Stay tuned.</p><p>I decided to deviate from my previous chain of posts. I want to share some raw thoughts on Emergent properties in Financial Markets.</p><p>Here is an excellent definition for<strong> </strong><a href="https://sciencetrends.com/what-are-emergent-properties-definition-and-examples/"><strong>“Emergent properties”</strong></a>: <em>Emergent properties are properties that manifest themselves as the result of various system components working together, not as a property of any individual element.</em></p><p>Emergent properties are often discussed when analyzing complex systems or a combination of several systems. <a href="http://people.reed.edu/~mab/">Mark Bedau</a> gives a Circle as an example of a nominal emergent property of a set of points. He also differentiates between “weak” vs. “strong” emergence.</p><p>Emergent properties are rooted in the narrative of modern physics and particularly in Quantum Mechanics. Some say that <a href="https://en.wikipedia.org/wiki/Quantum_entanglement">Quantum Entanglement</a> proposed by Einstein, Podolsky &amp; Rosen (EPR) in 1935 is so elementary that space-time may be an emergent property of quantum entanglement.</p><p>Entanglement &amp; Correlation are interesting concepts brought into the computation world of Quantum computing. Keep that in mind as you read my musings further.</p><p>I recently listened to an exciting book by <a href="https://www.anilseth.com/">Anil Seth</a>. His conversation with <a href="https://www.preposterousuniverse.com/podcast/2021/10/11/168-anil-seth-on-emergence-information-and-consciousness/">Sean Caroll</a>, on Conscience as an emergent property, is inspiring. If you don’t listen to Sean Caroll’s Mindscape podcast already, I highly recommend it.</p><p>Enter Financial Markets.</p><p>Financial markets refer to any marketplace where the trading of securities occurs, including the stock market, bond market, forex market, and derivatives market, among others.</p><p>Financial Markets are complex: There are 8,000 public companies in the US, Over 2,000 ETFs traded in the US, thousands of more assets in futures, derivatives, money markets. Multiply by country, and the globally interconnected Financial Markets span hundreds of thousands of assets.</p><p>Such a complex system is bound to have emergent properties. But which are those?</p><p>Is Correlation an emergent property, or is it as elementary as quantum entanglement?</p><p>What Macro properties are we missing when we’re doing our local trading at our local exchange?</p><p>Is there an equivalent of a circle that we’re missing by not connecting the right dots?</p><p>Could market flux &amp; crashes be an emergent property that we apply hindsight biases?</p><p>I have no answers, but I think there’s something out there.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=406d212164ed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LiuAlgoTrader Internals & Performance Tuning]]></title>
            <link>https://amor71.medium.com/liualgotrader-internals-performance-tuning-4cbb24fb7eba?source=rss-e10d677bab73------2</link>
            <guid isPermaLink="false">https://medium.com/p/4cbb24fb7eba</guid>
            <category><![CDATA[tracing-apps]]></category>
            <category><![CDATA[algorithmic-trading]]></category>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[performance]]></category>
            <dc:creator><![CDATA[@amor71]]></dc:creator>
            <pubDate>Wed, 15 Sep 2021 13:29:06 GMT</pubDate>
            <atom:updated>2021-09-15T13:29:06.910Z</atom:updated>
            <content:encoded><![CDATA[<p>How-to ensure your trading platform meets your performance needs</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ouBsDQG-ekhY9azb" /><figcaption>Photo by <a href="https://unsplash.com/@emilegt?utm_source=medium&amp;utm_medium=referral">Emile Guillemot</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Some strategies, specifically day-trading strategies, require low-latency data and fast execution times.</p><p>This article will explain <a href="https://github.com/amor71/LiuAlgoTrader">LiuAlgoTrader&#39;s</a> software architecture. It will explain how to monitor the framework, strategy performance and provide tools for strategy developers to tune the code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0mu96kGYv1Q0Lkqke3eD8A.png" /><figcaption>Fig 1: LiuAlgoTrader multi-processing model</figcaption></figure><p>LiuAlgoTrader heavily relies on <a href="https://docs.python.org/3/library/multiprocessing.html">Python Multiprocessing</a> and Python <a href="https://docs.python.org/3/library/asyncio.html">asyncio</a>. The framework has three types of processes: Producer, Consumer, and Scanners (e.g. <a href="https://github.com/amor71/LiuAlgoTrader/blob/master/liualgotrader/consumer.py">consumer.py</a> , <a href="https://github.com/amor71/LiuAlgoTrader/blob/master/liualgotrader/producer.py">producer.py</a> and <a href="https://github.com/amor71/LiuAlgoTrader/blob/master/liualgotrader/scanners_runner.py">scanners_runner.py</a>) .</p><p>The trader application <a href="https://en.wikipedia.org/wiki/Spawn_(computing)">spawns</a> a single Scanners and Producer child-processes and several Consumer child-processes. The trader process would wait for the main processes to terminate before running “end of day” calculations (more on that, in a later post ) and quitting.</p><p>The processes communicate using Queues. Queues are the primary Intern-Process-Communication means by which data moves in the framework. Queues implementation vary from one OS to another; Linux system, implement Queues using pipes.</p><p>The Scanners process shares a Queue with the Producer process. Respectively, the Producer process shares a Queue with each of the Consumer Processes.</p><p>The Scanners process runs a <a href="https://github.com/amor71/LiuAlgoTrader/blob/master/liualgotrader/scanners_runner.py#L24">task</a> to periodically call the scanners defined in the <em>tradeplan—toml</em> file. The task sends the newly scanned symbols over the shared Queue to the Producer process.</p><p>The Producer process listens to the Scanner’s process Queue. Once new symbols are coming down the pipe, the task would <em>subscribe </em>for updates over a web socket:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*nOdHmwlSd0jxHui89KcYCA.png" /></figure><p><em>streaming_factory</em> is a Singleton holding the specific implementation of the streaming data provider <a href="https://github.com/amor71/LiuAlgoTrader/blob/master/liualgotrader/data/streaming_base.py">interface</a>. The data provider is selected using the <strong>DATA_CONNECTOR </strong>environment variable. Currently, supported values are “alpaca” for <a href="https://alpaca.markets/">Alpaca Markets</a> and “polygon” for <a href="https://polygon.io/">Polygon.io</a>.</p><p>The Consumer(s) are doing the ‘heavy lifting’: receiving stock price &amp; trade updates and executing strategies per symbol per second. Symbol updates may be in the thousands per minute.</p><p>The platform spawns several consumer processes and load-balance symbols between the available consumers to optimize performance—the optimal number of consumers varieties between hardware &amp; software setup and the specifics of the strategies.</p><p>If the environment variable <strong>NUM_CONSUMERS </strong>is present, it will dictate the number of consumer processes. If the value is 0 or non-present, the platform will determine the optimal number of consumer processes by applying heuristics on the current system load average and the number of available processors.</p><p>The platform keeps a mapping between symbols and Consumer processes. The mapping ensures that certain symbol updates are consistently sent to the same queue.</p><p>Separating execution between Consumers processes increases the platform throughput by maximizes the usage of available computation resources. A side effect is also reducing risks: if a strategy throws an exception or a Consumer process terminates abnormally, the rest of the Consumers will continue to work unhindered.</p><p>The <a href="https://github.com/amor71/LiuAlgoTrader/blob/master/liualgotrader/common/types.py#L35">QueueMappe</a>r class holds the mapping between symbols and Queues . “load balancing” between the different Consumers is achieved by the Producer process when receiving new symbols from the Scanners process:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LoeD9dP5ZzLDh8_znhJI9g.png" /></figure><p>The current implementation would evenly spread symbols between the different consumer processes. In the future, the platform may implement additional, more advanced load-balancing logic.</p><p>The framework executes strategies on per-second boundaries. Strategy execution time is crucial to the proper tuning of the trading platform — even the most tuned framework will tip if the strategy computation time takes long to execute.</p><p>The first step in tuning the trading platform is to establish a performance baseline. A baseline means finding the range of concurrent symbols the framework can track within acceptable performance parameters.</p><p>The framework KPIs are:</p><ul><li>Data latency (DL): the elapsed time between the market participant timestamp on an event and the current time measured.</li><li>Number of Events Produced per second (PE): This measure is the number of updates received over the WebSocket and sent to the Consumer Queues. The more symbols produced by the Scanners process, the higher the number would be. PE would go up as the market becomes more active during the beginning and end of the trading day.</li><li>Number of Events Consumed per second (CE): This measure indicates the number of events processed by the Consumer process. Consuming events keeps track of aggregated per minute data and executing strategies per second (or any other time frame). Aggregated data include OHLC (=Open High Low Close) data, plus per-minute volume, number of trades, and VWAP.</li><li>Average time spent in Queue (TQ): The average time between the Producer posting new data into the Consumer Queue and the Consumer worker pulling the data. An increase in the measure means the Consumer is too busy executing strategies increasing Data Latency.</li></ul><p>Market participants have up to 10 seconds to report trades during market hours (and there is no such requirement during extended trading hours), leading to an acceptable average DL of 2 seconds.</p><ul><li>When the DL exceeds the upper bound of 10 seconds, the framework would start logging errors and not execute trades on the second mark to reduce load and rebalance the system. Such spikes are “okay” on high-load periods (such as running heavy scanners). Still, if the framework passes a tipping point where it can’t rebalance back to average data latency, and data latency keeps going up, it will practically be the end of the trading day.</li><li>An increase in TQ may be an earlier indication of an increase in DL. It may also mean OS &amp; infrastructure issues.</li><li>High variance in CE between different consumers may indicate an imbalance between the other Consumers.</li></ul><p>The platform uses <a href="https://opentelemetry.io/">OpenTelemetry</a> / <a href="https://opencensus.io/">OpenCensus</a> to send metrics and tracing information to Google Cloud Platform and use Google Monitoring and Google Tracing to view the results. However, the platform can be easily adjusted to send metrics and tracing information to any other destination supported by OpenCensus / OpenTelemetry.</p><p>The platform uses <a href="https://github.com/amor71/mnqueues">MNQueues</a> wrapper around Python Queues, allowing PE/CE and TQ metrics to be sent to Google Monitor.</p><p>There are two different aspects for the platform performance KPI analysis: Monitoring KPIs and Tracing specific flows &amp; calls. The same tools available here are also available for the strategy developer to understand and tune the performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f1LFHqbq2wvBpY1K1UTGDQ.png" /><figcaption>PE &amp; CE for 600 concurrent symbols post start of a trading</figcaption></figure><p>The above figure uses a scanner to pump updates on 600 symbols. The Right figures show the PE: the number of events per second sent from the Producer process to all Consumer processes. Around 10 AM EST, as the market eases off, the open period updates go down from 400 per second to around 200 per second shortly after 11 AM EST.</p><p>The right figure shows the distribution of CE between the 4 Consumer processes. When viewing the figure and knowing that symbols are evenly (and randomly) distributed between the 4 processes, we can deduce a high variance in activity between the different scanned stocks.</p><p>The next figure shows the DL and TQ distribution which are visualized as bucketed heat-maps. The left side shows the data latency between the time-stamp generated by the market participant and the time-stamp post internal processing. In other words, the update passed all the way from the market participant to the data provider (i.e., Alpaca Markets ) via the web-sockets to the Producer and from there to the Consumer process. The consumer then processed the message and updated the internal per-minute aggregate for the symbol. For the 600 concurrent symbols, the 50 percentile was below 75 ms (!), only 1 percentile reached the maximal allowed 10 seconds update time, while over 95% are well under a second. Not bad for a freemium trading platform 😏.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tc3LAUG9jLV5x9MFBkKNEA.png" /></figure><p>The TQ heatmap helps us understand DL further: the 50% percentile of messages spend below 30ms waiting in the queues, while 95% spend below 300ms and only 1% spend around one second. Subtracting TQ distribution gives us a good picture of the contribution of the platform processing to the DL vs. delays downstream in the connectivity between the market participant and the data provider.</p><p>As a baseline for the platform performance, this specific sample was running on my personal Laptop. During this analysis, a single strategy was used, which returns immediately, thus helping establish a baseline for performance. A Verizon consumer-grade fiber network in NYC Financial District connected the laptop to the Internet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*PAsSQ6EDy2aXMS_cU25x1g.png" /><figcaption>My modest MacBook Pro spec</figcaption></figure><p>To reproduce the same results for PE, CE, and TQ, include the below line</p><blockquote>gcp_monitor_measure_prefix = “gcp-prefix”</blockquote><p>in the <em>tradeplan.toml . T</em>he parameter would trigger the MNQueue package to send Queue metrics to GCP and include the prefix in the measure name, making it easier to define a dashboard.</p><p>The DL measure (<em>liualgotrader.DL)</em> is sent to GCP Monitoring if the below environment variable is defined before running the trader application:</p><blockquote>export LIU_TRACE_ENABLED=1</blockquote><p>Our tuning does not end here. In a way, it only begins: a strategy developer needs tools to analyze how long function calls &amp; calculations take, how calls are executed. OpenTelemetry was designed specifically for that use case.</p><p>The below example shows <em>tracing </em>for the main Consumer flows. The first figure presents Google Trace List, showing <em>spans </em>(in OpenTelemetry terminology) sharing the same trade-id.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t9hmZ8LRc5iCacwKDTcgCg.png" /><figcaption>Google Trace list for Consumer messages</figcaption></figure><p>The next figure shows a specific trace, with <em>handle_data_queue_msg()</em> as the “root span,” followed by “child spans,” including their length and execution order (keep in mind calls are done using asyncio).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OlG1popQl6j406nhrSe1-g.png" /><figcaption>Zoom in to a specific trace</figcaption></figure><p>The platform provides few tools for tracing functions:</p><ul><li>The <a href="https://github.com/amor71/LiuAlgoTrader/blob/master/liualgotrader/common/tracer.py">tracer module</a>: use <em>get_tracer() </em>to initialize tracing.</li><li><a href="https://github.com/amor71/LiuAlgoTrader/blob/master/liualgotrader/common/decorators.py#L36">Tracing decorator</a>: the decorator assumes that the calling function receives a required keyword parameter carrier . The carrier parameter passes trace-context, allows child-spans, and produce a full trace view of the calls.</li><li>Tracing works cross-process, threads, tasks, and asyncio calls.</li><li>To use the trace decorator, either uses it as a plain decorator or call it explicitly as in:</li></ul><pre>await trace({})(handle_data_queue_msg)(data, trader, data_loader)</pre><p>For setting up a root-span, or,</p><pre>await trace(carrier)(handle_aggregate)(<br>    trader=trader,<br>    data_loader=data_loader,<br>    symbol=symbol,<br>    ts=time_tick[symbol],<br>    data=data,<br>    carrier=None,<br>)</pre><p>for a child-span.</p><p>Once the LIU_TRACE_ENABLED environment variable enables the tracing function, the DL metric is sent to Google Monitoring and basic tracing details for the Consumer message.</p><p>If enabled, make sure there is a sufficient quote configured in Google Trace. Otherwise, HTTP error 429 will be thrown by the OpenTelemetry SDK.</p><p>Thank you for reading this article. I hope you found it informative. If you have any questions or found any issues, please feel free to post a question or comment on the <a href="https://gitter.im/LiuAlgoTrader/community">LiuAlgoTrader Gitter page</a> or open an<a href="https://github.com/amor71/LiuAlgoTrader/issues"> issue on GitHub</a> or email me directly.</p><p>In the next article, I will present how to set up and configure a production-grade setup for LiuAlgoTrader.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4cbb24fb7eba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to manage a portfolio with Liu]]></title>
            <link>https://amor71.medium.com/how-to-manage-a-portfolio-with-liu-e6a7256a096d?source=rss-e10d677bab73------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6a7256a096d</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[algorithmic-trading]]></category>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[trading-system]]></category>
            <category><![CDATA[alpaca-tutorial]]></category>
            <dc:creator><![CDATA[@amor71]]></dc:creator>
            <pubDate>Tue, 27 Jul 2021 12:58:08 GMT</pubDate>
            <atom:updated>2021-07-27T12:58:08.181Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*D9dYRfjWqg9nkCes" /><figcaption>Photo by <a href="https://unsplash.com/@sigmund?utm_source=medium&amp;utm_medium=referral">Sigmund</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><a href="https://amor71.medium.com/liualgotrader-part-i-3334a27edd4b">Part I</a> presented <a href="https://github.com/amor71/LiuAlgoTrader">LiuAlgoTrader</a>. <a href="https://amor71.medium.com/liualgotrader-part-ii-putting-it-all-together-1d447650808b">Part II </a>detailed an end-to-end example of backtesting a successful strategy with Liu.</p><p>This article focuses on Stock Portfolio management with Liu: How to create, trade, and analyze your portfolio results.</p><p>Let’s start with some terminology:</p><ul><li>Each execution of the trader application creates a batch context.</li><li>The Liu platform saves strategy algorithmic trades in a batch context.</li><li>A strategy may receive portfolioas a parameter. A link between a batch and a portfolio allows tracking trades over multiple trading sessions.</li><li>An Account is the equivalent of a bank account: it has initial cash and an allowed credit line.</li><li>Each account withdrawal or deposit is an account transaction .</li><li>Linking between an account and a portfolio allows tracking both cash and equity values over time.</li><li>It is up to the strategy code to associate portfolio with batch and to track account withdraws in an account. Liu provides the building blocks and implementation patterns.</li></ul><p>The below diagram visualizes the relationships between the different data objects:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zKItP_te8_uFKSruSp_d5w.png" /></figure><p><a href="https://amor71.medium.com/liualgotrader-part-ii-putting-it-all-together-1d447650808b">Part II</a> presented an end-to-end backtester run, which is essentially a single batch. For the rest of this article, you will see how to run tradersessions over multiple days and track your performance over time.</p><p>The article assumes you have a working setup of LiuAlgoTrader. If you do not yet, please go back to the previous articles and ensure you have a working environment and are sufficiently familiar with the platform.</p><p>We will be using a modified Trend-Following strategy from <a href="https://www.followingthetrend.com/tag/clenow-research/#">Andreas Clenow’s books</a> (the books are highly recommended and include source code).</p><p><a href="https://github.com/amor71/trading_strategies/blob/master/strats/trendfollow.py">Here is a link</a> to my version of the strategy; you will need to clone the repository (and remember to add a ⭐️).</p><p>Step #1 : Create a Portfolio with $100,000 and $10,000 credit line.</p><p>Type:</p><pre>$ portfolio create 100000 10000</pre><p>A response should be similar to this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*CMCSF6GQbuhCU5gDGk6S1A.png" /></figure><p>Step #2: include the Strategy definition in your <strong>tradeplan.toml </strong>file:</p><pre>[strategies.TrendFollow]<br>debug = true<br>filename = &quot;/home/me_me_me/dev/trades/strats/trendfollow.py&quot;<br>index = &#39;SP500&#39;<br>portfolio_id = &quot;d3b8a521-2096-441e-a682-b9f1208b3c41&quot;<br>rank_days = 90<br>rebalance_rate = &quot;daily&quot;<br>reinvest = true<br>stock_count = 15<br>volatility_threshold = 0.03</pre><p>(<em>filename</em> should point to where you cloned the strategies repo, and <em>portfolio_id </em>should hold the portfolio id you just created)</p><p>Step #3: Assuming Alpaca rails (Free tier in Polygon.io may also work) and <a href="https://liualgotrader.readthedocs.io/en/latest/Configuration.html#environment-variables">environment variables</a> are correctly set. Type:</p><pre>$ trader</pre><p>And off we go</p><p>The trader application will end at the end of the trading day, and the day after, you will need to re-run the trader application. A Later article will guide on how to set up a fully automated, production-ready trading platform.</p><p>To view the trades performed type:</p><pre>$ portfolio trades d3b8a521-2096-441e-a682-b9f1208b3c41</pre><p>To view your current equity holdings type:</p><pre>$ portfolio equity d3b8a521-2096-441e-a682-b9f1208b3c41</pre><p>Lastly, to see the cash withdrawals and deposit type:</p><pre>$ portfolio account d3b8a521-2096-441e-a682-b9f1208b3c41</pre><p>After several days of running on a paper account, use the <a href="https://github.com/amor71/LiuAlgoTrader/blob/master/analysis/notebooks/portfolio_analysis.ipynb">Portfolio Performance Analysis Notebook</a>. Similar to <a href="https://amor71.medium.com/liualgotrader-part-ii-putting-it-all-together-1d447650808b">Part II</a>, the backtester application can run the strategy on past data. The optimizer application, presented in a <a href="https://amor71.medium.com/liu-optimizer-42b0d6805d77">previous article</a>, helps select the best initial values for the hyper-parameters in the <strong>toml</strong> file.</p><p>In the following article, we will explore how to monitor Liu performance during day-trading sessions.</p><p>Questions? Issues? Feel free to post a question on the <a href="https://gitter.im/LiuAlgoTrader/community">LiuAlgoTrader Gitter page</a> or open an<a href="https://github.com/amor71/LiuAlgoTrader/issues"> issue on GitHub</a> or email me directly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6a7256a096d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LiuAlgoTrader — Part II — Putting it all together]]></title>
            <link>https://amor71.medium.com/liualgotrader-part-ii-putting-it-all-together-1d447650808b?source=rss-e10d677bab73------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d447650808b</guid>
            <category><![CDATA[trading-system]]></category>
            <category><![CDATA[algorithmic-trading]]></category>
            <category><![CDATA[trading-ideas]]></category>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[@amor71]]></dc:creator>
            <pubDate>Fri, 02 Jul 2021 10:32:33 GMT</pubDate>
            <atom:updated>2022-02-25T20:21:47.200Z</atom:updated>
            <content:encoded><![CDATA[<h3>LiuAlgoTrader — Part II — Putting it all together</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hPY_N61YxiDdBF9B" /><figcaption>Photo by <a href="https://unsplash.com/@wimvanteinde?utm_source=medium&amp;utm_medium=referral">Wim van &#39;t Einde</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><a href="https://amor71.medium.com/liualgotrader-part-i-3334a27edd4b">Part I</a> introduced the <a href="https://github.com/amor71/LiuAlgoTrader">LiuAlgoTrader</a> framework. This post presents an end-to-end example of a real-life trading strategy.</p><p>If you read Part I and still struggle with your local environment, head over to <a href="https://gitter.im/LiuAlgoTrader/community">Liu Chat room</a> and post your question, or check the <a href="https://github.com/amor71/LiuAlgoTrader/issues">Issues</a> section on Github.</p><p>The post has three segments:</p><ul><li>Details of the trading strategy,</li><li>Step-by-Step tutorial for implementing the strategy using Liu,</li><li>Backtesting and analyzing the results,</li></ul><p>The strategy presented here is for educational purposes only; it is <strong>not</strong> investment advice.</p><p>The strategy trades stock-pairs volatility: a pair of inversely-correlated equities is selected, and at any given time, one of the two is picked based on underlying market conditions.</p><p>The strategy would go long on the picked equity, at the end of a down-turn, and sell when the stock starts to trend down. There is no traditional “stop-loss” in this strategy.</p><p>The strategy calculates <a href="https://www.bollingerbands.com/">Bollinger Band </a>with a seven-day Exponential Moving Average window and 1 STD either up or down. The buy signal is triggered if:</p><ol><li>The previous trading day closed below the lower band,</li><li>In the current day, the equity gaps and opens above the last day’s close price,</li><li>The current price is trending above the lower band.</li></ol><p>The strategy will close the position when the price cross above the upper band.</p><p>There are three steps to this particular strategy: picking the correct stock pairs, selecting the appropriate pair member at any given time, and implementing the “band-trading” strategy on the chosen asset.</p><p>It isn&#39;t straightforward, but we will break it step by step to ensure it’s all understood. As said in “Part I,” we’re not here for the easy; we are here for winning.</p><p>The idea, though, is not that complex: pick a stock that has high volatility (I’ve successfully traded TSLA with the same method for a while); when it’s trending, there are good chances for excellent profits on good entry and exit points. Adding the inverse correlated makes a profit on a down-trend. In some cases, it’s possible to short on down-trends, but that requires a different discussion.</p><p>I picked two leveraged ETFs in this particular example, which is by definition reversely correlated: <a href="https://finance.yahoo.com/quote/JNUG">JNUG</a> and <a href="https://finance.yahoo.com/quote/JDST">JDST</a>. They are both Leveraged (2x) ETFs on the <a href="https://finance.yahoo.com/quote/GDXJ">GDXJ</a> index. Word of caution: before picking up leveraged ETFs, you need to do your research well, understand the dynamics (especially for the bearish leveraged ETFs) of the picked stocks, as well as the underlying market dynamics.</p><p>For the current example, I set up two Liu components: “Scanner” and “Strategy.” The Scanner object calculates 50-days Simple Moving Average (SMA) if the current GDXJ is above the SMA: go long on JNUG; otherwise, go long on JDST. The Strategy object is generic; it trades the bands, regardless of the passed asset.</p><p><strong>Motivation: </strong>Before we look at the code, let us review the combined strategy results. Below are three tear sheets. The first tear sheets show the results pair-wise between June 2020 and June 2021, The second shows what it would be like to trade the JNUG on up-trends, and the third what it would be like to trade on JDST on GDXJ down-trends. As you can see, there are times where each would be a good choice based on the underlying market conditions, but neither is sustainable compared to S&amp;P500. Putting them both together produces stellar results that beat S&amp;P500 thru choppy waters for Gold.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*mJVOwTRWQx2m7ctbr2Znbg.png" /><figcaption><a href="https://amor71.github.io/LiuAlgoTrader/jungjdst-sma50cross-jun-20-21.html">Figure 1 — Pair-wise trading Jun 20 — Jun 21</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*3Vt8MmnnbpobvC5vP9NXPw.png" /><figcaption><a href="https://amor71.github.io/LiuAlgoTrader/jnug-above-sma50-jun-20-21.html">Figure 2 — Trading JNUG during up-trends (good in ’20, below SPY in ‘21)</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*OXwdmxaafgJ6FOjfjUgeMA.png" /><figcaption><a href="https://amor71.github.io/LiuAlgoTrader/jungjdst-sma50cross-jun-20-21.html">Figure 3 — Trading JDST during down-trends (good in ’21, deficient in ‘20)</a></figcaption></figure><p>Before we start, I suggest you create your repo for Liu strategies. In that repo, you should have a folder for <strong>scanners, strategy </strong>and also keep track of your <strong>tradeplan. toml</strong> file.</p><p>To create a scanner, we need to create a class that inherits from the Scanner base class. Let’s start with importing the relevant Liu packages:</p><pre>from liualgotrader.scanners.base import Scanner<br>from liualgotrader.common.data_loader import DataLoader</pre><p><em>DataLoader </em>implements a DataFrame-like construct that automatically loads data from a data-provider abstraction (more on that, in later posts). We will see how to use it shortly.</p><p>Next is the Scanner class definition:</p><pre>class GoldDigger(Scanner):<br>    name = “GoldDigger”</pre><pre>    def __init__(<br>        self,<br>        data_loader: DataLoader,<br>        recurrence: Optional[timedelta] = None,<br>        target_strategy_name: str = None,<br>    ):</pre><pre>        super().__init__(<br>            name=self.name,<br>            data_loader=data_loader,<br>            recurrence=recurrence,<br>            target_strategy_name=target_strategy_name,<br>        )</pre><p>Our Class, <em>GoldDigger</em>, inherits from the <em>Scanner</em> base class. Liu passes parameters to <em>__init__()</em>: <em>data_loader, recurrence, and target_strategy_name </em>are mandatory fields for any Scanner you will write.</p><p>Lastly, we need to implement the <em>run() </em>function. Liu calls the <em>run()</em> function at the start of the trading day and consecutively, based on the <em>recurrence </em>parameter.</p><pre>async def run(self, back_time: datetime = None) -&gt; List[str]:<br>    sma_50 = (<br>        self.data_loader[“GDXJ”<br>        .close[back_time — timedelta(days=90) : back_time]<br>        .resample(“1D”)<br>        .last()<br>        .dropna()<br>        .rolling(50)<br>        .mean()<br>        .iloc[-1]<br>    )</pre><pre>   return (<br>       [&quot;JNUG&quot;] if self.data_loader[&quot;GDXJ&quot;].close[back_time] &gt; sma_50 else [&quot;JDST&quot;]<br>    )</pre><p>Don’t you love how neat Python is? Few things to note in this excerpt:</p><ul><li>Everything in Liu is type-specific.</li><li>Check out the <em>DataLoader </em>class usage. Wrapping a DataFrame makes it easy to operate on a <em>self.data_loader[ticker] </em>like an ordinary Pandas DataFrame, with the added benefit, that if data is missing, it will be automatically and optimally fetched from the data provider. More on that later.</li></ul><p>The run function calculates SMA 50 and returns [“JNUG”] if the close price is above the moving average; otherwise, [“JDST”] is returned.</p><p>That’s all you need to do to get the Scanner going. Liu does all the heavy lifting behind the scenes: loading data, making sure it&#39;s continuously updated and consistent, passes your results to the proper strategy, and running it all in a multi-processing environment.</p><p><a href="https://github.com/amor71/trading_strategies/blob/master/scanners/gold_digger.py">Here</a> is a link to the complete code from my personal Liu strategies repo.</p><p>Next comes the Strategy.</p><p>Strategy class starts quite similarly:</p><pre>class BandTrade(Strategy):<br>    <br>    def __init__(<br>        self,<br>        batch_id: str,<br>        data_loader: DataLoader,<br>        portfolio_id: str,<br>        ref_run_id: int = None,<br>    ):<br>        self.name = type(self).__name__<br>        self.portfolio_id = portfolio_id</pre><pre>        super().__init__(<br>            name=type(self).__name__,<br>            type=StrategyType.SWING,<br>            batch_id=batch_id,<br>            ref_run_id=ref_run_id,<br>            schedule=[],<br>            data_loader=data_loader,<br>        )</pre><p>This <em>__init()__ </em>function is slightly different:</p><ul><li>The strategy name is pulled directly from the Class name vs. statically defined in the Scanner. Both are valid, though I like the strategy way better.</li><li>The <em>__init__() </em>function expects <em>portfolio_id -</em> a string passed from the <strong>tradeplan.toml </strong>file.</li><li>Strategy type <em>StrategyType.SWING</em>. For further details, refer to the <a href="https://liualgotrader.readthedocs.io/en/latest/Strategies.html">full documentation</a></li><li>An empty <em>schedule</em> list was passed to the base class. An empty schedule will not be the case in Day-Trading strategies.</li></ul><p>The <em>Strategy</em> Class is called by Liu either per symbol or with all positions together per execution cycle. To select which use the <em>should_run_all() </em>function:</p><pre>async def should_run_all(self):<br>    return True</pre><p>Liu uses <a href="https://docs.python.org/3/library/asyncio.html">asyncio</a>, and most functions require async abbreviations. To learn more about Liu internals, read the <a href="https://liualgotrader.readthedocs.io/en/latest/Concepts.html#usage-fundamentals">official documentation</a>.</p><p>if<em> should_run_all() </em>returns <em>True, </em>as in our case, the platform will call the <em>run_all()</em> inherited from the base class:</p><pre>async def run_all(<br>    self,<br>    symbols_position: Dict[str, float],<br>    data_loader: DataLoader,<br>    now: datetime,<br>    portfolio_value: float = None,<br>    trader: Trader = None,<br>    debug: bool = False,<br>    backtesting: bool = False,<br>    fee_buy_percentage: float = 0.0,<br>    fee_sell_percentage: float = 0.0,<br>) -&gt; Dict[str, Dict]:<br>    actions = {}<br>    if await self.is_buy_time(now) and not open_orders:<br>        actions.update(<br>            await self.handle_buy_side(<br>                symbols_position=symbols_position,<br>                data_loader=data_loader,<br>                now=now,<br>        )<br>    )<br>    if (<br>        await self.is_sell_time(now)<br>        and (<br>            len(symbols_position)<br>            or any(symbols_position[x] for x in symbols_position)<br>        )<br>        and not open_orders<br>    ):<br>        actions.update(<br>            await self.handle_sell_side(<br>                symbols_position=symbols_position,<br>                data_loader=data_loader,<br>                now=now,<br>            )<br>         )</pre><pre>    return actions</pre><p>The function calls <em>handle_buy_side() </em>if <em>now</em> is inside the “buy window” or <em>handle_sell_side() </em>if <em>now </em>is inside the “sell window,” and there are open symbol positions. <em>open_orders </em>is a platform parameter with all current open orders in-flight, while <em>symbols_position </em>holds all current symbols_position.</p><p>In our case, the <em>GoldDigger </em>scanner will return either “JNUG” or “JDST.” Hence <em>symbols_position </em>will include either, with position 0. or above.</p><p>Let’s take a look at <em>handle_buy_side():</em></p><pre>async def handle_buy_side(<br>    self,<br>    symbols_position: Dict[str, float],<br>    data_loader: DataLoader,<br>    now: datetime,<br>) -&gt; Dict[str, Dict]:<br>    actions = {}<br>    for symbol in symbols_position:<br>       current_price = data_loader[symbol].close[now]</pre><pre>       serie = (<br>           self.data_loader[symbol]<br>           .close[now — timedelta(days=30) : now]<br>           .between_time(“9:30”, “16:00”)<br>       )</pre><pre>       if not len(serie):<br>           serie = self.data_loader[symbol].close[now — timedelta(days=30) : now<br>           ]</pre><pre>       resampled_close = serie.resample(“1D”).last().dropna()<br>       bband = BBANDS(<br>           resampled_close,<br>           timeperiod=7,<br>           nbdevdn=1,<br>           nbdevup=1,<br>           matype=MA_Type.SMA,<br>       )</pre><pre>       yesterday_lower_band = bband[2][-2]<br>       today_lower_band = bband[2][-1]<br>       yesterday_close = resampled_close[-2]<br>       today_open = self.data_loader[symbol].open[<br>           config.market_open.replace(second=0, microsecond=0)<br>       ]</pre><pre>       if (<br>           yesterday_close &lt; yesterday_lower_band<br>           and today_open &gt; yesterday_close<br>           and current_price &gt; today_lower_band<br>       ):<br>           yesterday_upper_band = bband[0][-2]<br>           if current_price &gt; yesterday_upper_band:<br>               return {}</pre><pre>           buy_indicators[symbol] = {<br>               “lower_band”: bband[2][-2:].tolist(),<br>           }<br>           cash = await Accounts.get_balance(self.account_id)<br>           shares_to_buy = cash // current_price</pre><pre>           actions[symbol] = {<br>               “side”: “buy”,<br>               “qty”: str(shares_to_buy),<br>               “type”: “limit”,<br>               “limit_price”: str(current_price),<br>           }</pre><pre>    return actions</pre><p>There are few subtleties to note in the function:</p><ul><li>The function returns a <em>Dictionary</em> with the symbol as a Dictionary key (=” JNUG” or “JDST”) and an action <em>Dictionary</em> that notifies Liu what action to execute. You may find details <a href="https://liualgotrader.readthedocs.io/en/latest/Strategies.html#run-actions">here</a>.</li><li>The <em>data_loader</em> passed to the strategy may differ by scale ( minute/daily); the Strategy needs to query the data_loader to understand if and how to resample.</li><li>The strategy uses TA-LIB, which may be a little tricky to install on some Windows distributions. You can find installation details <a href="https://github.com/mrjbq7/ta-lib">here</a>.</li></ul><p><a href="https://github.com/amor71/trading_strategies/blob/master/strats/bandtrade.py">Here</a> is a link to the complete Strategy code.</p><p>It’s time to put it all together: construct the <strong>tradeplan. toml</strong> file, execute the back-testing session, and view the results Notebook.</p><p>The first step is to create a <em>portfolio_id, </em>to hold our trades:</p><blockquote>portfolio create 10000 1000 US_EQUITIES</blockquote><p>The response should look like this:</p><pre>[create_db_connection()][82171]2021–06–28 15:29:01.902386:db connection pool initialized<br>Portfolio ID ceb333aa-7668–493c-bc4d-a415ca47be5a created</pre><p>Our <strong>tradeplan.toml </strong>file:</p><pre>[scanners]<br>[scanners.GoldDigger]<br>filename = &quot;scanners/gold_digger.py&quot;<br>recurrence = 5<br>target_strategy_name = &quot;BandTrade&quot;</pre><pre>[strategies]<br>[strategies.BandTrade]<br>filename = &quot;strats/bandtrade.py&quot;<br>portfolio_id = &quot;ceb333aa-7668-493c-bc4d-a415ca47be5a&quot;</pre><p>Finally, it’s time to execute our back-testing session; type:</p><blockquote>backtester from 2020-06-01 --scanners=GoldDigger --strats=BandTrade</blockquote><p>and watch the below unfolding:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h1H5TjaPlJyQqtA2YlgT6Q.png" /><figcaption>Back-test execution</figcaption></figure><p>The back-testing session runs for about 4 minutes on my local Mac (2019, 1.7 GHz Quad-Core i7 w/ 16 GB)</p><h3>Congratulations!</h3><p>You just went thru an end-to-end development and execution of a year-long back-testing session. It is now time to view the results. Fire up your Jupyter Notebook and use the <a href="https://github.com/amor71/LiuAlgoTrader/blob/master/analysis/notebooks/portfolio_analysis.ipynb">portfolio analysis notebook</a> to view the results of your efforts:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FLGIVCHqu2sU&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DLGIVCHqu2sU&amp;image=http%3A%2F%2Fi.ytimg.com%2Fvi%2FLGIVCHqu2sU%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/132fd255d5155d86265371278784edd4/href">https://medium.com/media/132fd255d5155d86265371278784edd4/href</a></iframe><p>Thank you for reading this post. Feel free to post questions, ideas, and suggestions on the <a href="https://gitter.im/LiuAlgoTrader/community">LiuAlgoTrader Gitter page</a> or open an<a href="https://github.com/amor71/LiuAlgoTrader/issues"> issue on GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d447650808b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Liu Optimizer]]></title>
            <link>https://amor71.medium.com/liu-optimizer-42b0d6805d77?source=rss-e10d677bab73------2</link>
            <guid isPermaLink="false">https://medium.com/p/42b0d6805d77</guid>
            <category><![CDATA[algorithmic-trading]]></category>
            <category><![CDATA[trading-system]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[optimization-techniques]]></category>
            <category><![CDATA[alpaca-tutorial]]></category>
            <dc:creator><![CDATA[@amor71]]></dc:creator>
            <pubDate>Thu, 24 Jun 2021 15:15:44 GMT</pubDate>
            <atom:updated>2021-06-24T15:15:44.279Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Xl1G4b8pKKyeKUwU" /><figcaption>Photo by <a href="https://unsplash.com/@kpzhnv?utm_source=medium&amp;utm_medium=referral">Damir Kopezhanov</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I wrote <a href="https://github.com/amor71/LiuAlgoTrader">LiuAlgoTrader</a> so I can trade using my long-earned development skill-set. Consistent winning is not easy.</p><p>That’s when back-testing enters:a tool that lets you test-drive your strategies, compressing months of potential trading into minutes of calculations.</p><p>Almost every strategy that I wrote has some configuration parameters. These parameters are the number of equities in your portfolio, EMA thresholds, length of the rolling window for volatility calculations, etc.</p><p>These parameters needs to be optimized to tune your strategy.</p><p><strong>Enter Hyperparameters</strong></p><blockquote><a href="https://en.wikipedia.org/wiki/Hyperparameter_(machine_learning)">In machine learning, a hyperparameter is a parameter whose value is used to control the learning process. By contrast, the values of other parameters are derived via training.</a></blockquote><p>In other words, hyper-parameters span the configuration space of strategies, selecting the optimal values can drastically improve strategies performance.</p><p>With release 0.3.11, LiuAlgoTrader has a new tool: optimizer . This unique application allows running, parallel back-testing of strategies while generating all possible combinations for hyper-parameters and storing these results to the database.</p><p>Once the optimization session ends,use a Jupyter Notebook to load all the back-test results and compare how the different configurations affect total returns, Sharpe ratio, and volatility.</p><p>It is now up to you to select your desired parameters by taking these three data points (or add a few of your own).</p><p>Let us see an example: you’re running a ‘Trend Following’ strategy with an account with $10,000 and wish to select the number of different equities that should make up your algo traded.</p><p>Your `tradeplan. toml` file looks something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*mAr5R4VGsOM0U5ejZyTWsA.png" /><figcaption><a href="https://raw.githubusercontent.com/amor71/LiuAlgoTrader/master/examples/optimizer/tradeplan.toml">Sample trade-plan</a></figcaption></figure><p>But is ‘10’ really the best selection forstock_count? Enter optimizer :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*LhSgCuNa5vLW9bmbLA1h6g.png" /></figure><p>Adding these lines to the configuration files instructs the optimizer application to run back-test sessions in the first half of 2021. The hyper-parameter is “stock_count,” with values ranging from 5 to 15. The optimizer can receive several hyper-parameters and create and iterate through the entire configuration space.</p><p>Contrary to the hyper-parameter, the ”parameters” depict how to calculate and over-ride the strategy configuration parameter for “portfolio_id.” For each execution of the back-test iteration, a new portfolio is generated with $10,000 and a credit line of $1,000.</p><p>Running the optimizer is as simple as typing:</p><blockquote>optimizer</blockquote><p>The optimizer may run for a while, producing an output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zJx0N7Kwmn2RKdPudGGLzw.png" /><figcaption>Sample `optimizer` run</figcaption></figure><p>Make sure to copy and optimizer session-id -&gt; you will need it later for your analysis.</p><p>Once completed, use the dedicated <a href="https://github.com/amor71/LiuAlgoTrader/blob/master/analysis/notebooks/hyperparameters_analysis.ipynb">Notebook</a> to view the collection of back-test sessions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wv9-obsx0oja23QiH2_gWA.png" /></figure><p>The Notebook loads all portfolio&#39;s transactions and analyzes them to produce the answer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*8OylMiG7rHzaX3OVMWMv2Q.png" /></figure><p>So it’s not “10” but rather <strong>“11”</strong> that yields the best returns and best Sharpe ratio for the strategy!</p><p>For further reading check LiuAlgoTrader optimizer <a href="https://liualgotrader.readthedocs.io/en/latest/Optimizer.html">documentation</a>.</p><p>Questions? Issues? Feel free to post a question on the <a href="https://gitter.im/LiuAlgoTrader/community">LiuAlgoTrader Gitter page</a> or open an<a href="https://github.com/amor71/LiuAlgoTrader/issues"> issue on GitHub</a> or email me directly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42b0d6805d77" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LiuAlgoTrader — Part I]]></title>
            <link>https://amor71.medium.com/liualgotrader-part-i-3334a27edd4b?source=rss-e10d677bab73------2</link>
            <guid isPermaLink="false">https://medium.com/p/3334a27edd4b</guid>
            <category><![CDATA[fintech]]></category>
            <category><![CDATA[trading-system]]></category>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[algotrading]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[@amor71]]></dc:creator>
            <pubDate>Wed, 09 Jun 2021 05:27:17 GMT</pubDate>
            <atom:updated>2021-07-03T06:07:10.078Z</atom:updated>
            <content:encoded><![CDATA[<h3>LiuAlgoTrader — Part I — Power up!</h3><h4>Who needs a trading platform?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Km6Qt6c_H_yu_ywZ" /><figcaption>Photo by <a href="https://unsplash.com/@hamzasky?utm_source=medium&amp;utm_medium=referral">Hamza Bounaim</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I am a retail trader/investor. In other words, I’m an amateur — I am not a “quant,” never worked for a Hedge fund, spent time on the trading floor, or even studied economics. However, I am a trained software developer with a decent background in math and a disruptive approach to post-postmodernism. If you are like-minded, you might want to read the rest of this post, and if you’re a pro, you might be interested to see how we amateurs roll.</p><p>This post is a high-level brief explaining the background of my endeavor, trading platform setup, and some basic concepts to get you going.</p><p>Part II will include concepts of developing strategies with the framework and provide a line-by-line sample strategy.</p><h3><strong>Let’s start at the end (a.k.a, a bit of motivation)</strong></h3><ol><li><a href="https://amor71.github.io/LiuAlgoTrader/tearsheet.html">Tear-sheet of a Trend-Following strategy, with daily, rebalance and capped volatility</a>,</li><li><a href="https://amor71.github.io/LiuAlgoTrader/brandtreade_tearsheet.html">Sample Swing trading volatility of leveraged ETF pairs,</a></li><li><a href="https://youtu.be/rVwFCbHsbIY">Back-test Day-Trading (!) with Liu Algo Trading platform.</a></li></ol><p>Until a year and a half ago, I didn’t trade a single asset on any market, didn’t know the jargon or market dynamics. Today I think of it as a self-employed gig economy. It’s far from easy money; in fact, it’s pretty hard, but it’s up to you—total independence. The markets are fascinating phenomena: purely manufactured chaos (yes, it’s more Fractal than Stochastic), psychology induced yet dominated by machine-based trading.</p><p>About two years ago, I ran into an audiobook on day-trading. The first thing that I noticed is the manual approach pattern identification and the complexities of day-trader psychology. I’m old enough to realize this won’t work for me. Shortly after that, I came across <a href="https://alpaca.markets/">Alpaca Markets </a>and a Python example of day-trading based on MACD. They are an excellent company: it’s a start-up company trying to make a name for themselves, rough around the edges, but they have just the poison I needed: APIs for trading, data feeds, account management, and a vibrant community. A big shout-out to the Alpaca team; thank you guys for making this available free of charge and help me take my baby steps into this fascinating world.</p><p>I noticed several things:</p><ol><li>Back-testing is essential, but it’s not the end-game.</li><li>There are no complete out-of-the-box back-testing platforms for day trading. For successful day-trading, the platform has to scan thousands of signals concurrently and act near-real-time. The platform also must provide tools to review, improve and benchmark model performance.</li><li>Trading services are dynamic eco-systems with brokers and data providers coming and going and constantly changing APIS. The platform must have an abstraction layer on top data providers and brokers, letting developers focus on strategies rather than infrastructure.</li><li>I need an “ML friendly” platform where I can start tinkering with machine learning (I am aware this point is a bit vague but super important, we’ll dwell on it in a later post).</li></ol><p>Oh, and I want it to be completely free. Forever.</p><p>I decided to take on the challenge and wrote <a href="https://github.com/amor71/LiuAlgoTrader">LiuAlgoTrader</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*JV18_sBhACCx1TjNgjRu8Q.png" /><figcaption>Sample Tear-Sheet w/ Liu</figcaption></figure><p>The rest of the post will walk you thru the setup of the framework and some basic concepts. The follow-up post will focus on how to develop and execute strategies using the platform. While I try to make it all sounds nifty swiftly, a word of warning before you go down the rabbit hole: this is not for everyone. LiuAlgoTrader is for developers, by developers. It does not have fancy-schmancy UI, it is not a “no-code” environment, and you need to be a solid Python developer to make the most of it. There is no money for the grab here, and unless you’re truly committed and willing to invests the many hours (heck, months! years!) required to create algo trading strategies that will float, <a href="https://robinhood.com/us/en/">you better look somewhere else</a>.</p><p>With that said, let’s fire up the engines!</p><p>The platform executes trades on Alpaca: you will need <a href="https://broker-app.alpaca.markets/sign-up">an account</a> (=API keys) to get started. The second step is to figure what kind of data you need for your trades. Currently, the platform supports both <a href="https://polygon.io/pricing">Polygon.io</a> and Alpaca native data-APIs. Polygon.io is pricier than Alpaca Data API but has been around longer. A “free” version exists for both, but it’s pretty limited.</p><p>LiuAlgoTrader is developed in Python 3.9 and tested on Python 3.8 (though switching to 3.9 is highly recommended).</p><p>LiuAlgoTrader requires a database to store trading results and details of the executed strategies for future analysis. The platform uses <a href="https://www.postgresql.org/">PostgreSQL</a>. There is no heavy-lifting here : liu, the installation wizard will download a Docker container and pre-populate the database with the required schema and sample data. You do need to make sure you have Docker Engine &amp; <a href="https://docs.docker.com/compose/install/">Docker Compose </a>installed.</p><p>I do my development and testing locally on macOS. My “production” environment is running on the Google Cloud Platform (GCP). It includes a 4-CPU “Virtual Compute Instance” running Debian Linux and a GCP hosted PostgreSQL. The instance is automatically fired up at 9 AM EST on trading days and automatically shut down shortly after the trading day. Logs are always viewable on the GCP logs viewer, as well as the data in the database. The total cost of the environment is ~$120/month.</p><p>The platform has several executable components, all written in Python:traderfor executing trades on live or paper-account, backtester replaying trading sessions, or testing strategies on past data and market_miner intended for off-hours calculations for speeding up trading sessions. The platform comes equipped with an installation &amp; configuration wizard called. liu .</p><p>LiuAlgoTrader is installed by</p><blockquote>pip install liualgotrader</blockquote><p>While I do my development on macOS and my production setup is Linux-based, the platform runs just fine on Windows.</p><p>Before running the installation Wizard, you need to make sure you correctly set up the environment variables required by Alpaca SDK. You could find further reading on configuration <a href="https://github.com/alpacahq/alpaca-trade-api-python#alpaca-environment-variables">here</a> (Note you need just the first four to start with). Once done, all you have to do is type:</p><blockquote>liu quickstart</blockquote><p>And follow the instructions of the installation wizard (which would typically mean just pressing the return/enter a key a couple of times and the setup unavailing).</p><p>Once installed, the wizard will provide instruction on how to view a pre-recorded day-trading session.</p><p>After the framework is fully installed, read the <a href="https://liualgotrader.readthedocs.io/en/latest/Getting%20Started.html">Getting Started page</a> to understand the platform&#39;s basic concept.</p><p><a href="https://amor71.medium.com/liualgotrader-part-ii-putting-it-all-together-1d447650808b">Part II</a> presents an end-to-end example of creating and running strategies using the Platform. For now, if you run into issues during your installation or setup, feel free to post a question on the <a href="https://gitter.im/LiuAlgoTrader/community">LiuAlgoTrader Gitter page</a> or open an<a href="https://github.com/amor71/LiuAlgoTrader/issues"> issue on GitHub</a> or email me directly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3334a27edd4b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>