<?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 Pedro R. Mendonça on Medium]]></title>
        <description><![CDATA[Stories by Pedro R. Mendonça on Medium]]></description>
        <link>https://medium.com/@mendoncaDS?source=rss-2c03b4a35f41------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*iEyrlFD8k5HODAvqLvim8A.jpeg</url>
            <title>Stories by Pedro R. Mendonça on Medium</title>
            <link>https://medium.com/@mendoncaDS?source=rss-2c03b4a35f41------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 01:33:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mendoncaDS/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[PostgreSQL ETL using GCP VM and Azure Container Apps]]></title>
            <link>https://medium.com/@mendoncaDS/postgresql-etl-using-gcp-vm-and-azure-container-apps-8949ee4f940e?source=rss-2c03b4a35f41------2</link>
            <guid isPermaLink="false">https://medium.com/p/8949ee4f940e</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Pedro R. Mendonça]]></dc:creator>
            <pubDate>Wed, 13 Sep 2023 05:10:14 GMT</pubDate>
            <atom:updated>2023-09-14T17:18:12.902Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*3L1biZNY926DfsVoV2llpA.jpeg" /></figure><h3>.0 Introduction</h3><p>In this article you will learn to build a PostgreSQL database in a Google Cloud Platform VM (Virtual Machine), and update it recurrently using a containerized routine in Python.</p><p>The VM is set to fall under free tier specifications, but there is no guarantee. Create a new GCP account and use your free credits to find out.</p><p>We will be using cryptocurrency markets data from Binance, but you can swap the database contents and the Python routine however you want.</p><p>This is a good project for learning SQL, containerization, and Cloud platforms. After you are done with it, you will have an always up to date database that you can use to serve any app you develop!</p><p><a href="https://github.com/mendoncaDS/postgreSQL-binance-prices">Check out the project’s repository!</a></p><h3>.1 Setting Up the VM</h3><p>For the VM, we use GCP. We won’t go through account setup, so look up how you can create your own.</p><h4>.1.0 Create a firewall rule within GCP to allow the VM web access</h4><ul><li>Within GCP console, search for VPC Networks</li><li>Select Firewall in the left sidebar</li><li>Click “Create Firewall Rule” up top</li><li>Give it a name</li><li>Set target tag: “allow-tcp-5432”</li><li>Set source IPv4 ranges to 0.0.0.0/0</li><li>Set specified protocols and ports to TCP, port 5432</li><li>Most settings are fine as default.</li></ul><p>Now that we have a firewall rule, we can create the VM.</p><ul><li>Search for Compute Engine</li><li>Click “Create Instance” up top</li><li>Give it a name</li><li>Go to <a href="https://cloud.google.com/free/docs/free-cloud-features#compute">this link</a> to check free tier regions, and chose one of them</li><li>Choose an e2-micro machine to fall under free tier. Check <a href="https://cloud.google.com/free/docs/free-cloud-features#compute">this link</a></li><li>Click “Change” under Boot Disk and change to “standard persistent disk” for free tier. Up to 30gb in free tier. Check <a href="https://cloud.google.com/free/docs/free-cloud-features#compute">this link</a></li><li>Expand “Advanced Options” at the end of the page, then “Networking” under that</li><li>In “Network tags”, enter “allow-tcp-5432” to bind the rule we previously set to this VM</li><li>Most settings are fine as default.</li></ul><p>The VM should boot correctly and be readily running in your GCP account.</p><h4>.1.1 Setup Docker inside the VM</h4><p>We need to setup Docker before pulling the image.</p><ul><li>Open the VM SSH terminal from the Compute Engine page. You should see your brand new VM there, and an option to SSH under the “Connect” column</li><li>Run the commands described in <a href="https://docs.docker.com/engine/install/debian/">this page</a>:</li></ul><pre>sudo apt-get update<br><br><br>sudo apt-get install ca-certificates curl gnupg lsb-release<br><br><br>sudo install -m 0755 -d /etc/apt/keyrings<br><br><br>curl -fsSL https://download.docker.com/linux/debian/gpg | sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpg<br><br><br>sudo chmod a+r /etc/apt/keyrings/docker.gpg<br><br><br>echo \<br>  &quot;deb [arch=&quot;$(dpkg --print-architecture)&quot; signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/debian \<br>  &quot;$(. /etc/os-release &amp;&amp; echo &quot;$VERSION_CODENAME&quot;)&quot; stable&quot; | \<br>  sudo tee /etc/apt/sources.list.d/docker.list &gt; /dev/null<br><br><br>sudo apt-get update<br><br><br>sudo apt-get install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin</pre><p>Now your VM should have Docker working. To test it, run:</p><pre>sudo docker run hello-world</pre><p>If Docker is installed and working correctly, this will print a message.</p><h4>.1.2 Pull and run the PostgreSQL image</h4><p>To pull the image:</p><pre>sudo docker pull postgres</pre><p>To run a container using it:</p><pre>sudo docker run --name [container-name] -e POSTGRES_PASSWORD=[your-password] -v postgres:/var/lib/postgresql/data -p 5432:5432 -d postgres</pre><p>Where</p><ul><li>[container-name] is the name you want to give your container.</li><li>[your-password] is the password you will need to connect to the database, once it’s running.</li></ul><p>You can run this to check running containers. Your PostgreSQL container should be there.</p><pre>sudo docker ps</pre><p>To use the database, you need the VM external IP. You can find it in GCP’s Compute Engine page. You can connect to the database through Python using the External IP and the PostgreSQL password you just set earlier, so save them.</p><h3>.2 Create the Updater Image</h3><p>Currently, the VM is running PostgreSQL, but there is no data. Ideally, you would populate the database with all available data from your own machine, then get the updater running from a cloud to keep the database up to date.</p><h4>.2.0 Initialize table for crypto prices</h4><p>So, before getting to the updater, we will create a table in the database, and make the first data insertion to it.</p><p>Before running scripts locally, create an environment by running the following command, either from a main Python installation, or preferably from a brand new venv such as conda:</p><pre>pip install -r requirements.txt</pre><p>Also, write your VM’s external IP and PostgreSQL password in the .env file, so scripts can connect to your database.</p><p>Then, you can run the script “create_market_data.py” to create the table “market_data” in your database.</p><pre>python create_market_data.py</pre><p>And then run this script with your desired parameters to download the data from the Binance API and push it to the database.</p><pre>python new_symbol_freq.py -symbol BTCUSDT -freq 1d</pre><h4>.2.1 Test and Build the Image</h4><p>Before building the image you should test the script. Try running the updater routine locally:</p><pre>python update_database.py</pre><p>This will open a Flask application on port 8080. Try opening localhost:8080 in your web browser.</p><ul><li>Loading this page triggers the update routine</li><li>This routine reads all combinations of “symbol” and “frequency” in the database</li><li>It will download and update every new datapoint from the last one to the most recent, for every combination of symbol and frequency already available in the table.</li><li>If the routine ran with no errors, it probably worked. Check if your database is updated.</li></ul><p>To build the image, you can use the dockerfile available in <a href="https://github.com/mendoncaDS/postgreSQL-binance-prices">the repository</a>. Ensure you have Docker running in your system, then try building the image:</p><pre>docker build -t update_database .</pre><p>If everything went right, you can proceed to the next step, but you may want to test the image by running it locally.</p><pre>docker run -it --rm -p 8080:8080 update-database:latest /bin/bash</pre><h3>.3 Run a Container App in Azure</h3><h4>.3.0 Push image to Container Registry</h4><p>Before pushing your image, make sure you have a Container Registry to store your images. Also, for that you need a Resource Group. Navigate the Azure Portal to create both the Resource Group and a Container Registry.</p><p>After that, install the azure CLI in your terminal. If you haven’t yet, follow <a href="https://learn.microsoft.com/en-us/cli/azure/install-azure-cli">this page</a>.</p><p>Then, login from terminal and authenticate Container Registry:</p><pre>az login<br><br>az acr login --name your-registry-name</pre><p>Tag the image you created before:</p><pre>docker tag update-database:latest your-registry-name.azurecr.io/update-database:latest</pre><p>Then push the image to the Container Registry:</p><pre>docker push donsacontainerregistry.azurecr.io/update-database:latest</pre><p>If everything worked, you should see the image available in the Container Registry page in Azure Portal.</p><h4>.3.1 create the Container App using the image</h4><ul><li>In Azure Portal, go to Container Apps</li><li>Click in “+ Create”, up left</li><li>Give the app a name</li><li>In “Container”, uncheck “Use quickstart image”. Give the container a name, and select the image you pushed earlier.</li><li>You can change CPU and Memory for the container, but you can also change this after the app is up and running.</li><li>In Ingress, enable ingress and accept traffic from anywhere.</li><li>Type 8080 into “Target port”</li><li>Review and create the app</li></ul><p>In the app page in the portal, you can copy the URL ofthe app. You can open it in your browser to trigger the routine and test it.</p><h3>.4 Setup a cron job using cron-job.org</h3><p><a href="http://cron-job.org/">cron-job.org</a> is an amazing platform to get an app like this to run recurrently in a simple and free way.</p><p>Before this I made the mistake of using Azure’s Logic Apps just for a cron job. This cost me a few dollar for a single night, even though the actual app routine cost close to nothing.</p><p>Just create an account and add a cron job pointing to your Container App URL. You can personalize the execution schedule.</p><h3>.5 Conclusion</h3><p>In this article, we:</p><ul><li>Created a VM in GCP and installed a PostgreSQL image to run our database online 24/7</li><li>Built a Docker Image of a simple service that updates the database every time it receives a request from the web</li><li>Got this routine running recurrently in Azure Container Apps, thanks to <a href="http://cron-job.org/">cron-job.org</a></li></ul><p>Notice that both GCP and Azure were used. I tried getting GCP Cloud Run to work but Azure Container Apps were just smoother. The VM is specifically on GCP as an attempt to fall under free tier.</p><p>Because this project has two separate components, being the database server and the updater routine, they can be deployed in different cloud platforms with no problems.</p><p>Notice that not many security measures were specified. Even though the database has a password, you wouldn’t want to have it’s IP “leaked”. In fact, the very Docker image we built has the .env file with access information hard coded in it, password and IP. This is not a big problem because we pushed the image directly to Azure, so <strong>don’t</strong> host it for free in Docker Hub.</p><p>Also, do not leak you Container App’s URL, as someone could spam it and that would cost you money.</p><p>See you in the next article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8949ee4f940e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Trading Bot Model Selection in Python]]></title>
            <link>https://medium.com/@mendoncaDS/trading-bot-model-selection-in-python-7f01f3769f56?source=rss-2c03b4a35f41------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f01f3769f56</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[trading-bot]]></category>
            <category><![CDATA[cryptocurrency]]></category>
            <dc:creator><![CDATA[Pedro R. Mendonça]]></dc:creator>
            <pubDate>Wed, 10 May 2023 09:07:12 GMT</pubDate>
            <atom:updated>2023-05-10T10:47:39.814Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part 3 — Selecting and Analyzing Models</h4><h3>Introduction</h3><p>In the previous articles, we delved into the live bot class responsible for handling API orders on the exchange, as well as the user interface. You can find those articles <a href="https://medium.com/@mendoncaDS/trading-bot-in-python-99ce77077372">here</a> and <a href="https://medium.com/@mendoncaDS/trading-bot-ui-in-python-571f6710ac5e">here</a>. Don’t forget to check out the <a href="https://github.com/mendoncaDS/binance_live_bot">project’s repository</a>!</p><p>In this final article, we’ll take an in-depth look at the model selection process. It’s important to note that the trading strategy doesn’t rely solely on the model’s predictions. Regardless of the accuracy of the predictions, we still need well-defined conditions to convert them into actionable orders.</p><h3>Parameters and Timeframes to Consider</h3><p>Currently, orders are generated from predictions using a linear function:</p><p><strong>exposure</strong> = <strong>a</strong> * <strong>prediction</strong> + <strong>b</strong></p><ul><li><strong>prediction</strong>: A value between 0 and 1 (a percentage) representing the percentage difference between the predicted and current moving average.</li><li><strong>exposure</strong>: A value between 0 and 1 that determines the percentage of the portfolio exposed to the asset being traded.</li><li><strong>a</strong>: The multiplier, which controls the sensitivity of the exposure in relation to the prediction.</li><li><strong>b</strong>: The constant.</li></ul><p>The coefficient “a” determines the sensitivity of the exposure in relation to the prediction. If a is set to a high value, the trading bot will take on a higher level of risk in response to a prediction, leading to larger exposure and potentially greater returns. Conversely, if a is set to a low value, the bot will take on a lower level of risk, resulting in smaller exposure and potentially smaller returns.</p><p>The coefficient “b” determines the constant added to the exposure level. A high value for b will lead to a more aggressive trading strategy, where the bot will have a higher exposure level even when the prediction is close to the current moving average. On the other hand, a low value for b will result in a more conservative trading strategy, where the bot will only have significant exposure levels when the prediction is far from the current moving average.</p><p>The ideal coefficients (a, b) are not immediately obvious. Additionally, the original article and repository version used minute data resolution, while the second version used hourly data. The trading system could also be applied to daily or weekly data, so the optimal timeframe remains unclear.</p><p>Moreover, the prediction horizon can vary. Predicting a 24-hour moving average one day or one week from now are different tasks. To simplify this assessment, we’ll always use the moving average window plus one as the prediction horizon. What is presented in the current article is a workflow to select the parameters a and b, but such workflow can be easily extended to select other characteristics of the strategy, such as timeframe and prediction horizon.</p><h3>Model selection workflow</h3><p>To evaluate the historical performance of our trading strategies, we will implement backtesting. Backtesting is a process that involves evaluating a trading strategy’s performance using historical data. Its purpose is to simulate how the strategy would have performed if it had been used to trade in the past. This is accomplished by applying the strategy’s rules to historical data and analyzing the results.</p><p>Backtesting also enables us to optimize a strategy by identifying which parameters and rules are the most effective. We can test a strategy with different combinations of parameters and determine which ones produce the best results. This information can then be used to refine and improve the strategy.</p><p>When training a model, we typically obtain an average error. This error is often used as a training benchmark, meaning that the model with the lowest average error metric is selected. However, this average error doesn’t directly translate into profits. Backtesting serves as a separate step in training and selecting a model, where we test the strategy on historical data to assess its performance and profitability. It’s essential to verify the historical performance of a model before choosing the one with the smallest error, as a strategy with higher average prediction error but greater profits might be preferable. Therefore, backtesting is a crucial step in model selection, enabling us to choose the most profitable strategy with the least amount of risk.</p><p>With sufficient computing power and speed, we could run numerous iterations of training models, varying feature engineering, machine learning algorithms, and more. As a result, we’d have multiple trained models in the “models” folder:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/238/1*YuYZvWM8hKHv0KwsOBinhw.png" /></figure><p>In this example, the only difference between these models is the window of the moving average being predicted. However, you could iterate any modifications you wish to test and optimize during model training.</p><p>Each of these models has its own average error. But how do they compare when it comes to actually trading? And what would be the best parameters (a, b) for each model?</p><p>To answer these questions, we will perform a grid search on the performance of each model, with each combination of a and b parameters, measured by the sharpe ratio of the backtest.</p><p>The Sharpe ratio is calculated by dividing the portfolio’s excess return (the portfolio’s return minus the risk-free rate) by its standard deviation. In other words, it measures how much return an investor earns per unit of risk taken. A higher Sharpe ratio indicates that the portfolio has a better risk-adjusted return than one with a lower Sharpe ratio. We will be using the sharpe ratio that is built in vectorbt, the backtesting package used.</p><h3>Implementing Backtesting</h3><p>We’ll use vectorbt to backtest our strategies. vectorbt is a very handy Python package, and generating a backtest is quite simple.</p><p>The first step is generating an exposure vector, by running a prediction through the linear function previously described. For that, I created this function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ece14e7a67bec5e39e47dfe0a98a69f8/href">https://medium.com/media/ece14e7a67bec5e39e47dfe0a98a69f8/href</a></iframe><p>The function calculates the exposure level for each data point in the DataFrame by applying the lambda function. The lambda function computes the exposure level using the linear function, taking the minimum and maximum values between 0 and 1. If the opening price is less than the predicted moving average, the exposure level is calculated, otherwise, it is set to 0. The function then returns a Series object containing the exposure levels for each data point.</p><p>“colname” is the column name in the DataFrame where the predictions are stored.</p><p>With “genExposure”, we can define a function that runs the backtest and returns a “portfolio” object, a vectorbt class with information about the backtest.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/75b713a2e234aea8c43308272bf5c009/href">https://medium.com/media/75b713a2e234aea8c43308272bf5c009/href</a></iframe><ol><li>It calls the <strong>genExposure</strong> function with the given arguments to generate the exposure levels for each data point in the DataFrame.</li><li>It creates a vectorbt Portfolio object (<strong>pf</strong>) using the <strong>vbt.Portfolio.from_orders</strong> method.</li></ol><ul><li>The opening price is used to execute orders, instead of the closing price.</li><li>The setting size_type is assigned to ‘targetpercent’ indicates that the order sizes are expressed as a percentage of the total portfolio value.</li><li>The data often has gaps, so it’s good to manually set a frequency so all metrics are computed in the backtest.</li></ul><p>By utilizing this function, you can perform a backtest with specific exposure settings, allowing you to analyze and optimize the performance of your trading strategy based on the exposure levels generated by the <strong>genExposure</strong> function.</p><h3>Selecting a model with grid search</h3><p>Grid search is effective in finding the optimal combination of parameters, but it can be time-consuming and computationally expensive, especially when testing a large number of parameters. It’s important to carefully select the ranges of values for each parameter and prioritize the most important parameters to minimize the computational cost.</p><p>The function to run all parameters combinations, and also compare the model predictions with the “perfect” predictions (the actual SMA but shifted back) is as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0f623879fc136a751f9a50812d39095f/href">https://medium.com/media/0f623879fc136a751f9a50812d39095f/href</a></iframe><p>The function takes the following arguments:</p><ul><li><strong>data</strong>: The DataFrame containing the historical data.</li><li><strong>exposureConstants</strong>: A list of exposure constants (<strong>b</strong>) to be tested.</li><li><strong>exposureMultipliers</strong>: A list of exposure multipliers (<strong>a</strong>) to be tested.</li><li><strong>maPeriod</strong>: The time period for calculating the simple moving average.</li><li><strong>model</strong>: The machine learning model to be used for generating predictions.</li><li><strong>modelParamsDict</strong>: A dictionary containing the model&#39;s parameters.</li><li><strong>targetScaler</strong>: The scaler used for transforming the target variable.</li><li><strong>scalers</strong>: A list of scalers used for preprocessing the features.</li></ul><p>The function performs the following steps:</p><ol><li>Calculates the current SMA and the shifted SMA using the given <strong>maPeriod</strong>.</li><li>Generates predictions using the <strong>genPreds</strong> function and concatenates them with the current SMA.</li><li>Initializes empty DataFrames (<strong>pfShiftedSMA_DF</strong> and <strong>pfPred_DF</strong>) to store the backtest results for the shifted SMA and model predictions, respectively.</li><li>Iterates through all combinations of exposure constants and multipliers, and for each combination:<br>- Calls the backtestFromExposureSettings function to perform backtests using both the shifted SMA and model predictions.<br>- Computes the Sharpe ratios for both backtests and stores them in the corresponding DataFrames.</li><li>Concatenates the two result DataFrames (<strong>pfShiftedSMA_DF</strong> and <strong>pfPred_DF</strong>) into a single DataFrame (<strong>backtests_DF</strong>), and calculates the difference between the Sharpe ratios of the model predictions and the shifted SMA.</li><li>Returns the <strong>backtests_DF</strong> DataFrame, which contains the Sharpe ratios for all combinations of exposure settings and the differences between the model predictions and shifted SMA backtests.</li></ol><p>Note there are some custom functions (example genPreds) that won’t be discussed here. You can take a look into them in the project’s repository.</p><p>In the following section, we’ll dive into automating the execution of <strong>searchExposureBacktest</strong> to backtest all trained models. This will allow us to evaluate the performance of each model and compare the results easily.</p><h3>Automating Backtesting for All Trained Models</h3><p>The function <strong>backtestModels</strong> takes care of automating the backtesting process for all trained models. Here’s the function and a breakdown of the steps it performs:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c1540359dc797da2c701af7ea030009/href">https://medium.com/media/6c1540359dc797da2c701af7ea030009/href</a></iframe><ol><li>It first checks if the “backtesting_ohlcv_data.csv” file exists. If not, it downloads the historical data from Binance using the <strong>vbt.BinanceData.download</strong> method and saves it to a CSV file. If the file exists, it reads the data from the file and converts the index to datetime objects.</li><li>Next, it loads the model, model parameters, target scaler, and other scalers using the <strong>loadModel</strong> function.</li><li>The <strong>searchExposureBacktest</strong> function is then called to calculate backtest results based on the input parameters, and the results are saved in the <strong>backtests_DF</strong> variable.</li><li>A folder is created with the name “modelBacktests/backtest_maPeriod_{maPeriod}” if it doesn’t already exist.</li><li>The backtest results are saved in a CSV file in the created folder.</li><li>Lastly, a histogram plot of the shifted SMA and predicted values is generated and saved as an image file in the folder.</li></ol><p>You can create a loop to call this function and iterate through your trained models. The code snippet below provides an example of how you can do this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f4acdb35d3c03cadae0dcb2a89782b7b/href">https://medium.com/media/f4acdb35d3c03cadae0dcb2a89782b7b/href</a></iframe><p>Keep in mind that this script may take some time to run, as is usual with grid search.</p><h3>Analyzing the Results of the Backtest Grid Search</h3><p>Now, let’s analyze the resulting histograms for the Sharpe ratios of each model. The X-axis represents the Sharpe ratio, while the Y-axis shows the frequency of such ratios among all combinations of parameters backtested.</p><h4>SMA3:</h4><p>Best shifted SMA Sharpe: 22.37</p><p>Best prediction Sharpe: 0.67</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w4TdkmjBzXrfJTp5DfmvTQ.png" /></figure><p>As the most short-sighted model we trained, we’d expect better results if the predictions were more precise. However, because the model tries to predict too close to the current moment (4 data points/hours from now), it deals with a lot of noise, resulting in mostly negative results.</p><h4>SMA6:</h4><p>Best shifted SMA Sharpe: 20.26</p><p>Best prediction Sharpe: 1.23</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uh4NszngfRHPCJlWrbxDOQ.png" /></figure><p>Interestingly, prediction results are slightly better in this model compared to the SMA 3 model, while the shifted SMA performs worse. This is likely due to the reduction of noise in higher timeframes — the model extracts fewer patterns from lower timeframes, while the shifted SMA behaves like a “perfect” prediction that can predict all random noise. We should see the difference between the prediction and the shifted SMAs Sharpe ratios decrease as we increase the timeframe.</p><h4>SMA12:</h4><p>Best shifted SMA Sharpe: 17.33</p><p>Best prediction Sharpe: 2.21</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xJOe1KWES5RUvyOCrExwKw.png" /></figure><p>As expected, the pattern continues with better results for this model.</p><h4>SMA18:</h4><p>Best shifted SMA Sharpe: 15.83</p><p>Best prediction Sharpe: 3.24</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9wFuehG_NyyLRrt6fQhtKA.png" /></figure><p>The pattern persists, and the distribution of Sharpe ratios from the prediction backtests is entering an interesting area. Most of them have good Sharpe ratios, which should raise some skepticism.</p><h4>SMA24:</h4><p>Best shifted SMA Sharpe: 14.66</p><p>Best prediction Sharpe: 3.98</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i5rwy7qM6W0XL-l8uSEjiA.png" /></figure><p>The results continue to improve for this model.</p><h4>SMA36:</h4><p>Best shifted SMA Sharpe: 12.53</p><p>Best prediction Sharpe: 5.40</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qVVziHppzHsKBbqlF2Ivcg.png" /></figure><p>The difference between the shifted SMA and prediction Sharpe ratios continues to decrease, while prediction Sharpe ratios are getting too good to be true.</p><h4>SMA48:</h4><p>Best shifted SMA Sharpe: 11.45</p><p>Best prediction Sharpe: 5.47</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hF_J00k-tB1H8iKKdEepKw.png" /></figure><h4>SMA96:</h4><p>Best shifted SMA Sharpe: 8.78</p><p>Best prediction Sharpe: 5.39</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8pHnHGU3kXzfOWOxpJIT1A.png" /></figure><p>For the first time, the pattern is broken: the SMA96 model seems to have worse results than the SMA48, which has a lower timeframe.</p><h4>SMA168:</h4><p>Best shifted SMA Sharpe: 7.06</p><p>Best prediction Sharpe: 4.50</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6vgq6ODoelXFabQ8Y4YqmQ.png" /></figure><p>The inversion of the pattern is repeated here.</p><h4>SMA336:</h4><p>Best shifted SMA Sharpe: 5.50</p><p>Best prediction Sharpe: 3.51</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BEBsDo8_yCPf3cudhylNtQ.png" /></figure><p>Again, worse prediction results. One interesting thing to note is that the shifted SMA continued to show worse Sharpe ratios the longer the timeframe. And, even though this model has worse results than SMA48, it seems that the prediction histogram has a lower variance. This might indicate more consistent results, even though they are generally lower. The lower shifted SMA results indicate less noise in the target variable, indicating a target variable with more pattern in relation to noise — better for modelling.</p><p>The best performing model, from this analysis, is SMA48, with a backtested Sharpe ratio of 5.47.</p><p>From now on, to close this article, we will work on this model solely, based on the premise that it overperformed the others.</p><h3>Investigating the Selected Model</h3><p>You can run grid search to investigate different combinations of parameters with your models, load different models, run backtests in specific sections of the time series, or even run these strategies on other crypto pairs such as ADAUST.</p><p>The following notebook isa straightfoward way to plot the backtest and check its stats, while still being able to quickly test new things.</p><p><a href="https://www.kaggle.com/code/pedrormendonca/modelsbacktestingnb?kernelSessionId=129001471">modelsBacktestingNB</a></p><h3>Conclusion</h3><p>This was an extensive project, as well as blogposts, and especially this one. However, some things should not be left unsaid.</p><p>As we are dealing with time series, the data should be further separated preemptively to accommodate the model training, and the backtest section presented in this article. Also, the model training takes random entries from the dataset to generate train test and validation sets, which means treating it as cross sectional data. This is not recommended. Something like cross validation is better. All in all, these factors most probably explain the extraordinary results in backtests.</p><p>I hope this series of articles is of good use to you. Make sure to follow me and engage with my work, that makes a difference! Cheers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f01f3769f56" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Trading Bot UI in Python]]></title>
            <link>https://medium.com/@mendoncaDS/trading-bot-ui-in-python-571f6710ac5e?source=rss-2c03b4a35f41------2</link>
            <guid isPermaLink="false">https://medium.com/p/571f6710ac5e</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[algorithmic-trading]]></category>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[bitcoin]]></category>
            <dc:creator><![CDATA[Pedro R. Mendonça]]></dc:creator>
            <pubDate>Sat, 15 Apr 2023 21:27:37 GMT</pubDate>
            <atom:updated>2023-04-15T21:27:37.603Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part 2 — The UI</h4><h3>Overview</h3><p>In this second article of the trading bot, we will take a look into the UI of the bot. It was built using the Streamlit package, which is pretty handy.</p><p>If you didn’t read the first one, <a href="https://medium.com/@mendoncaDS/trading-bot-in-python-99ce77077372">you can read it here</a>. It describes the bot class, which handles the interface between the bot and the exchange. Note that I’ve now refactored the bot to trade in 1 hour timeframe, instead of 1 minute, as in the first article.</p><p>Also, <a href="https://github.com/mendoncaDS/binance_live_bot">this is the project’s repository</a>, make sure to check it out.</p><h3>Loading the data</h3><p>The bot class saves trading data in .csv files. The UI script begins by trying to load this data:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/55c10c7207cb52ee3f016b1cc3c766cf/href">https://medium.com/media/55c10c7207cb52ee3f016b1cc3c766cf/href</a></iframe><p>As you can see, some data is gathered from the .env file.</p><p>The page is constructed by calling mainLayout(), which receives the DataFrames loaded by loadFromCsv(). Let’s take a look into it.</p><p>The first part of mainLayout() sets up variables:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/95d26daeef95c986eaa70c8b5c87e81e/href">https://medium.com/media/95d26daeef95c986eaa70c8b5c87e81e/href</a></iframe><p>The comments in the code make it easy to understand. lookBackRangeSlider() is used in the trading tab.</p><h3>📈 Trading tab</h3><p>Trading and metrics tabs are the ones which display useful data. Let’s take a look into the “📈 Trading” tab, which has some graphs. Note that this is the most extensive section of code in this article.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f0dc8c1e9c540b402172b7c0c102d337/href">https://medium.com/media/f0dc8c1e9c540b402172b7c0c102d337/href</a></iframe><p>This code generates the following page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1BgTP2i74vkDKG7fnezAtQ.png" /></figure><p>Streamlit is pretty good at rearranging the page to look good in mobile.</p><p>As we are here, let’s take a look into the “👀 About” tab. Not the code, as it has nothing interesting, but what it says. It explains the bot and the graphs in the “📈 Trading” tab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/1*Bf1jO3S_ltA3ziBX762GQQ.png" /></figure><p>Now, let’s take a look into the “📊 Metrics” tab.</p><h3>📊 Metrics tab</h3><p>This tab aggregates important info about the bot performance. This is the code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f8a5cae17ccb415d741084cba439364/href">https://medium.com/media/4f8a5cae17ccb415d741084cba439364/href</a></iframe><p>This code generates the following page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TWuELNvfOijUc1m5IZewFg.png" /></figure><p>There isn’t much to comment in this code.</p><h3>⚙ Settings tab</h3><p>The settings tab serves the purpose of displaying any customization available for the user. Currently, it’s only possible to define refreshing for the app. Here’s the code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/de36c381aa62ab4d5a6290a7daa49dee/href">https://medium.com/media/de36c381aa62ab4d5a6290a7daa49dee/href</a></iframe><p>Here’s how it looks:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yo_gTkVsjCMPLpfgMQH8oA.png" /></figure><p>That’s it for today. If you have any questions or suggestions, feel free to comment or make a pull request in GitHub!</p><p>See you in the next article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=571f6710ac5e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Trading Bot in Python]]></title>
            <link>https://medium.com/@mendoncaDS/trading-bot-in-python-99ce77077372?source=rss-2c03b4a35f41------2</link>
            <guid isPermaLink="false">https://medium.com/p/99ce77077372</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[bitcoin]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[algorithmic-trading]]></category>
            <dc:creator><![CDATA[Pedro R. Mendonça]]></dc:creator>
            <pubDate>Tue, 11 Apr 2023 12:32:53 GMT</pubDate>
            <atom:updated>2023-04-15T21:31:22.630Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part 1 — The Bot Class</h4><h3>Overview</h3><p>This project has been on my mind for quite some time. Indeed, it has been the main motivation guiding my studies:</p><ul><li>What do I need to know to build profitable automated trading algorithms, deploy them to a cloud, and monitor them while they operate?</li></ul><h4>Components</h4><p>The project is comprised of 3 essential components:</p><ul><li>The Bot Class<br>- Refreshes current portfolio balances<br>- Refreshes market data<br>- Computes new prediction based on new data<br>- Calculates new “ideal portfolio” based on prediction<br>- Executes orders to achieve such portfolio<br>- Saves what happened to .csv files (data, portfolio value, prediction, orders, etc)</li><li>The Streamlit Dashboard<br>- Reads data from the .csv files the bot is constantly updating<br>- Shows all information in a neat UI</li><li>The Model<br>- The most modular component in the project<br>- In this first article, we will be using a placeholder model</li></ul><p>This article delineates the bot class. Note that it has not yet been factored for production.</p><p>You can explore the code of this project <a href="https://github.com/mendoncaDS/binance_live_bot">by visiting this repository</a>.</p><h3>The bot class</h3><p>As the predictions are made by the model, and the gathering and processing of data isn’t very exciting in this case (concatenating rows to existing DataFrame, saving to .csv, simple operations), the juice of the bot class consists of:</p><ul><li>Enforcing the timing of operations correctly</li><li>Translating model predictions into orders to the exchange</li><li>Placing valid orders to the exchange as to achieve such desired portfolio<br>- This involves rounding numbers, verifying available balances, and checking minimal order value</li><li>Being stable as to not interrupt trading at crucial moments</li></ul><p>It’s good to have a quick bot, however, we are dealing with Python, and not really optimizing for speed. The bot is designed to run its routine every 1 minute, which is quick enough to detect trends early.</p><h4>Running the bot</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea08e609783ede832e19710f09098c02/href">https://medium.com/media/ea08e609783ede832e19710f09098c02/href</a></iframe><ul><li>“modelName” is used to locate the model folder, which contains its scalers and parameters. More on these parameters later.</li><li>“symbol” determines which Binance market will be traded.</li><li>“minPctChange” limits the size of adjustments the bot is allowed to make in its portfolio (avoids spamming orders)</li><li>“exposureMultiplier” goes into the equation that translates a prediction into an ideal exposure to the asset</li><li>API key and secret to connect to exchange</li></ul><p>This code section is located at the end of “liveBotClass.py”, which defines the bot class, so the bot can be initialized by typing in the terminal from root folder:</p><pre>python scripts/liveBotClass.py</pre><h4>Bot inicialization</h4><p>Once the bot is instantiated, it runs the __init__ function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e3aedf7c5eda58154e862a8341e201f/href">https://medium.com/media/9e3aedf7c5eda58154e862a8341e201f/href</a></iframe><p>Inside self.initializeBot() are all the initialization functions which are called only when the bot is initialized. They check if there is already a folder for this bot, if so, it loads all past data the bot saved before it shut down. Else, it creates the folder and the files. This way, the bot can pick up from where it left off if anything goes wrong.</p><p>If you paid attention, maybe you noticed that self.mainTradeLoop() was called inside the async function to get the bot running</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/03540739670df23469dc22ddc12a4ead/href">https://medium.com/media/03540739670df23469dc22ddc12a4ead/href</a></iframe><p>This function calls refreshAll(), smartSignals() and saveFinish(), respectively, at the start of every minute. Before calling smartSignals() and saveFinish(), it checks if the data is up to date by comparing the current minute with the most recent minute in the market data (lastMarketDataTS).</p><p>Most of the code in this main loop serves the purpose enforcing this timing correctly.</p><h4>Refresh functions</h4><p>refreshAll() is a short function, but it calls a bunch of other functions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/517a4ad9bb039d0b196d88ebc2e1a418/href">https://medium.com/media/517a4ad9bb039d0b196d88ebc2e1a418/href</a></iframe><p>Though it is a bit longer, this code should not be hard to understand. To make it clearer, here is a mindmap of refreshAll():</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1_FPEEDcLL6BZcYOYH4T2w.png" /></figure><p>Green rectangles represent updates in class attributes, and yellow rectangles represent update in .csv files.</p><p>saveFinish() is not used in refreshAll(), it is called after smartSignals().</p><p>Once refreshAll() ran, the bot is updated and ready to make a decision.</p><h4>Trading functions</h4><p>All trading computations derive from smartSignals(), just like all data refreshing is done by calling refreshAll(). These functions sum up to a fair amount of code, but are the last piece of the bot class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ec28d5e9103f6a674ca29535273c676/href">https://medium.com/media/0ec28d5e9103f6a674ca29535273c676/href</a></iframe><p>To make it clearer, here is a map of smartSignals():</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iBHsL5eWfxm-Eetrd0nuOA.png" /></figure><p>As you can see by reading the code, there are a couple of operations to verify minimum notional, round the decimals of orders, double check available balances, etc. It is very important that the bot is stable as to not interrupt trading in key moments.</p><p>Finally, the bot calls saveFinish() at the end of the routine. saveFinish() saves the timestamp, portfolio value, asset exposure, and current prediction to preds.csv. This data is later used to display the UI.</p><h4>Does it work?</h4><p><a href="https://github.com/mendoncaDS/binance_live_bot">You can clone <strong>this repositor</strong>y</a><strong> </strong>to test the bot. If everything goes well, you should be able to do this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*LLMXTJwcCO2Ku11UyfvkPA.gif" /></figure><p>In the next article, we’ll look into the UI of the bot, which was done using streamlit.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99ce77077372" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Como gerar uma coleção NFT com Python]]></title>
            <link>https://medium.com/@mendoncaDS/como-gerar-uma-cole%C3%A7%C3%A3o-nft-com-python-33ebaef52775?source=rss-2c03b4a35f41------2</link>
            <guid isPermaLink="false">https://medium.com/p/33ebaef52775</guid>
            <category><![CDATA[nft]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[art]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Pedro R. Mendonça]]></dc:creator>
            <pubDate>Mon, 27 Feb 2023 22:28:21 GMT</pubDate>
            <atom:updated>2023-02-28T01:04:05.351Z</atom:updated>
            <content:encoded><![CDATA[<p>Os NFTs se popularizaram nos últimos anos. Apesar das críticas, muitas justificadas, a cada dia novas coleções NFT são lançadas, e os “degens” não perdem tempo para comprar e especular com as peças.</p><p>Com este artigo, você aprenderá a escrever um script em Python que combina imagens (“traits” — características de cada peça: background, acessórios, cores, etc) para gerar uma coleção. Uma das coisas viciantes em NFTs são os perfis de raridade dos traits da coleção. Quem já colecionou álbum de figurinhas deve lembrar da adrenalina ao abrir um pacotinho na expectativa de uma carta rara. Muitos jogos modernos também implementam mecânicas envolvendo probabilidade, com loot boxes, etc. Uma coleção NFT que se preze possui uma distribuição de traits instigante.</p><p>Pré requisitos:</p><ul><li>Editor de imagens. Usei o Photoshop.</li><li>Alguma familiaridade com Python</li><li>Criatividade</li></ul><p>Etapas do processo:<br> 1 - Gerar as imagens para cada trait. Elas devem ter fundo transparente, para serem sobrepostas posteriormente, e devem ser organizadas em pastas.<br> 2 - Gerar uma representação “virtual” de cada trait no Python.<br> 3 - Escrever uma função que combine os traits numa planilha da forma desejada (respeitando as raridades predefinidas) — esta planilha será a “planta” de sua coleção, nela está a “metadata” de todas as peças.<br> 4 - Escrever uma função que leia a planilha de características da coleção, e combine as imagens para gerar todas as peças.</p><p>Não parece difícil, certo?</p><h3>0. KBCAs</h3><p>Lhes apresento os KBCAs (pronuncia-se cabecinhas):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*klArcNUJf5m7hzrCFE9wXQ.png" /></figure><p>Os KBCAs servirão de exemplo para este artigo</p><p>Eles têm os seguintes traits, com suas possíveis variações:</p><pre>Type:<br>  0 - dark<br>  1 - light<br><br>BG:<br>  0 - human<br>  1 - alien<br><br>Hair:<br>  0 - bald<br>  1 - dots<br>  2 - ssss<br>  3 - spikes<br>  4 - baby<br>  5 - ronaldo<br>  6 - classy<br>  7 - brushed<br>  8 - emo<br><br>Eye:<br>  0 - small<br>  1 - oo<br>  2 - cool<br>  3 - naruto<br>  4 - 420<br>  5 - \\\\<br>  6 - blindfold<br>  7 - mad<br>  8 - xx<br>  9 - /|<br>  10 - &gt;&lt;<br>  11 - lasereyes<br>  12 - batshit<br>  13 - cute<br>  14 - glasses<br><br>Item:<br>  0 - no item<br>  1 - scar<br>  2 - cross<br>  3 - icross<br>  4 - spot<br>  5 - knife<br>  6 - yellowf<br>  7 - redf<br>  8 - bluef<br>  9 - magentaf<br>  10 - orangef<br>  11 - wine<br><br>Mouth:<br>  0 - .<br>  1 - x<br>  2 - flat<br>  3 - yawn<br>  4 - ~<br>  5 - 0<br>  6 - smirk<br>  7 - hungry<br>  8 - sad<br>  9 - :D<br>  10 - D:<br>  11 - lyingluffy<br>  12 - p<br>  13 - bojji</pre><p>Originalmente estes nomes faziam parte do código, mas agora servem apenas como referência externa, o código usa apenas os índices.</p><h3>1. Gerando imagens</h3><p>A estrutura de pastas utilizadas para armazenar as imagens que serão usadas pelo script será:</p><pre>- dark<br>  - bgs<br>  - eyes<br>  - hairs<br>  - items<br>  - mouths<br>- light<br>  - bgs<br>  - eyes<br>  - hairs<br>  - items<br>  - mouths</pre><p>Cada uma dessas pastas irá conter as imagens dos respectivos traits, nomeados por índice (Ex.: hair=classy -&gt; hairID=6)</p><p>O exemplo anterior de KBCA é um type light, seu correspondente type dark é:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*IsN-17PYi56EuFPwQPmLxA.png" /></figure><p>São os mesmos traits, mas com as cores invertidas. Essa é a única diferença entre os traits “light” e “dark”.</p><p>Se você for reproduzir este artigo para sua própria coleção, sinta-se livre para usar uma estrutura de pastas diferente, mas lembre-se de adaptar o código para essa nova estrutura.</p><p>Ao gerar as imagens, elas devem encaixar uma sob a outra, a funcionalidade de layers do photoshop ajuda nisso. Exporte as imagens com fundo transparente, e com as mesmas dimensões.</p><p>Ex.:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*4o6Fkbs9VeR_6-WfwmgACg.png" /></figure><h3>2. Representando os traits no código</h3><p>Importando pacotes:</p><pre>import random<br>import itertools<br>from PIL import Image<br>import pandas as pd</pre><p>Será criado uma lista de raridade para cada trait da seguinte forma:</p><pre>hair_rarities = create_rarity_list([<br>    3,      # 0  bald<br>    28,     # 1  dots<br>    15,     # 2  ssss<br>    30,     # 3  spikes<br>    10,     # 4  baby<br>    25,     # 5  ronaldo<br>    15,     # 6  classy<br>    28,     # 7  brushed<br>    20      # 8  emo<br>    ])</pre><p>Segue a definição da função create_rarity_dict:</p><pre>def create_rarity_list(pct_list):<br>   rarity_list = []<br>   denominator = sum(pct_list)<br>   pct_aux = 0<br><br>   for pct in pct_list:<br>       pct_aux += pct/denominator<br>       rarity_list.append(pct_aux)<br><br>   rarity_list[-1] = 1<br><br>   return rarity_list</pre><p>Esta função permite a definição relativa das raridades, e retorna uma lista como (exemplo):</p><pre> [<br> 0.017241379310344827,<br> 0.1781609195402299,<br> 0.26436781609195403,<br> 0.4367816091954023,<br> 0.4942528735632184,<br> 0.6379310344827587,<br> 0.7241379310344829,<br> 0.885057471264368,<br> 1<br> ]</pre><p>Dessa forma, é criado um dicionário de raridades para cada categoria de trait (type, bg, hair, eye, item, mouth)</p><p>Ao retirar um número aleatório:</p><pre> rNumber = random.SystemRandom().random()<br> rNumber</pre><p>output: 0.7216065468519807</p><p>É possível escolher o cabelo, com base nos intervalos definidos em hairs_rarity. No caso, o cabelo selecionado teria sido “ronaldo”, com id 5</p><p>As listas de raridade de cada categoria de trait é agregada na lista de raridade de todos os traits:</p><pre> traits_rarity = [<br>     type_rarities,<br>     bg_rarities,<br>     hair_rarities,<br>     eye_rarities,<br>     mouth_rarities,<br>     item_rarities<br>     ]</pre><h3>3. Gerando a planilha da coleção</h3><p>A função create_metadata_rarity recebe três parâmetros:</p><ul><li>name: o nome do arquivo .csv que será salvo</li><li>traits_rarity: a lista de listas definindo a raridade de todos os traits</li><li>n_pieces: o número total de peças na coleção</li><li>cols: o nome das colunas da planilha</li></ul><p>Ela processa os valores recebidos e salva uma planilha .csv com a metadata de todas as peças:</p><ul><li>Cada linha é uma peça</li><li>Cada coluna é uma categoria de trait</li><li>Os valores determinam qual trait da coluna X (por ex, hair) a peça da linha Y possui (no caso, um valor de 0 a 8)</li><li>Cada sorteio feito dentro desta função é aleatório e independente. Os valores escolhidos são definidos pelo intervalo selecionado no sorteio (como exemplificado anteriormente). Por isso, mesmo utilizando os mesmos parâmetros, a coleção resultante tende a ser sempre diferente. Pode-se usar uma seed para os sorteios aleatórios, gerando reprodutbilidade. No caso, a função random.SystemRandom().random() procura ser aleatória e não reproduzível. Qualquer função que selecione um ponto aleatório entre 0 e 1 (float) pode ser usada aqui.</li><li>O loop while da função continua rodando e removendo qualquer linha duplicada (pode acontecer por acaso) até que o total de peças atingido seja igual a n_pieces</li></ul><p>Definição da função:</p><pre>def create_metadata_rarity(name, traits_rarity, n_pieces, cols):<br>  metadata = []<br>  <br>  while len(metadata) &lt; n_pieces:<br>    row = []<br>    <br>    for trait in traits_rarity.keys():<br>      # sorteia um valor entre 0 e 1<br>      row_trait = random.SystemRandom().random()<br>      <br>      # checa o intervalo selecionado e adiciona à linha &quot;row&quot;<br>      for key in range(len(traits_rarity[trait])):<br>        if key == 0:<br>          if row_trait &lt; traits_rarity[trait][0]:<br>            row.append(key)<br>        else:<br>          if row_trait &gt;= traits_rarity[trait][int(key-1)] and row_trait &lt; traits_rarity[trait][key]:<br>            row.append(key)<br>    <br>    # adiciona a linha completa à lista de linhas<br>    metadata.append(row)<br>    # embaralha a ordem das linhas<br>    metadata.sort()<br>    # remove linhas duplicadas<br>    metadata = list(metadata for metadata,_ in itertools.groupby(metadata))<br>  <br>  <br>  df = pd.DataFrame(metadata,columns=cols[1:], dtype=object)<br>  df = df.sample(frac=1)<br>  df[&quot;ID&quot;] = range(1,df.shape[0]+1)<br>  df[&quot;ID&quot;] = df[&quot;ID&quot;].apply(&#39;{:0&gt;4}&#39;.format)<br>  df = df[cols]<br>  df.to_csv(f&quot;{name}.csv&quot;, index=False)</pre><p>Vamos testar:</p><pre>cols = [&quot;ID&quot;,&quot;type&quot;,&quot;bg&quot;,&quot;hair&quot;,&quot;eye&quot;,&quot;mouth&quot;,&quot;item&quot;]<br>n_pieces = 20<br><br>create_metadata_rarity(&quot;test&quot;, traits_rarity, n_pieces, cols)</pre><pre>ID,type,bg,hair,eye,mouth,item<br>0001,0,0,4,0,9,0<br>0002,0,0,3,14,1,0<br>0003,0,0,4,0,10,0<br>0004,0,0,8,4,6,0<br>0005,0,0,4,14,4,6<br>0006,0,0,8,6,3,0<br>0007,0,0,3,5,13,0<br>0008,0,0,8,5,6,0<br>0009,0,0,1,5,7,0<br>0010,0,0,7,8,7,6<br>0011,0,0,6,9,9,0<br>0012,0,0,4,3,9,11<br>0013,1,0,3,6,12,0<br>0014,0,0,7,1,10,0<br>0015,0,0,5,12,9,0<br>0016,0,0,3,2,4,0<br>0017,0,0,7,13,8,0<br>0018,0,0,5,8,4,0<br>0019,0,0,3,13,1,0<br>0020,0,0,3,6,10,0</pre><p>Ok, parece estar funcionando. Agora vamos para o último passo: utilizar este .csv para gerar as imagens</p><h3>4. Gerando as imagens</h3><p>A função que lê a planilha de metadata da coleção e gera as imagens é:</p><pre>def render_pieces(filename, cols):<br><br>    # lê os dados da coleção. o .csv deve estar na mesma pasta<br>    metadata = pd.read_csv(filename, dtype={&#39;ID&#39;: object})<br><br>    # loop pelas linhas<br>    for i in range(len(metadata)):<br>        piece = metadata.iloc[[i]]<br><br>        # a primeira divisão nas pastas vai de acordo com o &quot;type&quot;<br>        if piece[&quot;type&quot;].values[0] == 0:<br>            folder = &quot;dark\\&quot;<br>        else:<br>            folder = &quot;light\\&quot;<br>        <br>        # as imagens de cada trait são acessadas pela concatenação de strings<br>        # a organização das pastas e o nome das imagens devem ser compatíveis com o código<br>        bg_img = Image.open(f&quot;{folder}bgs\\{str(piece[cols[2]].values[0])}.png&quot;)<br>        hair_img = Image.open(f&quot;{folder}hairs\\{str(piece[cols[3]].values[0])}.png&quot;)<br>        eye_img = Image.open(f&quot;{folder}eyes\\{str(piece[cols[4]].values[0])}.png&quot;)<br>        mouth_img = Image.open(f&quot;{folder}mouths\\{str(piece[cols[5]].values[0])}.png&quot;)<br>        item_img = Image.open(f&quot;{folder}items\\{str(piece[cols[6]].values[0])}.png&quot;)<br><br>        # a ordem na qual as imagens são sobrepostas faz diferença<br>        bg_img.paste(hair_img,(0,0),mask=hair_img)<br>        bg_img.paste(eye_img,(0,0),mask=eye_img)<br>        bg_img.paste(mouth_img,(0,0),mask=mouth_img)<br>        bg_img.paste(item_img,(0,0),mask=item_img)<br><br>        # salva a imagem com nome do ID da peça<br>        ID = str(piece[&quot;ID&quot;].values[0])<br>        bg_img.save(f&quot;output\\KBCA#{ID}.png&quot;, &quot;PNG&quot;)</pre><p>Este é um código simples e sem muitos mistérios. Agora vamos gerar uma coleção maior e finalizar o projeto.</p><pre><br>n_pieces = 2500<br><br>create_metadata_rarity(&quot;metadata&quot;, traits_rarity, n_pieces, cols)<br>render_pieces(&quot;metadata.csv&quot;,cols)<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*93L-SHwGobZB-fOW6pIqiA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*vrz8CWvn1ayIcKXByowrgg.gif" /></figure><p>Tudo parece ter funcionado bem.</p><p>Este é um projeto divertido, eu gostaria muito de ver a coleção de quem reproduzir este artigo! Seja criativo.</p><p>Uma coisa que ainda caberia ser feita, é a análise da metadata. Por exemplo, através da análise da planilha de traits, é possível traçar correlações entre as características, determinar clusters, enfim, aplicar técnicas análise de dados aos dados da coleção.</p><p>Dessa forma, seria possível selecionar uma planilha específica que seja mais interessante, contenha alguma característica desejada, etc.</p><p>Indo mais além, porque não aprimorar a forma como essa metadata é gerada? Não existem muitos limites quando se trata de dados.</p><p>Mas, por hoje é isso. Se você leu até aqui, deixe um comentário</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=33ebaef52775" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>