<?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 Addisualemuj on Medium]]></title>
        <description><![CDATA[Stories by Addisualemuj on Medium]]></description>
        <link>https://medium.com/@addisualemuj?source=rss-f8c60c8a305a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*CigzTiclLiCezIypoAKYYg.jpeg</url>
            <title>Stories by Addisualemuj on Medium</title>
            <link>https://medium.com/@addisualemuj?source=rss-f8c60c8a305a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 11:25:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@addisualemuj/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[Crypto Trading Engineering: Scalable Backtesting Infrastructure]]></title>
            <link>https://medium.com/@addisualemuj/crypto-trading-engineering-scalable-backtesting-infrastructure-f53a6f2fd4ce?source=rss-f8c60c8a305a------2</link>
            <guid isPermaLink="false">https://medium.com/p/f53a6f2fd4ce</guid>
            <dc:creator><![CDATA[Addisualemuj]]></dc:creator>
            <pubDate>Mon, 29 Jul 2024 07:30:47 GMT</pubDate>
            <atom:updated>2024-07-29T07:30:47.068Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m8U2brNqKn3wHazAnQjDSg.jpeg" /></figure><p><strong>Introduction</strong></p><p><strong>Backtesting</strong> is the process of evaluating the performance of a trading strategy or an investment model by applying it to historical market data. It involves simulating the application of a trading strategy or an investment approach using past data to see how it would have performed during that time period. The goal of backtesting is to simulate how a particular trading strategy or investment approach would have performed in the past, without actually investing real money.</p><p>The process of backtesting involves:</p><ul><li>Defining the trading strategy or investment model: This includes specifying the rules, indicators, and algorithms that will be used to make trading decisions.</li><li>Gathering historical market data: This data can include historical prices, trading volumes, economic indicators, and other relevant information.</li><li>Applying the trading strategy or investment model to the historical data: The strategy is “applied” to the historical data, simulating the trades that would have been executed based on the strategy’s rules.</li><li>Analyzing the results: The backtesting process generates a simulated performance history, which can be analyzed to assess the strategy’s profitability, risk, and other key metrics, such as:</li><li>Total returns</li><li>Drawdowns</li><li>Win/loss ratio</li><li>Sharpe ratio</li></ul><p><strong>Business Need</strong></p><p>A startup called Mela wants to make it simple for everyone to enter the world of cryptocurrencies. It also wants to give investors a reliable source of investment while lowering the risk associated with trading cryptocurrencies. This project is designing and building a reliable, large-scale trading data pipeline.</p><p><strong>Data exploratory analysis (EDA)</strong></p><p>Data Exploratory Analysis was conducted on Apple Inc. (AAPL) stock data, starting from January 1, 2020. The historical price data was obtained and saved to a CSV file for further analysis. To gain initial insights into the stock’s performance and price movements, two visualization methods were employed:</p><ul><li>A line diagram was created to display the overall trend of the stock price over time, providing a clear view of the stock’s general direction and major fluctuations.</li><li>A candlestick chart was generated to offer a more detailed representation of price action. This visualization allows for the observation of daily opening, closing, high, and low prices, revealing patterns and potential trading signals.</li></ul><p>These visualizations serve as a foundation for understanding AAPL’s price behavior and will inform further analytical steps in the trading strategy development process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/0*X2bol8oGc9UaEsZm" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/865/0*ubLg4xh0e7XncugR" /></figure><p>The above result is saying</p><ul><li>Broker (None): This indicates that no specific broker model was set, so Backtrader is using its default broker.</li><li>Cash (9862.6): This is the remaining cash in your account after the backtest.</li><li>Value (10071.67): This is the total value of your portfolio (cash + stock value) at the end of the backtest.</li><li>Data Trades (True): This indicates that trades were allowed on this data feed.</li><li>(1 day) c:209.07: This shows the closing price of the last day in your backtest period.</li><li>Volume BuySell (True, 0.015): This suggests that volume was considered for buy/sell decisions, and 0.015 might be a commission rate or a volume-related parameter.</li><li>SMA(50) 188.12: This is the 50-day Simple Moving Average value at the end of the backtest period.</li><li>SMA(100) 182.60: This is the 100-day Simple Moving Average value at the end of the backtest period.</li></ul><p><strong>Techstack used</strong></p><ul><li><strong>Backtrader: </strong>is a Python framework for backtesting, trading, and analyzing financial strategies.</li><li><strong>React: </strong>JavaScript library for building user interfaces.</li><li><strong>Fastapi:</strong> FastAPI is a modern, fast (high-performance), web framework for building APIs with Python.</li><li><strong>Kafka:</strong> Kafka is an open-source, distributed, and fault-tolerant streaming platform. It is designed to handle large-scale data processing and real-time data streaming applications.</li><li><strong>Mlflow: </strong>MLflow is an open-source platform for managing the end-to-end machine learning lifecycle, including experimentation, reproducibility, deployment, and a central model registry.</li></ul><p><strong>Methodology</strong></p><p><strong>Frontend</strong></p><p>A web-based interface has been developed using Vite and React to facilitate the backtesting of trading strategies. The application consists of three main components:</p><p><strong>Login Page:</strong></p><p>A secure authentication system has been implemented, allowing users to access the backtesting functionality. This ensures that only authorized individuals can utilize the trading strategy evaluation tools.</p><p><strong>Backtesting Page:</strong></p><p>Upon successful login, users are directed to the backtesting page. This interface provides</p><ul><li>Input fields for strategy parameters and data selection</li><li>Display of backtesting results</li></ul><p>The backtesting page is designed to output key performance metrics and visualizations derived from the backtesting process. This allows users to quickly assess the efficacy of their trading strategies.</p><p><strong>Signup Page: </strong>A new user registration system has been implemented, allowing new users to create accounts.</p><p>By leveraging Vite for fast build times and React for a responsive user interface, the application offers a smooth and efficient user experience. This frontend development complements the backend backtesting engine, creating a comprehensive tool for strategy evaluation and refinement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/0*tHEPC_maq1ar4god" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/473/0*RJTuNYNMchg6eA_o" /></figure><p><strong>Backtest: </strong>For the backend I used backtrader. Backtrader is a Python library for backtesting trading strategies. It provides a framework to: Define trading strategies, Load historical, market data, Simulate trades based on your strategy. Analyze and visualize results</p><ul><li>Set up the environment (Python, Backtrader, data sources)</li><li>Define the strategy class</li><li>Implement entry and exit rules</li><li>Create data feeds</li><li>Instantiate the cerebro engine</li><li>Add data feeds to cerebro</li><li>Add the strategy to cerebro</li><li>Set starting cash and commission</li><li>Add analyzers and observers</li><li>Run the backtest</li><li>Print and visualize results</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/0*OtDSJi5s1Va-o098" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/0*wlIS6QCNBl82begA" /></figure><p><strong>Backend:</strong> I used fastapi for backend</p><ul><li>Set up the environment (Python,FastAPI, Uvicorn)</li><li>Create the main application file</li><li>Define API endpoints using decorators</li><li>Implement request/response models with Pydantic</li><li>Add error handling and custom responses</li><li>Implement query parameters and request body parsing</li><li>Use dependency injection for shared logic</li><li>Add authentication and authorization</li><li>Organize code into modules (models)</li><li>Implement middleware (CORS)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FPM-5uEif39vVF9h" /></figure><p><strong>Mlflow: I</strong>ntegrates MLflow into a stock prediction and backtesting pipeline</p><ul><li>Experiment Setup: Sets up an MLflow experiment named “LSTM_Stock_Prediction” using mlflow.set_experiment().</li><li>Run Creation: Starts a new MLflow run using mlflow.start_run().</li><li>Metric Logging: During LSTM model training, logs the training loss for each epoch using mlflow.log_metric(“train_loss”, loss.item(), step=epoch). After training, logs the test Mean Squared Error (MSE) using mlflow.log_metric(“test_mse”, mse).</li><li>Model Saving: Saves the trained PyTorch LSTM model using mlflow.pytorch.log_model().</li><li>Backtest Results Logging: Logs the final portfolio value and portfolio return percentage after running the backtest.</li><li>Artifact Logging: Saves the backtest plot as a PNG file and logs it as an artifact using mlflow.log_artifact(“backtest_plot.png”).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*O9aGw7txWb1ppbcY" /></figure><p><strong>Lesson Learned and Conclusion</strong></p><p>The deep dive into backtesting different trading strategies has reinforced the importance of thorough evaluation and analysis before deploying any real-world trading system. Generating the key performance metrics like returns, number of trades, win/loss ratios, max drawdown, and Sharpe ratio has provided me with a comprehensive understanding of each strategy’s strengths and weaknesses. The experience of connecting my FastAPI backend to a Vite-powered React frontend has been a testament to the power of full-stack development. Building this integrated application has shown me the significance of seamless data exchange and a cohesive user experience. My exploration of LSTM models for financial prediction has deepened my appreciation for the capabilities of advanced machine learning techniques. Applying LSTM to forecast financial metrics has not only challenged me to grasp the complexities of time series data analysis but has also underscored the importance of selecting the right tools and algorithms for the task at hand.</p><p><strong>Future plans</strong></p><ul><li>Authentication for the frontend sign in page.</li><li>Create authentication handling backend for users to login using your frontend.</li><li>Airflow implementation</li><li>Create an algo which selects the best backtested strategy and implements a recommendation based on a combination of best returns, highest sharpe ratio and lowest drawdown</li></ul><p>References</p><ul><li><a href="https://fastapi.tiangolo.com/">https://fastapi.tiangolo.com/</a></li><li><a href="https://vitejs.dev/guide/">https://vitejs.dev/guide/</a></li><li><a href="https://kafka.apache.org/quickstart">https://kafka.apache.org/quickstart</a></li><li><a href="https://www.backtrader.com/docu/">https://www.backtrader.com/docu/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f53a6f2fd4ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>