<?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 acperez on Medium]]></title>
        <description><![CDATA[Stories by acperez on Medium]]></description>
        <link>https://medium.com/@ac28042?source=rss-e95acea40cd9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Zl3LKKOtE6_VFL3mI9URwQ.jpeg</url>
            <title>Stories by acperez on Medium</title>
            <link>https://medium.com/@ac28042?source=rss-e95acea40cd9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 00:20:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ac28042/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[Genetic algorithm for sharpe ratio maximizing within a universe of 70.000 funds.]]></title>
            <link>https://medium.com/@ac28042/genetic-algorithm-for-sharpe-ratio-maximizing-within-a-universe-of-70-000-funds-f002c9a5df42?source=rss-e95acea40cd9------2</link>
            <guid isPermaLink="false">https://medium.com/p/f002c9a5df42</guid>
            <category><![CDATA[markowitz]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[genetic-algorithm]]></category>
            <category><![CDATA[algorithmic-trading]]></category>
            <dc:creator><![CDATA[acperez]]></dc:creator>
            <pubDate>Fri, 22 Apr 2022 15:04:17 GMT</pubDate>
            <atom:updated>2022-04-22T17:27:52.687Z</atom:updated>
            <content:encoded><![CDATA[<h3>Genetic algorithm for Sharpe Ratio maximizing within a universe of 70.000 funds.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/0*N_-ugRcuk6q039EK" /><figcaption>Resultant Markowitz’s efficient frontier</figcaption></figure><h3>Motivation</h3><p>As many of you know, portfolio optimization is one of the biggest challenges in financial markets and asset management. This article shows how is possible to find enough good combination of assets and weights in a reasonable computational time for a universe of 70,000 funds with one-year trading history by implementing evolutionary computing techniques. In contrast to other works I have found where the assets are static and the evolutionary approach focuses on finding the best combination of weights for that portfolio; this approach deals with a much more complex problem, finding the combination of assets and weights within a universe of 70,000 funds.</p><h3>Evolutive Computing</h3><p>Evolutionary Computing is a field of computer science that uses stochastic search processes based on natural evolution to solve optimization problems in areas such as planification, design, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*ihbrWpC58FHty6tO0I3cEA.png" /><figcaption>Canonical evolutionary algorithm.</figcaption></figure><h3>Genetic Algorithms</h3><p>Genetic algorithms would be the most widely used variant within evolutionary computing. John H. Holland introduced genetic algorithms as we know them today in 1962 [Holland 1962, Holland 1965]. Holland later summarized this work in his book <strong><em>Adaption in Natural and Artificial Systems</em></strong>. Years later, David E. Goldberg made them popular, by giving them a practical approach in his book <strong><em>Genetic Algorithms in Search, Optimization and Machine Learning</em></strong>.</p><h3>Sharpe Ratio</h3><p>The Sharpe Ratio measures the excess annualized return per unit of risk for a <em>zero investment strategy</em>. By risk, I mean the annualised standard deviation of returns, and by excess return, I mean returns over the riskless rate.</p><p>This will be our fitness function to maximize.</p><p><strong>¿How Sharpe Ratio is calculated?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/0*g-YhGDaiYhmouCtj.png" /><figcaption>Sharpe Ratio formula.</figcaption></figure><h3>Coding our genetic algorithm</h3><h4>Individual</h4><p>Okay, let’s go by parts. We already know the equation to calculate the Sharpe Ratio that will be our fitness function to be maximized, <strong>but</strong> <strong>how do we use it in our genetic algorithm?</strong></p><p>The first thing I will do is define the class Individual that will represent a solution from the set of explored solutions.</p><p>The asset universe will be common to all individuals. For this, I decided to add the asset set as a class attribute. In this way, all instances of individuals will have access to the asset universe.</p><p>These assets universe will be a data frame where the columns represent the investment fund, and the rows will be its closing prices from 2020–01–03 to 2021–12–11. This DataFrame will be clean, homogenized and bias-free.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*u4lqfnWkFDKQ3ECyoEZ-6Q.png" /><figcaption>Data overview.</figcaption></figure><p>On the other hand, an individual receives two vectors as initialization parameters, one of them will represent the assets from the universe through indexes, and the other one will be a vector of weights of the same length, which will represent the weight of each asset within the individual’s portfolio. Since the universe of assets is huge, I decided to limit the number of assets that individuals’ portfolios can hold by restricting them to a maximum of 20 assets and a minimum of 1.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b0fa0fc037cfb6e8f9406cd596d4ddd9/href">https://medium.com/media/b0fa0fc037cfb6e8f9406cd596d4ddd9/href</a></iframe><p>Once the structure of an individual is defined, it is necessary to add more operations that help us achieve the objectives of the use case.</p><h4>Calculating mean returns</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/27552e10fc0e84bc47230252b01bbef0/href">https://medium.com/media/27552e10fc0e84bc47230252b01bbef0/href</a></iframe><h4><strong>Calculating the risk</strong></h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e0f85ac706a009dcfc132a056d8d8d0/href">https://medium.com/media/8e0f85ac706a009dcfc132a056d8d8d0/href</a></iframe><h4><strong>Calculating our fitness function (Sharpe Ratio)</strong></h4><p>In this case our risk-free rate will be 0.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0f0dc0aef0526ff118ac3911a64e3912/href">https://medium.com/media/0f0dc0aef0526ff118ac3911a64e3912/href</a></iframe><h3>Individual selection</h3><p>I will use proportional selection with elitist ranking and migratory replacement for this case.</p><p>“Migratory replacement” is something I have come up with to add diversity to the solution set by adding new individuals. As the search space is so large, it is necessary to add much diversity to our population in order to avoid falling into local minimums.</p><p>This type of selection assigns a probability to each individual in order to be selected according to its fitness function. This allows the best-adapted individuals to have more possibilities of being selected and therefore to be more present in the next generation. In comparison, the worst adapted individuals have fewer possibilities of being selected.</p><p>On the other hand, as it is elite driven, it chooses the best adapted n% and adds them to the next generation to ensure that the best individuals spread their genes.</p><p>Another percentage is allocated to a migratory replacement, where new individuals are incorporated into the selection, thus favoring greater diversity and therefore greater exploration.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d466c7f4b45a4b281be080cca05c6cb7/href">https://medium.com/media/d466c7f4b45a4b281be080cca05c6cb7/href</a></iframe><h3>Crossover method</h3><p>Between generations, the number of assets of each individual will be variable. For this, I will use modulus 20 such that 20 will be the maximum number of assets an individual can have while the minimum will be 1.</p><p>My crossover method continuously prevents the resulting portfolios from falling into minimums or maximums (1 or 20 assets). For example, if two parents have 14 and 17 assets respectively when working in modulus 20, their offspring will have 11 assets, while if two parents have 2 and 3 assets respectively, their offspring will have 5 of those assets.</p><p>The offspring also inherit the weights from the parents; in this way, I make sure that weights never sum more than 1. If two parents have the same asset and this has been selected for the offspring, this asset is not inherited twice, but the weights are summed and inherited only once. In this way we avoid the offspring having several repeated assets.</p><p>When an offspring inherits the assets from his parents, he also inherits the weights following the following equation:</p><p>OffspringA = α ∗ Parent1+ (1 −α) ∗ Parent2</p><p>OffspringB = (1 −α) ∗ Parent1+ α ∗ Parent2</p><p>Where α is a random number between 0 and 1.</p><p>Thus some individuals may have few assets with a large percentage of accumulated capital.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cda74cbb3398029a4bcb51e592e0dc97/href">https://medium.com/media/cda74cbb3398029a4bcb51e592e0dc97/href</a></iframe><h3>Mutation method</h3><p>In mutation operation I replace a random number of assets from the individual with assets from the universe of assets; in that way, I add diversity to the population. The probability of mutation will be variable in each generation such that in some generations, exploration will be rewarded while others will focus on exploiting the current solution subspace. If the mutated individuals do not have a better degree of adaptation than the best individual, they are discarded.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/000fb38bd680d2137e4f6cb5ed8928bc/href">https://medium.com/media/000fb38bd680d2137e4f6cb5ed8928bc/href</a></iframe><h3>Evolutive approach</h3><p>This part contains the core of our genetic algorithm. It defines the steps in which the previously defined methods will be executed until the stop condition is met.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ede2cb2db7bc1429997011682b31c6e8/href">https://medium.com/media/ede2cb2db7bc1429997011682b31c6e8/href</a></iframe><h3>Putting all together</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a3dcab360fddc692690a2d9492d3d35/href">https://medium.com/media/6a3dcab360fddc692690a2d9492d3d35/href</a></iframe><p>If you want to <strong>try the entire code yourself or follow along, </strong>go to my published codebase on GitHub:</p><p><a href="https://github.com/QuantumA/GA-efficient-frontier">GitHub - QuantumA/GA-efficient-frontier: An evolutionary algorithm (EA) capable of maximizing the sharpe ration for a given universe of 70.000 funds.</a></p><h3>References &amp; inspiration</h3><p><em>Carmona, Enrique &amp; Fernández, Severino. (2020). Fundamentos de la Computación Evolutiva.</em></p><p><em>Ivan Grindin (2021). Learning Genetic Algorithms with Python:Empower the Performance of Machine Learning and Artificial Intelligence Models with the Capabilities of a Powerful Search Algorithm.</em></p><p><em>Holland, John H. (1992). Adaptation in Natural and Artificial Systems: An Introductory Analysis with Applications to Biology, Control and Artificial Intelligence.</em></p><p><em>David E. Goldberg. (1989) Genetic Algorithms in Search, Optimization, and Machine Learning.</em></p><p><em>Pankaj Sinha. Et al. (2015) Algorithm of construction of optimum portfolio of stocks using genetic algorithm.</em></p><p><em>Emanuele Stomeo. Et al. (2019). Genetic Algorithm Application to Portfolio Optimisation.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f002c9a5df42" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automatiza el despliegue de instancias EC2 en AWS con Ansible]]></title>
            <link>https://medium.com/@ac28042/automatiza-el-despliegue-de-instancias-ec2-en-aws-con-ansible-5656392cc938?source=rss-e95acea40cd9------2</link>
            <guid isPermaLink="false">https://medium.com/p/5656392cc938</guid>
            <category><![CDATA[ansible]]></category>
            <category><![CDATA[ec2]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[acperez]]></dc:creator>
            <pubDate>Sat, 29 Jan 2022 15:38:41 GMT</pubDate>
            <atom:updated>2022-01-29T15:38:41.090Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ia2P13JPzxW4ibOdDZMY5w.png" /><figcaption>Creado por acperez</figcaption></figure><p>En este artículo que mostrar como es posible provisionar instancias EC2 en AWS de manera automática utilizando Ansible. Mi intención es ofrecer una plantilla usable y fácil de entender con la configuración básica que se necesitaría para llevar a cabo este tipo de tareas.</p><h3><strong>¿En qué situaciones puede ayudarte este caso de uso?</strong></h3><p>Imagina que has desarrollado un SAAS y quieres gestionar los despliegues que haces para tus clientes o supón por ejemplo que vas a comenzar un proyecto en tu empresa y los equipos de trabajo se quedan cortos para realizar determinadas tareas. Una posible solución sería tener preparada una plantilla que automatice el todo el proceso de despliegue de una o varias instancias en AWS con las características que necesites en ese momento.</p><p><strong>Al grano.</strong></p><p>En este post no voy a entrar en detalles de qué es Ansible, cual es su arquitectura o sus características. Voy a mostrar simplemente los pasos que necesitas para automatizar el despliegue de tus instancias en Amazon.</p><h3>ENTORNO</h3><p>Para este workshop voy a utilizar Ubuntu 20.04 pero tu puedes utilizar la distribución que te sea más cómoda. Lo importante es que tengas instalado <strong><em>Python3</em></strong><em> </em>y su gestor de entornos virtuales <strong><em>virtualenv</em></strong><em> </em>porque es lo que voy a utilizar para instalar las dependencias para este proyecto y tenerlas separadas del resto del sistema.</p><h3>Lo primero, instálate Ansible.</h3><p>Para instalar Ansible en tu sistema abre una terminal y escribe el siguiente comando:</p><pre>sudo apt-get install ansible</pre><p><strong>Crea una carpeta para el proyecto</strong></p><pre>mkdir Ansible-for-EC2<br>cd Ansible-for-EC2/</pre><p>Empezamos a poblar el proyecto con los archivos necesarios.</p><p><strong>Create un entorno virtual</strong></p><p>Lo primero será crear un entorno virutal en el que instalaremos ciertas dependencias como boto3 y boto, que son los SDK de AWS en Python.</p><pre>python3 -m venv venv <br>source venv/bin/activate</pre><p>Sabrás que se te ha activado el entorno virtual porque a la derecha de tu terminal te indica el nombre.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/1*NMiNs0vr0PS69_Sb1XEh3Q.png" /></figure><p>Una vez tenemos creado el entorno virtual es hora de instalar dependencias.<br>Esto habitualmente se podría hacer con un simple <strong>pip install &lt;python-package&gt; </strong>pero si queremos utilizar este proyecto en otros entornos, lo recomendable será crear un fichero con todas las dependencias que vayamos a necesitar.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b27e9c514d60859f22ed5779be1b475/href">https://medium.com/media/2b27e9c514d60859f22ed5779be1b475/href</a></iframe><p><strong>Instala las dependencias</strong></p><p>Para ello ejecuta el siguiente comando:</p><pre>pip install -r requirements.txt</pre><p><strong>Genera tu archivo de claves</strong></p><p>Obtén tus credenciales de AWS, tanto el ACCESS_KEY_ID como SECRET_ACCESS_KEY. Las utilizaremos para que nuestros playbooks puedan conectarse a nuestra cuenta de AWS a través de boto y boto3. Estas claves se obtienen después de la creación del usuario y las puedes encontrar en tu IAM.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f23fdaf6621f67bf95a53e9ab515de29/href">https://medium.com/media/f23fdaf6621f67bf95a53e9ab515de29/href</a></iframe><p><strong>Define las carácterísticas de la instancia</strong></p><p>En este archivo se definen las características de la instancia que quieres desplegar. Es probable que en tu cuenta de AWS tengas más instancias que no has levantado utilizando estas plantillas y que no querrás borrar cuando elimines las instancias desplegadas con Ansible. Para ello utilizaremos unos tags que nos permitirán filtrar solo las instancias que deseas eliminar.</p><p>Fíjate en el atributo <strong>type </strong>dentro de <strong>infra_tags_node</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a468c73f2d22211aa77bcc11c0644fc4/href">https://medium.com/media/a468c73f2d22211aa77bcc11c0644fc4/href</a></iframe><p><strong>Create un inventario local</strong></p><p>Ansible trabaja contra varios sistemas de tu infraestructura al mismo tiempo. Lo hace seleccionando partes de los sistemas listados en el archivo de inventario de Ansible, que por defecto se guarda en la ubicación <strong>/etc/ansible/hosts</strong>. Para especificar un inventario diferente utiliza la opción<strong> -i &lt;ruta&gt;</strong> en la línea de comandos.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/04beff0e8f8f198e8ea3b79a5c0f1ffb/href">https://medium.com/media/04beff0e8f8f198e8ea3b79a5c0f1ffb/href</a></iframe><p><strong>Define las plantillas</strong></p><p>Para este caso vamos a definir dos plantillas genéricas. Una para desplegar instancias y otra para eliminarlas. En ellas se hará uso de los archivos anteriormente definidos.</p><p><strong>Plantilla de creación</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/02ec479ade0bd35a1d5e31d841ac71bf/href">https://medium.com/media/02ec479ade0bd35a1d5e31d841ac71bf/href</a></iframe><p><strong>Detalles a tener en cuenta:</strong></p><ul><li>Fíjate que a nuestra instancia le estamos añadiendo un volumen de 8gb. Mediante el parámetro<strong> delete_on_termination: true </strong>haremos que automáticamente se elimine cuando la instancia se elimine.</li><li>También hemos definido un grupo de seguridad con unas determinadas reglas de entrada/salida. Posteriormente añadimos la instancia a ese grupo mediante el parámetro <strong>group_id</strong>.</li></ul><p><strong>Plantilla de borrado</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1ca41357ffcbf6180c59192987a538a3/href">https://medium.com/media/1ca41357ffcbf6180c59192987a538a3/href</a></iframe><p><strong>Detalles a tener en cuenta:</strong></p><ul><li>Para decidir que instancias eliminamos definimos un filtro que puede observarse en la <strong>línea 6, </strong>ese filtro debe coincidir con el filtro anteriormente mencionado en la plantilla de despliegue.</li></ul><p><strong>Utiliza un Makefile</strong></p><p>Para centralizar todos los comandos que tengamos que realizar sobre un terminal configuramos un <strong>Makefile </strong>donde agrupamos los comandos necesarios para realizar una acción y le añadimos un pseudónimo para que sea más cómodo, facil de recordar y rápido de utilizar.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d79eee2ac374e745070e1e237a0cab6d/href">https://medium.com/media/d79eee2ac374e745070e1e237a0cab6d/href</a></iframe><p><strong>Ejecución de un despliegue</strong></p><p>Mediante el comando <strong>make deploy-server</strong> desplegamos una instancia que hayamos definido en aws:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5F2_bm0_IqYYWW_hcKL97Q.png" /><figcaption>make deploy-server</figcaption></figure><p>Nos aseguramos en nuestra cuenta AWS que se ha desplegado la instancia.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tjVjdqpkMn7f6NjENOkXHQ.png" /><figcaption>AWS console</figcaption></figure><p><strong>Ejecución de un borrado</strong></p><p>Para este caso utilizaremos el comando <strong>make delete.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GLETRc7IBEIOtIbYR3aG6g.png" /></figure><p>Nos aseguramos que la instancia se ha terminado correctamente:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9370gj1Q9NPYaF5Z5LqHfg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5656392cc938" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>