<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.10.0">Jekyll</generator><link href="https://www.haksoat.com/feed.xml" rel="self" type="application/atom+xml" /><link href="https://www.haksoat.com/" rel="alternate" type="text/html" /><updated>2026-04-11T23:28:51+01:00</updated><id>https://www.haksoat.com/feed.xml</id><title type="html">HAKSOAT</title><subtitle>The personal site of Habeeb Kehinde Shopeju</subtitle><author><name>Habeeb Shopeju</name><email>shopejuh@gmail.com</email></author><entry><title type="html">Lessons from My Father</title><link href="https://www.haksoat.com/lessons-from-my-father/" rel="alternate" type="text/html" title="Lessons from My Father" /><published>2026-02-11T00:00:00+01:00</published><updated>2026-02-11T00:00:00+01:00</updated><id>https://www.haksoat.com/lessons-from-my-father</id><content type="html" xml:base="https://www.haksoat.com/lessons-from-my-father/"><![CDATA[<p>On December 8, 2025, I was in Lagos to see my father. He had been ill for a couple of weeks and I needed to visit him. I planned to see him again in January 2026. So when leaving, I told him to stay strong as I would see him again soon. I told him I still had a lot of advice to seek and knowledge to learn from him.</p>

<p>One week later, I went for an appointment. While awaiting my turn, I was reading James Dyson’s “Against the Odds”, a passage that said:</p>

<blockquote>
  <p>“My father was dead, and his achievement, anyway, was as a classicist. External figures had to count for a father. It is why a man called Jeremy Fry became so important to me, and Sir Hugh Casson, and Anthony Hunt. But they had to be overcome before I could move forward. If I was to push further there had to be new fathers. There had to be Buckminster Fuller, and Brunel.”</p>
</blockquote>

<p>I remember feeling sad reading those words but little did I know that I was losing my father in those moments. When I finished that appointment, I got a call from my brother that our dad had passed on. <em>Inna lillahi wa inna ilayhi raji’un</em>. Amidst the sadness that I felt, I was grateful for actively having him in my life. Unlike the author of the book I was reading earlier, I did have my father for 25+ years of my life, an experience I can’t put a price on.</p>

<p class="text-center"><img src="https://res.cloudinary.com/haks/image/upload/v1770833558/HAKSOAT_Blog/lessons-from-my-father/me_father_brother.jpg" alt="Left to Right: Myself, my father, my brother." class="align-center" />
Left to Right: Myself, my father, my brother.</p>

<p>I have two Notion pages where I note the lessons from my dad and mum. After losing my dad, I opened the page and I had a sad realisation that I won’t be actively adding to the document anymore. Well, except retrospectively as I remember more precious teachable moments.</p>

<p>Some years ago, my father told me that very soon, I would remember his words and say <code class="language-plaintext highlighter-rouge">"this man told me these things; he was right."</code> Here I am, doing more than just saying he told me these things; I am putting them into writing.</p>

<p>In this piece, I want to share some advice from my father with the intention that it benefits you, the reader, and it serves as <em>sadaqah jariyah (ongoing charity)</em> for my father.</p>

<p>Before I proceed, here’s something to note:</p>

<p>Each piece of advice is a lived experience for me. I have poorly applied, forgotten and been negligent about each one at various points in my life and faced the music. They are now more than just advice and have become lessons.</p>

<p>For you the reader, it may be different if this is your first encounter with these ideas. I also recognise that not everyone has had the opportunity to have this kind of relationship with their father. That said, I hope you find the lessons useful; perhaps you’ll remember after failing to follow them and facing your own consequences :-)</p>

<p>I classify the lessons into these categories:</p>

<ul>
  <li>Life’s Challenges</li>
  <li>Record Keeping</li>
  <li>Procrastination and Prioritisation</li>
  <li>Agency</li>
</ul>

<h2 id="on-lifes-challenges">On Life’s Challenges</h2>

<p>In the year 2014, I wrote the Joint Admission Matriculation Board examination. I scored just below 200 which was not enough to study what I wanted; I failed. The implication was that I had to wait one year before getting another shot at a university admission. I remember crying for days as I was utterly disappointed with myself. The fact that I was considered an exceptional student at secondary school made it worse.</p>

<p>In those moments, I expected my dad to be furious and show it. To my surprise, he acted as though nothing life-changing happened. He brushed it off as failure being part of life, regularly counselling me that life is not a bed of roses. I remember him saying that I had to pick myself up, find something else to do for the year, and prepare harder for the next examination.</p>

<p>I would experience more challenges in the following years and my father did not shy away from encouraging me to stay strong in the face of adversity. He would remind me that facing challenges is an expected part of being alive, so they should neither cause me to give up nor stay moody. Instead, I should accept them for what they are. He would then tell stories of various challenges he himself had faced from various perspectives: business, career, people, and community. <code class="language-plaintext highlighter-rouge">"Life is not a bed of roses,"</code> he would say, <code class="language-plaintext highlighter-rouge">"it won't always be smooth."</code></p>

<p>One conversation that is etched in my mind forever is one I had with him when an acquaintance died. He told me that to live is to feel the pain of losing one’s loved ones. The only way to avoid that is to not live, in which case, others will feel that pain. To hear that from someone who lived for 82 years is to hear the absolute truth.</p>

<p>In teaching me to expect trials, my father would also teach me to always have a contingency plan. This lesson he would pass across both by words and deeds. He really liked to teach by example. Many times if he wanted me to do something for him, he would mention it, then follow up with <code class="language-plaintext highlighter-rouge">"but this may not work; if it doesn't work, you should do this instead."</code></p>

<p>One of his favourite examples was when we purchased items for the home. For some items, he would buy more than the required quantity and mention that they would likely be out of stock in a couple of months. Sure enough, when they were actually out of stock, he would give a lecture.</p>

<h2 id="on-record-keeping">On Record Keeping</h2>

<p>If you knew and worked with my father, it wouldn’t take long before you got a glimpse of how much of a documenting geek he was. While he had a good memory, he knew that relying on memory alone was a disaster waiting to happen, so he made sure everybody knew this. My father would document nearly everything. During conversations, if an event was referenced, he could stand up, go into his room and in a couple of minutes, produce a document with information about that event with its dates.</p>

<p>When I was much younger, in a bid to cultivate a culture of documenting in me, my father would get me a folder. He would encourage me to do my record-keeping in it. For certain documents, he made photocopies, giving me some and keeping some himself.</p>

<p>After his passing, when helping to clear his room, I had a lot of “oh”s and “ah”s at the amount of documenting he did. Record-keeping is a habit I still need to improve on, as it does not come naturally to me yet. I have enjoyed its dividends. It always feels good when I try to remember something that happened a while ago and I am able to reference some document and keep things moving.</p>

<p class="text-center"><img src="https://res.cloudinary.com/haks/image/upload/v1770833551/HAKSOAT_Blog/lessons-from-my-father/colleague_documentation.png" alt="A work colleague was surprised that I could still find throwaway code a long time after." class="align-center" />
A work colleague was surprised that I could still find throwaway code a long time after.</p>

<p>In my lazy moments I feel like it is unnecessary work and engage in self-deceit by relying on memory, telling myself that I would not forget. You do not need to be a seer to know that I almost always end up forgetting. In those cases, the feelings of self-let-down are often worse because I expect that I would have had some documentation in place only to find out that I did not.</p>

<h2 id="on-procrastination-and-prioritisation">On Procrastination and Prioritisation</h2>

<p>By far, the most frequent advice I got from my father was <code class="language-plaintext highlighter-rouge">"do not leave till tomorrow what you can do today."</code> It almost became his motto in my eyes. As I grow older, I realise that my dad was well aware that procrastination is the thief of time and assassination of all destinations.</p>

<p>Anyone who worked with my dad would probably experience his tendency to just do things himself if someone else was taking too long to do it. He was aware that everything cannot be done immediately, but he was also big on possessing a sense of urgency. So if he noticed me procrastinating and could sense the BS in my excuses, he would hit me with a <code class="language-plaintext highlighter-rouge">"do not leave till tomorrow what you can do today."</code></p>

<p>Those words have been so ingrained in me that I can hear his voice as I write this, and my wife has heard me say those words countless times. That said, if you then think that I do not procrastinate anymore, you would be completely wrong. I still tend to put things off and I feel like I disappoint my father when that happens. I honestly do not think I can eliminate it, but I am more aware when it is happening, giving me a chance to course-correct if it is vital and urgent.</p>

<p>Procrastination is the enemy of prioritisation. When people talk about procrastination, it is often about it being a means to avoid doing anything. But there is one step after that: procrastination as a means to do everything but the hard, important things.</p>

<p>My father was very much aware of this second step. So while I could be working on something valuable, he would acknowledge that and then give me a lecture on prioritising properly. His advice would be something like, <code class="language-plaintext highlighter-rouge">"Habeeb, you are doing B but A is undone. There is a limited time to do A; if the opportunity to do A goes, can you still do it? No. But if you do A, you can always then come back to do B."</code></p>

<p>As I grew older, when I made poor prioritisation choices, I would remember my dad. When I made good prioritisation choices, I would even call him to tell him how his advice helped. I can’t tell him anymore, but I am grateful.</p>

<h2 id="on-agency">On Agency</h2>

<p>When my father asked me to do something, my much younger self would try to bail by simply telling him it couldn’t be done. Then he would ask <code class="language-plaintext highlighter-rouge">"have you tried?"</code> Well, the answer was usually no. Like clockwork, I would then go and try, with probably the most lacklustre attempt he has ever witnessed. He would then come and do it himself, showing me that:</p>

<ol>
  <li>It could be done; I just did not try.</li>
  <li>I tried, but I just did not try properly.</li>
</ol>

<p>Those teachings have stayed with me till today. Such that when working on a task, perhaps feeling tired and tending to do a poor job, I would remember his disapproval. This has also caused me to think twice before I blurt out “it cannot be done” just because I currently do not know how to do something.</p>

<p>I may not have realised then, but he was instilling the belief that I could take control of things and largely influence the outcome. This is a trait I can see in all my siblings. I cannot count the number of times I have seen them go the extra mile to succeed, stand out and shine. These outcomes are usually attributed to the grace of God, but one can also see the effort involved.</p>

<p>As I come to the end of this article, I realise that I learnt a lot of these lessons when I was a teenager. A point in my life where I had the teenage tendency to hold everything else accountable but myself. When my father would ask me to do something and I did not do it properly, I would easily say it was not my fault. Dad would tell me, and I quote, <code class="language-plaintext highlighter-rouge">"a bad workman always blames his tools,"</code> then proceed with a lecture on how this was a skill issue and I should look inward.</p>

<p>Now that the years have rolled by, I have come to my own conclusion that there really are bad tools for a job. But I also acknowledge that one requires knowledge to be able to tell that. If I do not have the expertise to judge if a tool is bad or use it properly, I do not go around blaming my tools. When I do, I hear his voice in my head, catch myself, and go through a moment of introspection.</p>

<h2 id="final-words">Final Words</h2>

<p>After days of contemplating if I should write this piece or not, I am glad I did it. Indeed, I felt a flush of emotions in the process. At the start of the article, I said I was hoping you find it useful. Ironically, I think I would be the one returning to it in the future.</p>

<p>As a parting shot, I would narrate a time in my life when he would teach me something beneficial—it was valuable then, remains so now, and will be in the future.</p>

<p>My handwriting was poor; it still is. So some years ago, my father paid extra attention to my writing and would scold me a lot because of it. He would then enrol me in handwriting classes every Saturday, probably for one year until those classes stopped running. He would say to me: <code class="language-plaintext highlighter-rouge">"it does not matter how intelligent or knowledgeable you are; nobody would read what you are writing if it is illegible."</code> In essence, it does not matter how good my work is; it would be dead in the water if I am unable to communicate what was done to someone else.</p>]]></content><author><name>Habeeb Shopeju</name><email>shopejuh@gmail.com</email></author><category term="experience" /><summary type="html"><![CDATA[I lost my father in December 2025, I am sharing some lessons I learnt from him.]]></summary></entry><entry><title type="html">Deep Learning Indaba 2025: Top Moments + a Poster Presentation</title><link href="https://www.haksoat.com/indaba-25-poster/" rel="alternate" type="text/html" title="Deep Learning Indaba 2025: Top Moments + a Poster Presentation" /><published>2025-08-27T00:00:00+01:00</published><updated>2025-08-27T00:00:00+01:00</updated><id>https://www.haksoat.com/indaba-25-poster</id><content type="html" xml:base="https://www.haksoat.com/indaba-25-poster/"><![CDATA[<p>“Discussion and exchange of views is usually refreshing, stimulating and encouraging, especially when one is in difficulties and worried.”</p>

<p>This quote from the book “The Art of Scientific Investigation” explains one of my motivations for wanting to attend the Deep Learning Indaba in Rwanda.</p>

<p>So if you ask, “did the conference help?”, my answer to that will be an emphatic “yes!”.</p>

<p>I had a range of conversations; some enlightening and interesting, and others I would never have thought of having at an event like the Deep Learning Indaba. Some of these interactions include:</p>

<ul>
  <li>Getting a 1-1 lecture on generative ai modelling approaches from a fellow attendee</li>
  <li>Having a conversation about balancing building as an engineer and sharing some of my knowledge</li>
  <li>Getting insights into what it is like to do machine learning research in the Kingdom of Saudi Arabia</li>
</ul>

<p>In the middle of all of this, I also helped give a poster presentation about improving the quality of dense embeddings for Nigerian languages. This is a project I worked on in the first quarter of the year with three amazing people in the Information Retrieval focus group at <a href="https://mlcollective.org/wiki/mlc-nigeria/">ML Collective, Nigeria</a>. The project deserves a separate technical post, and that should come later, God willing. The exciting part is the poster got an award as one of the best General Posters at the conference; that is a welcomed morale booster.</p>

<p><img src="https://res.cloudinary.com/haks/image/upload/v1756494272/HAKSOAT_Blog/indaba-25/haksoat-indaba-banner.jpg" alt="Urunana (hand-in-hand)" /></p>

<p>Deep Learning Indaba 2026 holds in Nigeria. I expect the application forms will be out next year and I encourage you to apply.</p>

<p>Now, let’s proceed to my top moments.</p>

<h3 id="top-five-moments">Top Five Moments</h3>

<ol>
  <li>Learning New Generative Modelling Approaches</li>
  <li>Meeting Luis Serrano</li>
  <li>Realizing Data Access is Harder Than Initially Thought</li>
  <li>Random Learnings</li>
  <li>Getting a Poster Award</li>
</ol>

<h4 id="learning-new-generative-modelling-approaches">Learning New Generative Modelling Approaches</h4>

<p>Prior to the conference, I had some exposure to approaches to generative modelling such as Generative Adversarial Networks (GANS), Variational AutoEncoders (VAE), and Diffusion Models. Some of these approaches I learnt from previous projects, work, and the <a href="https://www.oreilly.com/library/view/hands-on-generative-ai/9781098149239/">Hands-On Generative AI with Transformers and Diffusion Models</a> book. Attending a session on generative modelling techniques, I expected it to be a refresher session, but it was more than that.</p>

<p>I came across two new concepts: “<a href="https://arxiv.org/abs/1908.09257">Normalizing Flows</a>” and “<a href="https://www.youtube.com/playlist?list=PL57nT7tSGAAUDnli1LhTOoCxlEPGS19vH">Flow Matching</a>”. As it turns out, they are actually not new; I was only late to the party. Anyone who attends a session where they are seeing a technical concept for the first time will likely agree that it is a bad place to learn. It is a good place to gain inspiration but you need to do some work after. Thankfully, I met the brilliant <a href="https://www.linkedin.com/in/rodeooswald">Rodeo Oswald</a> at the conference; he provided some context that made the concepts easier to understand.</p>

<p>It is befitting that this moment was on the first day of Indaba; it set the pace for what I was to expect for the rest of the one-week conference.</p>

<h4 id="meeting-luis-serrano">Meeting Luis Serrano</h4>

<p>On the same day, I came across Luis Serrano from <a href="https://www.youtube.com/@SerranoAcademy/featured">Serrano Academy</a>. Some years ago I remember regularly turning to Luis’ YouTube videos to properly understand concepts I was struggling to wrap my head around. For example, in 2020 when I was working on a project that required topic modelling I watched <a href="https://youtu.be/T05t-SqKArY">Latent Dirichlet Allocation</a> and <a href="https://youtu.be/BaM1uiCpj_E">Gibbs Sampling</a>; the videos were helpful. Hopefully, you can imagine how excited I was to see the man just two seats away from me. I reached out to him and we had quite a chat, talking on topics from the weather in Kigali to what sharing knowledge could mean for someone looking to focus on engineering and research.</p>

<p>The next day, Luis gave a class on Large Language Models. It was a masterclass; his slides, metaphors, and how kept his audience engaged. I am usually inspired when I see someone do what they know how to do well, it shows that they put in great effort over a long time. As I write this, I wonder if I should try re-explaining the concepts with the metaphors he used, but it’s just sunrise and I don’t need a rabbit hole today.</p>

<p>I will mention two metaphors that I liked from his class:</p>

<ul>
  <li>Explaining the concepts of Keys and Queries in the attention mechanism via the relationship between himself (less popular) and Taylor Swift (extremely popular).</li>
  <li>Explaining why angular distance is more favourable for measuring vector similarity (compared to Euclidean distance), via how Google Maps measures distance between places.</li>
</ul>

<p>On the third day, Luis gave a mentorship session. In this class, he gave direct answers to questions, acknowledging when he really didn’t have an answer and using metaphors that did a good job of passing his message across. I will leave you with a gem he shared during the session in relation to the constant uncertainty about doing work in the Artificial Intelligence space.</p>

<p>It goes thus:</p>

<blockquote>
  <p>“Imagine a sport will be invented in 10 years’ time and you have no idea what that sport will be. How will you prepare?”</p>
</blockquote>

<p>The answer from the audience and himself went something like:</p>

<blockquote>
  <p>“You will probably do a lot of running, swimming, throwing, skipping, jumping, eating healthy. When the sport is finally invented, it will most likely involve some of these things and you will only need a couple of weeks or months of very specific practice.”</p>
</blockquote>

<p>In the field of Artificial Intelligence, things are constantly being invented. So it is essential to understand the fundamentals, in preparation for the future and to build the capacity for making contributions. For someone involved in engineering and research, the fundamentals here may include things like: learning to code, knowing linear algebra, knowing how backpropagation works, learning to train a neural network, etc.</p>

<h4 id="realizing-data-access-is-harder-than-initially-thought">Realizing Data Access is Harder Than Initially Thought</h4>

<p>I understand that working on data solutions for African problems is hard, but conversations with other attendees helped me see that:</p>

<ol>
  <li>I was not alone in feeling that way.</li>
  <li>It is much harder than I thought.</li>
</ol>

<p>In the last couple of years, my interests have been in the areas of information retrieval and natural language processing. So most of the challenges I face are due to the lack of access to documents in Africa’s native languages. There are a dizzying number of languages spoken across the continent; <a href="https://en.wikipedia.org/wiki/Languages_of_Africa">Wikipedia says it is about 2000 to 3000 languages</a>. A lot of those languages do not have a significant digital footprint, so it is hard to build for those languages. These challenges make you question if it is even a worthwhile commitment to try at all.</p>

<p>Outside the language field, others shared frustrations getting access to data in the healthcare, legal, real estate, climate, media spaces. Some of the challenges include:</p>

<ul>
  <li>The absence of an aggregated, quality data source for the African context. Perhaps seeking one data source is an overkill, but having a couple where the data is of enough quality and quantity to do downstream work such as building products, will go a long way.</li>
  <li>The shortage of funding for data collection. As a result, seeking funding from organizations outside the continent becomes an appealing option, despite the onerous clauses that might be involved.</li>
</ul>

<p>Africa has a long way to go and the development of infrastructure—whatever that may mean—is a prerequisite to building data solutions. The problems stated above occur even within individual countries, so it will be much harder to get solutions that work across the continent for the ideal Pan-African dream. It was also discussed how the challenge in cross-collaboration further extends even to travel, where you often have to take flights to Europe and then back into Africa to go from one African country to another.</p>

<p>I consider the conversations on this topic to be a top five moment because I rate awareness highly. As more people become aware of the situation, perhaps more efforts can come together that can move the needle. A different article will be needed to talk about what such efforts might be.</p>

<h4 id="random-learnings">Random Learnings</h4>

<h5 id="african-institute-for-mathematical-sciences-aims">African Institute for Mathematical Sciences (AIMS)</h5>

<p><a href="https://nexteinstein.org/">AIMS</a> is a postgraduate school for mathematical sciences. This year’s Indaba is not my first time hearing about the organization, but it is only now that I realize how much impact it is having on the African Artificial Intelligence ecosystem. If it is properly run and gets adequate funding, it can only get better from here. I met a number of students from the institution, likely because there’s a centre in the country: <a href="https://aims.ac.rw/">AIMS Rwanda</a>. Most of these students recently finished their Master’s programme there and I met one who is currently doing a PhD. While I do not know enough about the organization to confidently recommend them, I saw enough to say “check them out.”</p>

<h5 id="the-africa-technology-policy-tracker">The Africa Technology Policy Tracker</h5>

<p>The <a href="https://carnegieendowment.org/features/africa-digital-regulations?lang=en">Africa Technology Policy Tracker</a> is a platform that keeps track of the various laws, policies and regulations in relation to information technology in Africa, going back to the early 2000s. It seems to contain links to each document and can be useful for individuals looking to do policy research across various African countries. A few links do not work or point to the wrong thing, but most of them work and it is a valuable resource.</p>

<h5 id="middle-east-and-north-africa-machine-learning-mena-ml">Middle East and North Africa Machine Learning (MENA ML)</h5>

<p><a href="https://www.mena.ml/">MENA ML</a> is a Machine Learning Winter School program that appears to hold in January each year. I met someone who attended this year’s edition in Qatar and absolutely loved it. The 2026 edition will be at the King Abdullah University of Science and Technology (KAUST) in the Kingdom of Saudi Arabia. Applications are now open and close on the 18th of September 2025, so hurry and <a href="https://www.mena.ml/applications">put in your application</a> if interested.</p>

<h5 id="the-10-oclock-problem">The 10 o’Clock Problem</h5>

<p>Open your favourite “chat app” or visual language model, ask it to generate a clock at some time, see what happens. In my case, all images I got had one hand pointing to 10 despite using different prompts. The following grid contains images from: <a href="https://manus.ai/">Manus.ai</a>, <a href="https://chatgpt.com/">ChatGPT</a>, <a href="https://claude.ai/">Claude</a>, <a href="https://gemini.google.com/">Gemini</a>, <a href="https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5">stable-diffusion-v1-5</a>, using the following prompt: “Generate an image of a clock at 9pm.”</p>

<p><img src="https://res.cloudinary.com/haks/image/upload/v1756481412/HAKSOAT_Blog/indaba-25/beautiful_unique_clock_grid.jpg" alt="Always 10 o'Clock" /></p>

<p>The only different result is from Claude and it is not because Claude is better. It did not generate an image directly. Instead, it generated an SVG file and rendered it.</p>

<p>Why are the results like this? I don’t know. But my suspicions align with those from the organizers of the GenAI practical sessions at the Indaba: Somewhere in the training process, a lot of clocks with the short hand at 10 and the long hand at 2 were used in the training data.</p>

<p>I find it interesting, and think this is a good example that shows that these models can only pull from their distribution. If the distribution does not “support” your prompt, it does not matter how good your prompt is.</p>

<h5 id="google-deepminds-habermas-machine">Google DeepMind’s Habermas Machine</h5>

<p>On attending <a href="https://scholar.google.co.uk/citations?user=4c2k2LEAAAAJ&amp;hl=en">Verena Rieser’s</a> keynote speech, <code class="language-plaintext highlighter-rouge">"Whose Gold? Aligning AI with Diverse Views on What's Safe, Aligned, and Beneficial"</code>, I got to learn about the <a href="https://github.com/google-deepmind/habermas_machine">Habermas Machine</a>. It is system for automated mediation, named after German social theorist <a href="https://en.wikipedia.org/wiki/J%C3%BCrgen_Habermas">Jurgen Habermas</a>. From my understanding, the system tries to answer the question: “Given a group of differing opinions about a matter from various parties, how can you automatically mediate and produce a single useful statement that satisfies the various parties?” I will not be writing about this system in this article, but I recommend <a href="https://www.lesswrong.com/posts/j9K4Wu9XgmYAY3ztL/habermas-machine">Nicholas Kees’ article on the work</a>, it is a lovely overview of the work.</p>

<h5 id="googles-healthcare-models">Google’s Healthcare Models</h5>

<p>I attended the <a href="https://ds4healthafrica.github.io/">Data Science for Health Workshop</a> and it included a hands-on tutorial using a couple of Google’s models for Health use cases. These include the <a href="https://huggingface.co/google/medgemma-4b-it">MedGemma</a>, <a href="https://huggingface.co/google/medsiglip-448">MedSigLIP</a> and <a href="https://huggingface.co/google/txgemma-9b-chat">TxGemma Chat</a> models. These models are quite useful and have a wide range of applications. For example, MedGemma can be used for things like describing an X-ray, MedSigLIP for creating dense embeddings from medical images to be <a href="https://www.haksoat.com/working-on-ahnlich/">stored in a database like Ahnlich</a> and TxGemma Chat for predicting properties of therapeutics.</p>

<h5 id="continual-learning">Continual Learning</h5>

<p>Prior to the Indaba, I did not know “continual learning” was a thing, so the first time I heard it, I actually thought it was “online learning”. As it turns out, they are completely different things. Online learning involves continuously improving a model as new data streams in, rather than storing the data to set up a full retraining process on the entire batch. Continual learning on the other hand, involves training a model such that it retains historical information, essentially tackling the problem of catastrophic forgetting.</p>

<p>A couple of poster presentations at the Indaba were related to continual learning. I remember one talking about latent replay buffers; sadly, I can’t find links to the poster. I also saw one with the title “Ask and Remember: A Questions-Only Replay Strategy for Continual Visual Question Answering” from <a href="https://iemprog.github.io/">Imad Eddine Marouf</a>. You can <a href="https://arxiv.org/pdf/2502.04469">checkout the paper from Imad’s work</a>, and <a href="https://drive.google.com/file/d/13BUw4fsjeevj6fRmiVnShzRBygt0Yb3y/view">the poster</a> too. Heads-up that there’s a chance the poster link will be broken in the future.</p>

<p>Interestingly, I experienced the case of catastrophic forgetting while working on the project I presented at the Indaba, so I’m curious to try out continual learning techniques:</p>

<ol>
  <li>To get better context and learn something.</li>
  <li>To see if it works.</li>
</ol>

<p>Take a look at the following image:</p>

<p><img src="https://res.cloudinary.com/haks/image/upload/v1756483955/HAKSOAT_Blog/indaba-25/catastrophic-forgetting-bge-evals.png" alt="Catastrophic Forgetting Example" /></p>

<p>The <code class="language-plaintext highlighter-rouge">BGE-M3-yoruba-alldata-Epochs-3</code> row was the first model training phase, where it was trained on Yoruba only. Next it was trained on Igbo to yield <code class="language-plaintext highlighter-rouge">BGE-M3-yoruba-igbo-alldata-Epochs-3</code>. Finally, it was trained on Hausa to yield <code class="language-plaintext highlighter-rouge">BGE-M3-yoruba-igbo-hausa-alldata-Epochs-3</code>.</p>

<p>As the model trains on more languages, the quality of the results on Yoruba tasks drops. The Igbo dataset here was probably about 20k rows and the Hausa one about 85k rows. You will notice that the model performs worse after training on Igbo, then takes a huge dip after training on Hausa (4 times the size of the Igbo dataset). Perhaps I’ll write a piece if I ever get around trying different continual learning techniques on this task.</p>

<h4 id="getting-a-poster-award">Getting a Poster Award</h4>

<p>At <a href="https://mlcollective.org/wiki/mlc-nigeria/">ML Collective Nigeria</a>, I suggested setting up an Information Retrieval focus group for members interested in working on projects at the intersection of Information Retrieval and Machine Learning. Interestingly, a couple of incredible people showed interest. The project <code class="language-plaintext highlighter-rouge">"Improving BGE-M3 Multilingual Dense Embeddings for Nigerian Low-Resource Languages"</code> was the first project we worked on, and interestingly, the work got a poster award.</p>

<p>You can <a href="https://drive.google.com/file/d/15-9xt7X2UMsY6mkn8w3zwhyfn_v72Ae2/view?usp=sharing">view the poster presentation on Google Drive</a>, also I will give a brief explanation of the work.</p>

<p>To start with, here’s some context about the base model:</p>

<p>The project builds on <a href="https://huggingface.co/BAAI/bge-m3">the BGE-M3 model</a>. BGE-M3 is an embedding model that supports the creation of embeddings across up to 100 languages, with various forms of embeddings (sparse, dense and multi-vector), and can process up to 8k tokens. You can <a href="https://arxiv.org/abs/2402.03216">take a look at the paper</a>, I think it is quite interesting research and engineering-wise. For example, how they use <code class="language-plaintext highlighter-rouge">self-knowledge distillation</code> to train for the sparse, dense and multi-vector embedding objectives, and how they batch their data for efficient use of GPU compute.</p>

<p>Back to the work:</p>

<p>The team thought to improve on the quality of BGE-M3 for Nigerian languages. This means if such a model works well enough, it has search use cases in those languages, serving people who speak them as their main language. For example, if one sends text messages in Igbo, it becomes possible to effectively search past text messages. Most software that support search today, do so in English; this is problematic because the user often has to rely solely on keywords that appear in the documents.</p>

<p>So with this model, it is possible to do:</p>

<ul>
  <li>Yoruba queries to search Yoruba documents</li>
  <li>Igbo queries to search Igbo documents</li>
  <li>Hausa queries to search Hausa documents</li>
</ul>

<p>Towards the end of the project, the team also wanted to make English queries work semantically, so you can search in English without the keywords appearing in the target document. This kind of search benefits users who want to search within local language documents, but only know English.</p>

<p>The main challenges faced in this work include, but are not limited to:</p>

<ul>
  <li>Getting data to train the model.</li>
  <li>Building a data cleaning pipeline to reduce the amount of crap we train on.</li>
  <li>Finding an LLM suitable for translating from our target languages to English.</li>
  <li>Efficiently run LLM inference for the translation tasks on the training data.</li>
</ul>

<p>I used Manus.ai to vibecode the demo below. It shows the English-Yoruba search use case, with our model running in the background.</p>

<p><img src="https://res.cloudinary.com/haks/image/upload/v1756498902/HAKSOAT_Blog/indaba-25/bge-m3-naija-poc.gif" alt="Semantic Search POC" class="align-center" /></p>

<p>The demo involves the following things:</p>

<ul>
  <li>Indexing Surah Taha from the Yoruba Qur’an using the embedding model.</li>
  <li>Generating embeddings with the English query using the embedding model.</li>
  <li>Using cosine similarity to find the most similar verses to the query.</li>
  <li>Generating translations from Yoruba to English for highlighted text (the translations generally don’t make sense but are useful here).</li>
</ul>

<p>I did this using Manus.ai and I was quite impressed by the results. I think a PoC like this is a good use case for vibecoding, as I do not care if it does things the correct way, as long as it works. You can <a href="https://gist.github.com/HAKSOAT/0a39edeacd737b8e9e403bc1c049dbd4">find the prompt I used in this GitHub Gist</a> if interested.</p>

<h3 id="the-end">The End</h3>

<p>That’s all I have to share in this article about my top five moments at the Deep Learning Indaba 2025 in Rwanda. If you are still reading, I hope you benefitted a thing or two from the piece. As a reward 😂, you can find the Colab notebooks used at the practical sessions at the Indaba at <a href="https://github.com/deep-learning-indaba/indaba-pracs-2025/tree/main">indaba-pracs-2025 on GitHub</a>.</p>

<p>See you in the next one.</p>]]></content><author><name>Habeeb Shopeju</name><email>shopejuh@gmail.com</email></author><category term="experience" /><summary type="html"><![CDATA[I attended Deep Learning Indaba 2025 in Rwanda, so I briefly share my experience and a poster presentation.]]></summary></entry><entry><title type="html">A Letter after Hajj</title><link href="https://www.haksoat.com/letter-after-hajj/" rel="alternate" type="text/html" title="A Letter after Hajj" /><published>2025-06-19T00:00:00+01:00</published><updated>2025-06-19T00:00:00+01:00</updated><id>https://www.haksoat.com/letter-after-hajj</id><content type="html" xml:base="https://www.haksoat.com/letter-after-hajj/"><![CDATA[<h2 id="a-letter-after-hajj">A Letter after Hajj</h2>

<p>In the name of Allah, the Most Gracious, the Most Merciful, it has been a couple of days since performing Hajj at the sacred sites in Makkah, Mina, Mt Arafat, and Muzdalifah. Without any iota of doubt, the trip was an incredible experience; one that suits the Yoruba proverb:</p>

<p>“Iroyin, o to afoju ba, eni ba de ibe lo le so.”</p>

<p>Meaning:</p>

<p>“Narration cannot be compared to experience; only those who have experienced can tell.”</p>

<p>I will not describe the details of the trip, as that is difficult. Rather, I will try to put my feelings about the Umrah and Hajj experience into words.</p>

<p>There were so many people in Mecca for Hajj; <a href="https://www.stats.gov.sa/en/w/news/49">the stats say about 1.67 million pilgrims</a> were there this year. Being one of so many people is a humbling experience, one that screams, “You are not so special.” The constant recitation of the Talbiyah swiftly counters with feelings of hope and gratitude.</p>

<p>“لَبَّيْكَ اللَّهُمَّ لَبَّيْكَ، لَبَّيْكَ لَا شَرِيكَ لَكَ لَبَّيْكَ، إِنَّ الْحَمْدَ وَالنِّعْمَةَ لَكَ وَالمُلْكَ، لَا شَرِيكَ لَكَ”</p>

<p>Transliterated as:</p>

<p>“Labbayka Allāhumma labbayk, labbayka lā sharīka laka labbayk, inna al-ḥamda wa-n-ni‘mata laka wa-l-mulk, lā sharīka lak.”</p>

<p>Meaning:</p>

<p>“Here I am, O Allah, here I am.<br />
Here I am, You have no partner, here I am.<br />
Indeed, all praise, grace, and sovereignty are Yours.<br />
You have no partner.”</p>

<p>At Hajj, I made <a href="https://hajjumrahplanner.com/tawaf/">seven circuits (tawaf) around the Kaaba</a>, drank <a href="https://www.aljazeera.com/news/2025/6/4/the-water-of-hajj-a-simple-illustrated-guide-to-zamzam">zamzam water</a>, <a href="https://hajjumrahplanner.com/safa-marwa/">went back and forth between Mt Al-Safa and Mt Al-Marwah</a> seven times, went to <a href="https://thepilgrim.co/mount-arafat/">Mt Arafat</a> for prayers, slept in the open at <a href="https://hajjumrahplanner.com/day-2-9th-of-dhul-hijjah-muzdalifah/">Muzdalifah</a>, and <a href="https://hajjumrahplanner.com/rami-al-jamarat/">threw stones at the various Jamaraat for three days</a>. When performing a rite, I would think to myself, “I am doing the same thing many others from all corners of the Earth have done for centuries in the same manner. How incredible!!! “ In those days, my heart was tuned for ibaadah like never before and it felt grand, in spite of the physical exertion and stress involved.</p>

<p>At Hajj, I had the opportunity to observe prayers at the <a href="https://en.wikipedia.org/wiki/Masjid_al-Haram">Masjid Al-Haram</a>, the mosque which surrounds <a href="https://en.wikipedia.org/wiki/Kaaba">the Kaaba</a>. Its beauty, size, and the sight of so many people in it made me feel grateful for the opportunity. All my life, I have observed prayers in the direction of the Kaaba; to then observe my prayers while seeing that destination from a close distance was surreal. I had multiple chances to touch the Kaaba at various points during tawaf—it is not like something magical or spiritual happens when you do so​​—and I was delighted to go that close. Given the size of Masjid Al-Haram, I am grateful for the police and guards who worked there, directing the traffic and taking steps to prevent a potential stampede. May Allah grant them eternal protection as they looked after us.</p>

<p>I found the locals to generally be kind, welcoming, and charitable. In the barely bearable weather, reaching 45 degrees at some point, I would see locals giving away bottles of water, ice cream, dates, food, and other things that could potentially bring relief to the Hujaaj (pilgrims). When I mentioned that my Arabic was weak but that I was learning, some were patient enough to have very brief conversations, listening to me use words in unsuitable contexts. May Allah reward them abundantly for their kind gestures.</p>

<p>I kept a list of every country I came across during Hajj. Given that I only walked around when necessary, it was incredible to see that I came across people from fifty countries—see the list in the appendix. I encountered people from various places such as Ethiopia, Ghana, Canada, China, Palestine, Bosnia, and Italy, to name a few.</p>

<p>I end this letter where I started this journey, Al Madinah Al Munawwarah. Al Madinah was my arrival point in the Kingdom of Saudi Arabia and I spent about three days in the city. <a href="https://en.wikipedia.org/wiki/Prophet%27s_Mosque">Masjid An-Nabawi (The Prophet’s Mosque)</a> is a beautiful piece of architecture, to say the least. I looked forward to observing prayers there, and the sajdah (prostration) on its perfumed rugs was heavenly. While Umrah or Hajj rites cannot be performed in Al Madinah, my stay there was definitely blissful and calm.</p>

<p>Umrah and Hajj were amazing experiences. I will miss the cities: <a href="https://en.wikipedia.org/wiki/Medina">Al-Madinah Al-Munawwarah</a> and <a href="https://en.wikipedia.org/wiki/Mecca">Makkah Al-Mukarramah</a>. It will take quite some time for the calls “Yala Hajj, Yala Hajj” and the cheers “Hajjiiiiii” to leave my immediate memory. I hope everyone wishing to experience Umrah and Hajj gets their wish in the near future.</p>

<p>Yours Sincerely,<br />
Al-Hajj Habeeb Kehinde Shopeju</p>

<h2 id="appendix">Appendix</h2>

<h3 id="the-motivation">The Motivation</h3>

<p>The first time I came across a letter of this kind was in 2023, and it was that of <a href="https://en.wikipedia.org/wiki/Malcolm_X">Brother Malcolm</a> in his piece, “<a href="https://www.icit-digital.org/articles/malcolm-x-s-letter-from-mecca-april-20-1964">Malcolm X’s Letter From Mecca (April 20, 1964)</a>.” That letter was in his book, “<a href="https://www.amazon.co.uk/Autobiography-Malcolm-X/dp/0141032723">The Autobiography of Malcolm X</a>”, which I would recommend to any Muslim or African. The letter stirred my soul. It made me more excited than I had ever been about going for Hajj. I lack the clout or political or philosophical prowess that Brother Malcolm had at the time of writing his letter. However, I write this letter with the hope that it would somehow become a beacon of light for someone out there, just as that letter from 1964 was to me fifty-nine years later. May Allah grant him goodness in the hereafter and high ranks in Jannah.</p>

<h3 id="list-of-countries">List of Countries</h3>

<ol>
  <li>Algeria 🇩🇿</li>
  <li>Bangladesh 🇧🇩</li>
  <li>Belgium 🇧🇪</li>
  <li>Bosnia 🇧🇦</li>
  <li>Burkina Faso 🇧🇫</li>
  <li>Cameroun 🇨🇲</li>
  <li>Canada 🇨🇦</li>
  <li>Chad 🇹🇩</li>
  <li>China 🇨🇳</li>
  <li>Comoros Island 🇰🇲</li>
  <li>Egypt 🇪🇬</li>
  <li>Equatorial Guinea 🇬🇶</li>
  <li>Ethiopia 🇪🇹</li>
  <li>Gambia 🇬🇲</li>
  <li>Ghana 🇬🇭</li>
  <li>Guinea 🇬🇳</li>
  <li>Indonesia 🇮🇩</li>
  <li>Iran 🇮🇷</li>
  <li>Ivory Coast 🇨🇮</li>
  <li>Italy 🇮🇹</li>
  <li>Kenya 🇰🇪</li>
  <li>Kyrgyzstan 🇰🇬</li>
  <li>Lebanon 🇱🇧</li>
  <li>Liberia 🇱🇷</li>
  <li>Malaysia 🇲🇾</li>
  <li>Mauritania 🇲🇷</li>
  <li>Myanmar 🇲🇲</li>
  <li>Morocco 🇲🇦</li>
  <li>Mozambique 🇲🇿</li>
  <li>Niger 🇳🇪</li>
  <li>Nigeria 🇳🇬</li>
  <li>Oman 🇴🇲</li>
  <li>Pakistan 🇵🇰</li>
  <li>Palestine 🇵🇸</li>
  <li>Philippines 🇵🇭</li>
  <li>Russia 🇷🇺</li>
  <li>Saudi Arabia 🇸🇦</li>
  <li>Senegal 🇸🇳</li>
  <li>Sierra Leone 🇸🇱</li>
  <li>Somalia 🇸🇴</li>
  <li>Sudan 🇸🇩</li>
  <li>Suriname 🇸🇷</li>
  <li>Tajikistan 🇹🇯</li>
  <li>Thailand 🇹🇭</li>
  <li>Tunisia 🇹🇳</li>
  <li>Turkey 🇹🇷</li>
  <li>Turkmenistan 🇹🇲</li>
  <li>United Kingdom 🇬🇧</li>
  <li>Uzbekistan 🇺🇿</li>
  <li>Yemen 🇾🇪</li>
</ol>]]></content><author><name>Habeeb Shopeju</name><email>shopejuh@gmail.com</email></author><category term="religion" /><summary type="html"><![CDATA[In this letter, I write about how I felt during the Umrah and Hajj experience.]]></summary></entry><entry><title type="html">Building An Embedding Service: Sharing My Three Surprises</title><link href="https://www.haksoat.com/ahnlich-ai-embedding-service-surprises/" rel="alternate" type="text/html" title="Building An Embedding Service: Sharing My Three Surprises" /><published>2025-01-07T00:00:00+01:00</published><updated>2025-01-07T01:20:02+01:00</updated><id>https://www.haksoat.com/ahnlich-ai-embedding-service-surprises</id><content type="html" xml:base="https://www.haksoat.com/ahnlich-ai-embedding-service-surprises/"><![CDATA[<p>Hello dear reader, in my article, <a href="/working-on-ahnlich/">We are working on Ahnlich, a Database to Aid Semantic Search</a> I gave an introduction to the project I have been working on recently. In that piece, <a href="/working-on-ahnlich/#my-ask">I promised to write a couple of articles</a>, of which this is the first one I am taking a stab at.</p>

<p>As a quick reminder, Ahnlich is a suite of tools built to ease the developer workflow for integrating semantic search functionality into products and services. It provides <a href="https://github.com/deven96/ahnlich/tree/main/ahnlich/db">a database</a> (Ahnlich-db), <a href="https://github.com/deven96/ahnlich/tree/main/ahnlich/ai">an embedding service</a> (Ahnlich-ai), <a href="https://github.com/deven96/ahnlich/tree/main/ahnlich/cli">a CLI service</a> (Ahnlich-cli), and various language clients. A significant amount of my contributions to Ahnlich have been to the embedding service, which is why I thought it interesting to write about some surprises I encountered while building.</p>

<p>Here are the surprises I will be writing about:</p>

<ul>
  <li>Varying Image Decoding Implementations</li>
  <li>The Dip in Similarity Scores for Image-Text Data</li>
  <li>The Importance of Model-Specific Preprocessing</li>
</ul>

<p>Before I get into writing about the surprises, here is some useful context about what the embedding service does.</p>

<h2 id="ahnlich-ai-context">Ahnlich-ai Context</h2>

<p><strong>What does Ahnlich-ai do?</strong></p>

<p><a href="https://github.com/deven96/ahnlich/tree/main">Ahnlich-ai</a> is an embedding service that takes in some input—which can be an image or text, as at the time of writing—and then returns vectors. When Ahnlich-ai is started, it loads up a set of supported models, and these models can be used to generate embeddings. The models to be loaded up are either provided as an argument or not, in which case Ahnlich-ai falls back to the default set. When Ahnlich-ai returns embeddings, the hope is that they contain information that can be relied on to convey similarity between multiple items and can be used for semantic search tasks.</p>

<p><strong>How does Ahnlich-ai do it?</strong></p>

<p>The embedding service relies on <a href="https://github.com/huggingface/hf-hub">huggingface_hub</a> and the <a href="https://github.com/pykeio/ort">onnxruntime</a> to pull model weights and generate embeddings, respectively.</p>

<p>Hugging Face is a platform that enables machine learning experimentation and development. <a href="https://huggingface.co/docs/hub/en/index">Hugging Face has a hub that hosts more than 900k models and 200k datasets</a>; it is via this hub that Ahnlich gets the model configurations and ONNX model weights used to convert inputs into embeddings. The <a href="https://onnxruntime.ai/">ONNX Runtime</a> is a machine learning tool that makes it possible to run inference with ONNX models; it provides optimizations and accelerations that reduce inference time. ONNX (Open Neural Network Exchange) is an intermediary representation for machine learning models, making models accessible across various machine learning frameworks and programming languages.</p>

<p>I think this context should suffice, but if you want to learn more you can read the <a href="/working-on-ahnlich/">Ahnlich introduction article</a>. Let us dive right into the surprises.</p>

<h2 id="varying-image-decoding-implementations">Varying Image Decoding Implementations</h2>

<p>When looking to add the image-to-embeddings functionality, the team hoped to find existing crates that have done a large part of this work. We found one, called <a href="https://github.com/Anush008/fastembed-rs">fastembed-rs</a>; which is a Rust implementation of <a href="https://github.com/qdrant/fastembed">Python’s fastembed package</a>. It was great at the start, but it had one limitation—at least for Ahnlich’s use case—which is that it always runs preprocessing on the image before inference. For Ahnlich, this was not great because we wanted to give users the choice of using custom or model-specific preprocessing.</p>

<p><img src="https://res.cloudinary.com/haks/image/upload/v1736222270/HAKSOAT_Blog/embedding-service-surprises/embedding_inference_workflow.png" alt="Embedding Generation Workflow" /></p>

<p>To make this work, the first approach was to find a way to access the methods for doing direct inference without calling the preprocessing logic. However, most of those functions were <a href="https://doc.rust-lang.org/reference/visibility-and-privacy.html">private and not visible to consumers</a> of the crate, meaning there was no way to call them.</p>

<p>The next approach was to lift the implementation from fastembed-rs into the Ahnlich-ai project. However, this was not seamless considering that project structures differ and we were only interested in a tiny bit of the code—the inference code. We had to do a considerable rewrite on the lifted code. This worked, but since the implementation was now essentially rewritten, it became important to test that the embeddings were as expected.</p>

<p>This is where the surprise came in; reading the same image in Python and Rust gave different pixel values. It took a while to understand this. I went about gradually checking various parts of the code to understand the cause of the disparity, finally narrowing it down to the decoding bits.</p>

<p>Take this image for example:</p>

<p><img src="https://res.cloudinary.com/haks/image/upload/v1736222275/HAKSOAT_Blog/embedding-service-surprises/python_rust_tennis.png" alt="Pixel Differences Test Image" /></p>

<p>Below are some of the pixel values gotten from reading the image in Python and in Rust, the array format is <code class="language-plaintext highlighter-rouge">(number_of_channels, image_height, image_width)</code>. If you look closely, you will see the differences in pixel values. I tried to make some of the differing numbers in bold, so they are easier to identify:</p>

<p><img src="https://res.cloudinary.com/haks/image/upload/v1736222275/HAKSOAT_Blog/embedding-service-surprises/python_rust_pixels.png" alt="Python-Rust Pixel Differences" /></p>

<p>These differences in pixel values are not visible when the images are rendered; from that angle it is not a big deal. So you may ask:</p>

<blockquote>
  <p>If the differences are not visible, why is it important to be concerned?</p>
</blockquote>

<p>Answer: It becomes harder to test the correctness of the embeddings using the full pipeline.</p>

<p>The pixel values may pass through preprocessing, then go into the models for embedding generation, at which point the effect becomes more apparent.</p>

<p>To make the message clearer, here are the embeddings gotten from sending the preprocessed values into the <a href="https://huggingface.co/Qdrant/clip-ViT-B-32-vision">CLIP Vision</a> model:</p>

<p><img src="https://res.cloudinary.com/haks/image/upload/v1736222272/HAKSOAT_Blog/embedding-service-surprises/python_rust_embeddings.png" alt="Python-Rust Embedding Differences" /></p>

<p>Do you observe the disparity in the embedding values? There is a mix of small and big differences in the values; my guess—which may be a good idea to confirm—is that both embeddings are very close in the embedding space, making them similar enough to be substitutes.</p>

<p><em>Takes a break from writing to confirm hypothesis.</em></p>

<blockquote>
  <p>The similarity score between both embeddings is 0.967, so they are close enough to be considered alternatives.</p>
</blockquote>

<p><em>Returns to writing.</em></p>

<p>From the machine learning perspective, this variation is not an issue; however, from the software engineering point of view, it is. How can I verify that the custom implementation—the one in Rust—is doing what I expect it to do? Especially as the output differs from the Python one, and I can’t also tell what the magnitude of the difference may be.</p>

<p>So what did I do about this issue?</p>

<p>On the Python side, I:</p>

<ol>
  <li>Extracted the preprocessed input to the model as a NumPy array.</li>
  <li>Extracted the output of the model as a NumPy array.</li>
  <li>Saved both arrays as an <code class="language-plaintext highlighter-rouge">.npz</code> file.</li>
</ol>

<p><img src="https://res.cloudinary.com/haks/image/upload/v1736222270/HAKSOAT_Blog/embedding-service-surprises/export_python_artifacts.png" alt="Exporting Embedding Workflow Artifacts" /></p>

<p>On the Rust side, I:</p>

<ol>
  <li>Assumed that the image decoding part of the code is working as expected; that code is largely from Rust’s <a href="https://crates.io/crates/image">image crate</a>, so it is pretty much a standard.</li>
  <li>Isolated the inference part of the Rust pipeline.</li>
  <li>Loaded the saved arrays i.e., the <code class="language-plaintext highlighter-rouge">.npz</code> file, using a crate like <a href="https://docs.rs/npyz/latest/npyz/index.html">npyz</a>.</li>
  <li>Sent the preprocessed input into the isolated Rust inference code.</li>
  <li>Verified that the output of the Rust inference and that of the Python inference are the same.</li>
</ol>

<p><img src="https://res.cloudinary.com/haks/image/upload/v1736222273/HAKSOAT_Blog/embedding-service-surprises/isolate_rust_inference.png" alt="Isolating Rust Inference" /></p>

<p>By doing this, I was able to verify that the inference code was working as expected. This setup could also be made into a unit test, using the preprocessed input and output from Python’s side of things as mocks.</p>

<p>The main lesson here is to beware of the difference in decoding implementations across languages and libraries for various forms of data. The caution is not necessarily due to huge differences in implementation—heck, it may even be that—but because the variance will propagate down your pipeline. When you finally notice the disparity, it can cause sleepless nights trying to understand the root cause. Finally, if you come across an issue like this, find a way to isolate and test the important parts.</p>

<h2 id="the-dip-in-similarity-scores-for-image-text-data">The Dip in Similarity Scores for Image-Text Data</h2>

<p>When working on Ahnlich-ai, the team first catered to implementing functionality that converts text to embeddings, after which we worked on one to convert images to embeddings. The addition of the images-to-embeddings functionality paved the way for multimodal search use cases.</p>

<p>However, here is what we noticed: when we tried to check for the similarity between texts or between images, the scores would be within a “normal range.” However, when we tried to do this across modalities, say between images and texts, the scores would be strangely low.</p>

<p>Given a football-themed setup like this:</p>

<p>Doc 1: “An event is ongoing on the green field.”<br />
Doc 2: “A football match happens between two teams.”<br />
Doc 3: “Wayne Rooney’s famous overhead.”</p>

<p>Then a text query like:</p>

<p>“Let us get the ball rolling.”</p>

<p>And an image query like:</p>

<p><img src="https://res.cloudinary.com/haks/image/upload/v1736222274/HAKSOAT_Blog/embedding-service-surprises/rooney_overhead_kick_query.jpg" alt="Modality Gap Test Image" /></p>

<p>Before looking at the similarity scores, anyone with some football knowledge can tell that the image query is more similar to the documents than the text query.</p>

<p>NB: In this example, the images and texts are converted into embeddings using the <a href="https://huggingface.co/Qdrant/clip-ViT-B-32-vision">CLIP Vision</a> and <a href="https://huggingface.co/Qdrant/clip-ViT-B-32-text">CLIP Text</a> models, respectively.</p>

<p>Let’s see the similarity scores for text-text data:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>[("An event is ongoing on the green field.", Similarity(value=0.828507)),   
("A football match happens between two teams.", Similarity(value=0.76724356)),   
("Wayne Rooney"s famous overhead.", Similarity(value=0.62843007))]
</code></pre></div></div>

<p>You see how the values are all above 0.5?</p>

<p>Now let’s see the similarity scores for text-image data:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>[("Wayne Rooney's famous overhead.", Similarity(value=0.2871881)),   
("A football match happens between two teams.", Similarity(value=0.26372734)),   
("An event is ongoing on the green field.", Similarity(value=0.18715198))]
</code></pre></div></div>

<p>Do you notice how the scores dropped?</p>

<p>All the scores from the text-text similarity are higher than the scores from the text-image similarity, despite the image query being more relevant than the text query. One thing to note is that the model seems to understand the context; it ranks <code class="language-plaintext highlighter-rouge">"Wayne Rooney's famous overhead."</code> above the rest, and that is correct.</p>

<p>The issue with low scores was quite surprising, as it initially seemed to be due to a bug somewhere. I looked into the code, scouring for explanations but did not find any. In the end, I found explanations outside the code.</p>

<p>Before I go into that, you may ask:</p>

<blockquote>
  <p>Why is the drop in scores important if the results are still ranked in an order of similarity?</p>
</blockquote>

<p>That is since the texts for these images are already ranked like:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>["Wayne Rooney's famous overhead.",   
"A football match happens between two teams.",   
"An event is ongoing on the green field."]
</code></pre></div></div>

<p>Why does it matter what the scores are?</p>

<p>One answer is thresholds. If one builds software and works on the assumption that items above a certain threshold are similar enough to be shown to the user, an issue like this would need a change in threshold values to surface relevant items. Let’s say the threshold is agreed upon to be 0.8, and then the image-text scenario returns a score less than 0.3, the threshold will require some modification to fit the domain.</p>

<p>Another answer is interpretability. In the described scenario, following the scores would lead to an interpretation that the text is more similar than the image to the documents, which is wrong. It is hard enough to interpret similarity scores; an issue like this makes it even harder.</p>

<p>So what is the cause of this issue? The answer is in <a href="https://jina.ai/news/the-what-and-why-of-text-image-modality-gap-in-clip-models/">the modality gap</a>.</p>

<p>A summary of <a href="https://jina.ai/news/the-what-and-why-of-text-image-modality-gap-in-clip-models/">the linked article</a> can be described via this image:</p>

<p><img src="https://res.cloudinary.com/haks/image/upload/v1736222273/HAKSOAT_Blog/embedding-service-surprises/jina_modality_gap.png" alt="Jina AI's Modality Gap Illustration" /></p>

<p>The embeddings of a given medium tend to cluster in an area significantly different from other mediums. Hence, the items within a medium tend to be closer to each other and, as a result, have higher scores when compared to items in other mediums.</p>

<p>There are a couple of reasons for this:</p>

<p>One is <strong>the difference in models</strong>. Each data modality (image and text) is processed by its own encoder with separate architecture and weight initializations. For example, CLIP typically uses a vision transformer or ResNet for images and a text transformer for textual data. While CLIP trains these models together to align their embeddings, the fact that the embeddings originate from two distinct encoders inherently creates a modality gap. This gap arises because the two encoders may capture different kinds of features due to their distinct architectures despite being trained with a shared goal.</p>

<p>Another is <strong>the loss function</strong>. The contrastive loss function used in training CLIP models treats the data as a batch of image-text pairs. For each image, there is one associated text (to form a positive pair), and all other texts in the batch are treated as negatives. For a batch of size N, this means each image is paired with one true positive text and N−1 negative texts. The loss aims to maximize the similarity between embeddings of the positive pairs while minimizing it for the negatives. However, this binary “positive vs. negative” treatment can oversimplify the alignment process. Some of the “negative” texts might still have partial relevance to the image but are treated as entirely dissimilar. This limitation can create noise in the optimization process and make it harder for the model to properly align images and texts.</p>

<p>Now that you know why this happens, what was done to fix this issue? Nothing, at least not yet.</p>

<p>However, it is something the development team is aware of and is a known issue in the machine learning community. While doing further research for writing this article, I came across some papers like <a href="https://arxiv.org/abs/2203.02053">Mind the Gap: Understanding the Modality Gap in Multi-modal Contrastive Representation Learning</a> and <a href="https://arxiv.org/abs/2405.18570">It’s Not a Modality Gap: Characterizing and Addressing the Contrastive Gap</a> which look into further understanding the cause of this gap and potential solutions.</p>

<h2 id="the-importance-of-model-specific-preprocessing">The Importance of Model-Specific Preprocessing</h2>

<p>Given my experience in machine learning, I would not exactly say I found it surprising to see that model-specific processing is important. Instead, I am including it in this article because I think it is beneficial to still point it out, and not just the idea but the magnitude of its importance.</p>

<p>Earlier in the article, I mentioned having to do custom inference implementations while working on Ahnlich-ai due to the tool’s flexibility requirement. Part of the custom implementations was adding logic to do model-specific preprocessing.</p>

<p>Image encoder models will often work provided the image dimensions meet the requirements. However, if you want to get the best out of these models, you have to apply their specific preprocessing instructions. Some of these operations include normalization, resizing, and rescaling images to get them in the best format for inference, not just to meet the dimension requirement. Thanks to Huggingface, you would usually find the preprocess config in the <code class="language-plaintext highlighter-rouge">preprocessor_config.json</code> file for the target model; for example, <a href="https://huggingface.co/microsoft/resnet-50/blob/main/preprocessor_config.json">this link contains the preprocessing instructions for the ResNet50</a>.</p>

<p>Writing code to perform these specific operations can take some effort, especially since it should work for various models. So <a href="/principles-machine-learning-engineer/#fck-and-unfck">in the spirit of prototyping</a>, the team decided to only implement the resizing transformation, ensuring that all images meet the dimension requirement—this is 224 x 224 for the ResNet50. As expected, this worked, and the ranking order made sense when eyeballing some results; however, the similarity scores were weird, unusually high.</p>

<p>Let’s look at the following setup to fully understand what “weird” means in context.</p>

<p>Say we have the following images to be indexed:<br />
<img src="https://res.cloudinary.com/haks/image/upload/v1736222273/HAKSOAT_Blog/embedding-service-surprises/image_index_specific_processing.png" alt="Image Preprocessing Index Images" /></p>

<p>From left to right, I will refer to the images as <code class="language-plaintext highlighter-rouge">Image1</code>, <code class="language-plaintext highlighter-rouge">Image2</code>, <code class="language-plaintext highlighter-rouge">Image3</code> and <code class="language-plaintext highlighter-rouge">Image4</code>.</p>

<p>And we have the following query image:</p>

<p><img src="https://res.cloudinary.com/haks/image/upload/v1736222271/HAKSOAT_Blog/embedding-service-surprises/image_query_specific_processing.png" alt="Image Preprocessing Query Image" /></p>

<p>This is a basketball-themed example, and without running the query, I would have a couple of expectations:</p>

<ul>
  <li><code class="language-plaintext highlighter-rouge">Image3</code> should be ranked first since it is basketball being played as in the query image.</li>
  <li><code class="language-plaintext highlighter-rouge">Image1</code> should be ranked second since it is an <a href="https://en.wikipedia.org/wiki/Air_Jordan">Air Jordan</a> and it is related to the individual in the query image, <a href="https://en.wikipedia.org/wiki/Michael_Jordan">Michael Jordan</a>.</li>
  <li><code class="language-plaintext highlighter-rouge">Image2</code> and <code class="language-plaintext highlighter-rouge">Image4</code> can be ranked third and fourth in any order.</li>
</ul>

<p>So how do the images and similarity scores fare when running only the resizing operation?</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>[("Image3", Similarity(value=0.99914294)),   
("Image1", Similarity(value=0.9987868)),   
("Image4", Similarity(value=0.9984776)),   
("Image2", Similarity(value=0.9978745))]
</code></pre></div></div>

<p>The rankings look as expected, but the numbers “feel off.” Why are they all that high?</p>

<p>I believe that possessing some knowledge of the domain and data is the only way to develop this kind of “feel” and intuition. For me, this experience further cements <a href="/principles-machine-learning-engineer/#know-the-data-and-its-transforms">the importance of understanding the data and its transforms as a machine learning engineer</a>.</p>

<p>I do not know for sure why they are all that high; that is a question that probably deserves an answer. However, on implementing the model-specific preprocessing operations, here is how the images and similarity scores turn out:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>[("Image3", Similarity(value=0.6100306)),   
("Image1", Similarity(value=0.25423393)),   
("Image4", Similarity(value=0.24817139)),   
("Image2", Similarity(value=0.17258035))]
</code></pre></div></div>

<p>The similarity scores are distinct and easier to explain. The scores for <code class="language-plaintext highlighter-rouge">Image1</code> and <code class="language-plaintext highlighter-rouge">Image4</code> are much closer than I would like, but this is a much better result compared to working without the model-specific preprocessing operations.</p>

<p>It is not surprising that the results are better, but I did not expect the results to be this different. I do not think the approach of only using the resizing operation as done on this project was a bad decision; it served its purpose. However, it did help me see that the more processors are tailored to a model’s strength, the better.</p>

<p>There’s not much to take away from here other than the need to take preprocessing as seriously as the inference logic itself. Considering that the outputs of the preprocessing will be going into the model, one can say it dictates the quality of the model’s results.</p>

<h2 id="an-extra-surprise-rusts-error-handling-philosophy">An Extra Surprise: Rust’s Error Handling Philosophy</h2>

<p>This is not exactly a surprise related to the embedding service; it is more about the language used: Rust.</p>

<p>I was initially going to call this “Rust’s Verbosity,” because the language is actually verbose compared to Python. However, there’s not much value in saying that; statically typed programming languages tend to be verbose.</p>

<p>It occurred to me that it is not exactly Rust’s verbosity that put me off at the start, but dealing with the language’s approach to handling errors. One of Rust’s main selling points is its ability to nudge programmers to write robust code, and this is thanks to its <a href="https://doc.rust-lang.org/book/ch09-03-to-panic-or-not-to-panic.html">error handling philosophy</a>.</p>

<p>Here is a trivial example that I hope conveys why I initially struggled with it.<br />
Let’s imagine I want to read the first line of a file in Python; I can simply do this:</p>

<figure class="highlight"><pre><code class="language-python" data-lang="python"><span class="k">def</span> <span class="nf">read_first_line</span><span class="p">(</span><span class="n">filepath</span><span class="p">):</span>
    <span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="n">filepath</span><span class="p">,</span> <span class="s">'r'</span><span class="p">)</span> <span class="k">as</span> <span class="nb">file</span><span class="p">:</span>
        <span class="n">line</span> <span class="o">=</span> <span class="nb">file</span><span class="p">.</span><span class="n">readline</span><span class="p">()</span>
        <span class="k">return</span> <span class="n">line</span> </code></pre></figure>

<p>This code will run in Python, even if I can think of some reasons why it can crash. Such as:</p>

<ul>
  <li><code class="language-plaintext highlighter-rouge">filepath</code> may be the wrong data type, e.g., it may be a boolean data type.</li>
  <li>There may be issues opening the file from the <code class="language-plaintext highlighter-rouge">filepath</code>, e.g., if the file does not exist.</li>
  <li>There may be issues reading the file, e.g., incorrect file formatting.</li>
</ul>

<p>The thing is, if I am in experimentation mode, I do not care much about handling potential failure cases; I simply want to just get something that works. So in this case, I would only test with a file that I expect to work to avoid dealing with the error handling detail.</p>

<p>However, if I were to do something similar in Rust, it would fail.</p>

<p>The equivalent would be something like:</p>

<figure class="highlight"><pre><code class="language-rust" data-lang="rust"><span class="k">fn</span> <span class="nf">read_first_line</span><span class="p">(</span><span class="n">filepath</span><span class="p">:</span> <span class="o">&amp;</span><span class="nb">str</span><span class="p">)</span> <span class="k">-&gt;</span> <span class="nb">String</span> <span class="p">{</span>
    <span class="k">let</span> <span class="n">file</span> <span class="o">=</span> <span class="nn">File</span><span class="p">::</span><span class="nf">open</span><span class="p">(</span><span class="n">filepath</span><span class="p">);</span>
    
    <span class="k">let</span> <span class="k">mut</span> <span class="n">reader</span> <span class="o">=</span> <span class="nn">BufReader</span><span class="p">::</span><span class="nf">new</span><span class="p">(</span><span class="n">file</span><span class="p">);</span>
    <span class="k">let</span> <span class="k">mut</span> <span class="n">line</span> <span class="o">=</span> <span class="nn">String</span><span class="p">::</span><span class="nf">new</span><span class="p">();</span>
    <span class="n">reader</span><span class="nf">.read_line</span><span class="p">(</span><span class="o">&amp;</span><span class="k">mut</span> <span class="n">line</span><span class="p">);</span>
    <span class="n">line</span>
<span class="p">}</span></code></pre></figure>

<p>But this fails with:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>21 |     let mut reader = BufReader::new(file);
   |                      -------------- ^^^^ the trait `std::io::Read` is not implemented for `Result&lt;File, std::io::Error&gt;`
   |                      |
   |                      required by a bound introduced by this call
</code></pre></div></div>

<p>This simply means that <code class="language-plaintext highlighter-rouge">File::open(filepath)</code> is expected to return a <code class="language-plaintext highlighter-rouge">Result</code> object that can either be the <code class="language-plaintext highlighter-rouge">File</code> object or an <code class="language-plaintext highlighter-rouge">io::Error</code>. In other words, Rust wants you to decide how to deal with the situation where the file cannot be opened. Rust will also make a similar complaint for the <code class="language-plaintext highlighter-rouge">reader.read_line(&amp;mut line)</code> line if I handle that initial case.</p>

<p>In the end, the code may look something like:</p>

<figure class="highlight"><pre><code class="language-rust" data-lang="rust"><span class="k">fn</span> <span class="nf">read_first_line</span><span class="p">(</span><span class="n">filepath</span><span class="p">:</span> <span class="o">&amp;</span><span class="nb">str</span><span class="p">)</span> <span class="k">-&gt;</span> <span class="nb">Result</span><span class="o">&lt;</span><span class="nb">String</span><span class="p">,</span> <span class="nb">String</span><span class="o">&gt;</span> <span class="p">{</span>
    <span class="k">let</span> <span class="n">file</span> <span class="o">=</span> <span class="nn">File</span><span class="p">::</span><span class="nf">open</span><span class="p">(</span><span class="n">filepath</span><span class="p">)</span><span class="nf">.map_err</span><span class="p">(|</span><span class="n">e</span><span class="p">|</span> <span class="nd">format!</span><span class="p">(</span><span class="s">"Failed to open file: {}"</span><span class="p">,</span> <span class="n">e</span><span class="p">))</span><span class="o">?</span><span class="p">;</span>

    <span class="k">let</span> <span class="k">mut</span> <span class="n">reader</span> <span class="o">=</span> <span class="nn">BufReader</span><span class="p">::</span><span class="nf">new</span><span class="p">(</span><span class="n">file</span><span class="p">);</span>
    <span class="k">let</span> <span class="k">mut</span> <span class="n">line</span> <span class="o">=</span> <span class="nn">String</span><span class="p">::</span><span class="nf">new</span><span class="p">();</span>
    <span class="n">reader</span><span class="nf">.read_line</span><span class="p">(</span><span class="o">&amp;</span><span class="k">mut</span> <span class="n">line</span><span class="p">)</span><span class="nf">.map_err</span><span class="p">(|</span><span class="n">e</span><span class="p">|</span> <span class="nd">format!</span><span class="p">(</span><span class="s">"Failed to read from file: {}"</span><span class="p">,</span> <span class="n">e</span><span class="p">))</span><span class="o">?</span><span class="p">;</span>
    <span class="nf">Ok</span><span class="p">(</span><span class="n">line</span><span class="p">)</span>
<span class="p">}</span></code></pre></figure>

<p>Changes needed to get this to work are:</p>

<ul>
  <li><code class="language-plaintext highlighter-rouge">Result&lt;String, String&gt;</code>: To show that the function is expected to possibly fail.</li>
  <li><code class="language-plaintext highlighter-rouge">.map_err(|e| format!("Failed to open file: {}", e))?</code>: To properly handle the case where the file cannot be opened.</li>
  <li><code class="language-plaintext highlighter-rouge">.map_err(|e| format!("Failed to read from file: {}", e))?</code>: To properly handle the case where the file cannot be read.</li>
  <li><code class="language-plaintext highlighter-rouge">Ok(line)</code>: The content of the file is wrapped in <code class="language-plaintext highlighter-rouge">Ok&lt;T&gt;</code>, indicating that it was read successfully.</li>
</ul>

<p>This example is trivial, but I hope it passes the message: Rust requires me to consciously decide how I want to handle the potential failure modes, even if I am not interested in doing that yet.</p>

<p>To be fair, <a href="https://doc.rust-lang.org/book/ch09-03-to-panic-or-not-to-panic.html#examples-prototype-code-and-tests">Rust does give some room via <code class="language-plaintext highlighter-rouge">unwrap</code> and <code class="language-plaintext highlighter-rouge">expect</code> to do prototyping work</a> without having to write detailed error-handling code immediately. Using <code class="language-plaintext highlighter-rouge">unwrap</code> and <code class="language-plaintext highlighter-rouge">expect</code> means you allow your program to stop execution by triggering a <code class="language-plaintext highlighter-rouge">panic!</code> if the code encounters an error. The <code class="language-plaintext highlighter-rouge">expect</code> method is similar to <code class="language-plaintext highlighter-rouge">unwrap</code>, except that it allows you to provide a custom error message when a <code class="language-plaintext highlighter-rouge">panic!</code> occurs.</p>

<p>Using <code class="language-plaintext highlighter-rouge">unwrap</code> will give code that looks something like:</p>

<figure class="highlight"><pre><code class="language-rust" data-lang="rust"><span class="k">fn</span> <span class="nf">read_first_line</span><span class="p">(</span><span class="n">filepath</span><span class="p">:</span> <span class="o">&amp;</span><span class="nb">str</span><span class="p">)</span> <span class="k">-&gt;</span> <span class="nb">String</span> <span class="p">{</span>
    <span class="k">let</span> <span class="n">file</span> <span class="o">=</span> <span class="nn">File</span><span class="p">::</span><span class="nf">open</span><span class="p">(</span><span class="n">filepath</span><span class="p">)</span><span class="nf">.unwrap</span><span class="p">();</span>

    <span class="k">let</span> <span class="k">mut</span> <span class="n">reader</span> <span class="o">=</span> <span class="nn">BufReader</span><span class="p">::</span><span class="nf">new</span><span class="p">(</span><span class="n">file</span><span class="p">);</span>
    <span class="k">let</span> <span class="k">mut</span> <span class="n">line</span> <span class="o">=</span> <span class="nn">String</span><span class="p">::</span><span class="nf">new</span><span class="p">();</span>
    <span class="n">reader</span><span class="nf">.read_line</span><span class="p">(</span><span class="o">&amp;</span><span class="k">mut</span> <span class="n">line</span><span class="p">)</span><span class="nf">.unwrap</span><span class="p">();</span>
    <span class="n">line</span>
<span class="p">}</span></code></pre></figure>

<p>The only changes here are the addition of <code class="language-plaintext highlighter-rouge">unwrap</code>s where necessary. As a beginner in the language, I found Rust’s approach to error handling surprising and tedious, so <code class="language-plaintext highlighter-rouge">unwrap</code> came in very handy for me. It helps with exploratory work, leaving error handling for later. The key point here is “leaving error handling for later”, meaning that it should be properly taken care of; <code class="language-plaintext highlighter-rouge">unwrap</code>s and <code class="language-plaintext highlighter-rouge">expect</code>s should not be left in the code.</p>

<p>I believe Rust’s error handling philosophy is great, and as I went further with the project, I would find cases where I was genuinely grateful I had handled the possible failure modes. So I am fully onboard with it, and I think it fits in nicely when looking to build robust software as a result.</p>

<h2 id="summary">Summary</h2>

<p>It took a while for me to come up with a title for this article. I was not quite sure what title would do justice to the information I was about to share, and to be honest, I am still not certain at this point. So I will give up on that and just get to the summary.</p>

<p>In this article, I wrote about three surprises I encountered while building <a href="https://github.com/deven96/ahnlich/tree/main">Ahnlich-ai</a>, the embedding service for <a href="https://ahnlich.tech/">Ahnlich</a>. The main points were:</p>

<ul>
  <li><strong>Varying Image Decoding Implementations</strong>: The approach to reading images may vary across languages and libraries. Be vigilant as this could result in pixel discrepancies and spread throughout your data pipeline.</li>
  <li><strong>Dip in Similarity Scores for Image-Text Data</strong>: There is a gap that tends to exist in the embedding space, visibly separating data from different modality types. If you experience low similarity scores between images and texts, that may just be the cause.</li>
  <li><strong>Importance of Model-Specific Preprocessing</strong>: Data is king, in its raw and processed form. Be meticulous about how you get to process data before feeding it into your model; it can have massive effects.</li>
</ul>

<p>I then included an extra point, talking about how I struggled to work with Rust’s error handling approach early on. If I sound like I no longer have issues with it, I’ll be kidding; that said, I like it. <a href="/working-on-ahnlich/#my-ask">This is the first of three articles</a>, and I hope you learned a thing or two from it. See you in the next one.</p>]]></content><author><name>Habeeb Shopeju</name><email>shopejuh@gmail.com</email></author><category term="ahnlich" /><summary type="html"><![CDATA[I learnt a couple of things while building Ahnlich-ai; in this article I distill some of them into concrete takeaways.]]></summary></entry><entry><title type="html">We are working on Ahnlich, a Database to Aid Semantic Search</title><link href="https://www.haksoat.com/working-on-ahnlich/" rel="alternate" type="text/html" title="We are working on Ahnlich, a Database to Aid Semantic Search" /><published>2024-12-21T00:00:00+01:00</published><updated>2024-12-21T01:20:02+01:00</updated><id>https://www.haksoat.com/working-on-ahnlich</id><content type="html" xml:base="https://www.haksoat.com/working-on-ahnlich/"><![CDATA[<p>Hello dear reader, my friends and I have been <a href="https://github.com/deven96/ahnlich">building an in-memory vector database</a>, which we are calling “Ahnlich”, <a href="https://en.wiktionary.org/wiki/%C3%A4hnlich">the German equivalent of the word “similar”</a>. Our goal is to give developers a means to easily integrate semantic search and key-value retrieval functionalities in their systems.</p>

<p>We have been working on Ahnlich for a significant part of this year, <a href="https://x.com/_deven96/status/1864366945916571978">recently doing an alpha release</a>. The core team currently consists of five contributors, doing a wide range of things such as building the database, working on the embedding service, working on demos via the Python client, etc.</p>

<p>The team is hoping that we can learn from the process of building this and create a suite of tools that can serve production use cases. The team also believes it will be more fun to collaborate with you if you could contribute to Ahnlich.</p>

<p>The purpose of this article is to tell you about this project, and I am hoping that one or all of the following happens at the end:</p>

<ul>
  <li>You feel inspired to contribute or use it in your side projects.</li>
  <li>You share the piece, and someone else feels inspired to contribute or use it in their side projects.</li>
  <li>You learn from the knowledge shared here.</li>
  <li>You are simply aware of its existence.</li>
</ul>

<p>Now let me get into the actual job of writing this article.</p>

<p>I will start by writing a bit on lexical search, which is the traditional way of doing information retrieval, then “semantic search” and “in-memory vector database”, two keywords I used earlier in this article, after which I will proceed to the rest of the piece. In other words, if you already know what they mean, you can skip to the “What is Ahnlich?” section.</p>

<p>Here is the outline:</p>

<ul>
  <li>What is Lexical Search?</li>
  <li>What is Semantic Search?</li>
  <li>What is an In-memory Database?</li>
  <li>What is Ahnlich?</li>
  <li>Why Build Ahnlich?</li>
  <li>What is Next?</li>
  <li>My Ask</li>
</ul>

<h2 id="what-is-lexical-search">What is Lexical Search?</h2>

<p>Before I talk about what semantic search is, I would briefly talk about what came before it: lexical search. Lexical search is the traditional way of finding relevant information, and this is not to say it is now outdated; it is still as essential today as it was years ago. However, semantic search complements it, significantly enhancing the quality of information retrieval systems.</p>

<p>A simple approach to preparing for lexical search is to create an index by doing the following on all documents with which you intend to make an index:</p>

<ul>
  <li>Tokenization: This means you split the document into individual terms. So if you have a document that says, “The lights are looking so beautiful this evening”, you split this into [“The”, “lights”, “are”, “looking”, “so”, “beautiful”, “this”, “evening”].</li>
  <li>Normalize the terms: There are various normalization approaches possible, but the common ones are lowercasing, <a href="https://stackoverflow.com/questions/1787110/what-is-the-difference-between-lemmatization-vs-stemming">lemmatization, or stemming</a> (depending on the context). Doing this means the tokenized values become [“the”, “light”, “be”, “look”, “so”, “beautiful”, “this”, “evening”].</li>
  <li>Build an inverted index: <a href="https://en.wikipedia.org/wiki/Inverted_index">An inverted index</a> is a data structure—commonly referred to as a posting list—that maps each unique word to the ID of the documents it appears in. This means you have something like: {“the”: [0], “light”: [0], “be”: [0], “look”: [0], “so”: [0], “beautiful”: [0], “this”: [0], “evening”: [0]}. An inverted index is often more complicated, but this explanation suffices.</li>
</ul>

<p><img src="https://res.cloudinary.com/haks/image/upload/v1734747525/HAKSOAT_Blog/working_ahnlich/index_workflow.png" alt="Index Workflow. Icons from Flaticon" /></p>

<p>A simple approach to doing lexical search at query time is to do the following:</p>

<ul>
  <li>Repeat the preprocessing done at index time on the query: This means that you repeat the first two steps from the indexing phase. If you have a query that says, “Are the lights on now?” you will end up with tokenized values like: [“be”, “the”, “light”, “on”, “now”]</li>
  <li>Run a relevance scoring algorithm on the index: There are many ways to calculate the relevance score; in this case, I will use the <a href="https://en.wikipedia.org/wiki/Boolean_model_of_information_retrieval">boolean model</a>, which just means I give a score of one to each document for each query term that appears in it. Following the example, the document with id 0 gets a score of 3 because [“be”, “the”, “light”] all appear in it.</li>
</ul>

<p><img src="https://res.cloudinary.com/haks/image/upload/v1734747525/HAKSOAT_Blog/working_ahnlich/query_workflow.png" alt="Query Workflow. Icons from Flaticon" /></p>

<p>Now, lexical search can be more complex than I described above. There are a lot of things that can be done to make it more robust, such as removing <a href="https://en.wikipedia.org/wiki/Stop_word">stop words</a>, using <a href="https://en.wikipedia.org/wiki/Okapi_BM25">Best Match 25 (BM25)</a> as the scoring algorithm, etc. However, the following explanation shows a challenge that lexical search approaches always face.</p>

<p>Consider two documents: “Kicking the round leather with friends improves mental health” and “Backstreet Boys are a music group.”</p>

<p><img src="https://res.cloudinary.com/haks/image/upload/v1734747024/HAKSOAT_Blog/working_ahnlich/index_workflow_example.png" alt="Indexing Workflow Example. Icons from Flaticon" /></p>

<p>After preprocessing, the documents will have something like the following:<br />
Document 0 - [“kick”, “the”, “round”, “leather”, “with”, “friend”, “improve”, “mental”, “health”]<br />
Document 1 - [“backstreet”, “boy”, “be”, “a”, “music”, “group”]</p>

<p>Then the inverted index will look like:</p>

<p>{“kick”: [0], “the”: [0], “round”: [0], “leather”: [0], “with”: [0], “friend”: [0], “improve”: [0], “mental”: [0], “health”: [0], “backstreet”: [1], “boy”: [1], “be”: [1], “a”: [1], “music”: [1], “group”: [1]}</p>

<p>Given a search query, “I am so happy that my boys and I will play football today; I am excited,” let’s process a retrieval request.</p>

<p><img src="https://res.cloudinary.com/haks/image/upload/v1734747025/HAKSOAT_Blog/working_ahnlich/query_workflow_example.png" alt="Indexing Workflow Example. Icons from Flaticon" /></p>

<p>The first step will be to tokenize the query, which gives:</p>

<p>[“i”, “be”, “so”, “happy”, “that”, “my”, “boy”, “and”, “i”, “will”, “play”, “football”, “today”, “i”, “be”, “excite”]</p>

<p>In this situation, none of the values in the query appear in document 0, while the values [“be”, “be”, “boy”] appear in document 1, leading to a score of 0 for the former and a score of 3 for the latter.</p>

<p>In essence, lexical search here says that document 1 is more relevant than document 0, but anyone with some understanding of the English language can see that document 0 is more relevant. There is a similarity between “round leather” and “football”, “I am so happy” and “improves mental health”, even if the words do not match.</p>

<p>Lexical search is fast, cost-efficient, and reasonably good at extracting relevant documents. However, it struggles with the absence of exact keywords.</p>

<p>If you want to learn more about the fundamentals of information retrieval, you can take the <a href="https://www.coursera.org/learn/text-retrieval">Text Retrieval and Search Engines course</a> on Coursera. Do note that it is quite theoretical, but I took it a couple of years ago, and I still find myself going back to <a href="https://haksoat.notion.site/Text-Retrieval-and-Search-Engines-Coursera-55ef43e370ec422a8c45e13eaad21103">some of my notes</a> every now and then. Really good stuff.</p>

<h2 id="what-is-semantic-search">What is Semantic Search?</h2>

<p>Next, I talk about semantic search. While lexical search is dependent on the presence of keywords, semantic search attempts to understand the meaning of text and use that understanding as a means of finding relevant documents.</p>

<p>Semantic search implementations can vary, but the most common approach is to rely on the <a href="https://en.wikipedia.org/wiki/Vector_space_model">vector space model</a> using dense vectors to convey meaning in text. These dense vectors, or embeddings as they are commonly called, are often gotten from transformer encoders, which “somehow” manage to convert text into numbers. Many articles on the internet do a better job of <a href="https://huggingface.co/learn/nlp-course/en/chapter1/4">explaining how transformer models work</a>, so you can get a thorough understanding of encoders using those resources.</p>

<p>Like in lexical search, there are also some preprocessing transforms used in semantic search. However, such transforms are considerably different from the kind you do in lexical search; they mainly help the models convert text to embeddings.</p>

<p>The gist with semantic search is that text embeddings contain contextual information, and it is useful enough to rely on the similarity between embeddings as a measure of relevance.</p>

<p>Going back to the earlier example, we had:</p>

<p>Query: “I am so happy that my boys and I will play football today; I am excited.”<br />
Document 0: “Kicking the round leather with friends improves mental health.”<br />
Document 1: “Backstreet Boys are a music group.”</p>

<p>Adding one more document that would also have had a zero score in lexical search,</p>

<p>Document 2: “The sun is up guys, we can have soccer sessions, woohoo!!!”</p>

<p>Using the <a href="https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2">sentence-transformers/all-MiniLM-L6-v2</a> as an embedding model, I get embeddings that look something like:</p>

<p>Query:<br />
[-0.01294223, -0.01123377, 0.00591772, -0.10435747, 0.03420463, …]</p>

<p>Document 0:<br />
[0.06874192, 0.1199687, 0.05535591, 0.0141326, -0.01607886, …]</p>

<p>Document 1:<br />
[-0.00164266, -0.058489, -0.01499688, -0.00426761, 0.00169406, …]</p>

<p>Document 2:<br />
[0.01470442, 0.03317017, 0.00964091, 0.03046494, 0.05122278, …]</p>

<p>Only the first 5 dimensions are printed, but the <a href="https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2">all-MiniLM-L6-v2 model</a> returns 384 embeddings. The numbers make no sense when you look at them, but if you visualize them, it makes more sense.</p>

<p><img src="https://res.cloudinary.com/haks/image/upload/v1734747351/HAKSOAT_Blog/working_ahnlich/tsne_embeddings_example.png" alt="Illustration of Embeddings. Created using Matplotlib." /></p>

<p>The illustration above visualizes the position of the query and documents in embedding space, where the edge labels are cosine similarity scores of the embeddings. Cosine similarity goes from -1 to 1, and the assumption is that documents with a score close to 1 are relevant.</p>

<p>The illustration shows that the embeddings are able to carry information about the context in text without a need for keyword dependence. In this case, Query is most relevant to Doc 2, with which it shares zero keywords, and least relevant to Doc 1, with which it shares the most number of keywords in the corpus.</p>

<p>NB: The embeddings were originally with 384 dimensions, but I reduced them to 2 dimensions <a href="https://www.datacamp.com/tutorial/introduction-t-sne">using t-SNE</a> to make it easier to visualize.</p>

<p>There is a lot more to semantic search than I have described in this section; the objective was to simply provide some context as to why it is considered an improvement on lexical search. Huggingface has a section on <a href="https://huggingface.co/learn/nlp-course/en/chapter5/6">Semantic search with FAISS</a> from their <a href="https://huggingface.co/learn/nlp-course/en/chapter0/1">NLP course</a> that does a better job of explaining the concepts than I have done in this section.</p>

<h2 id="what-is-an-in-memory-database">What is an In-memory Database?</h2>

<p>On-disk databases are quite popular, from PostgreSQL to MongoDB, but Ahnlich is taking the model of storing data in-memory instead. There are a couple of implications that come with this decision, and this section looks to cover them.</p>

<p>On the positive side (for in-memory):</p>

<ul>
  <li>The data is much faster to retrieve since expensive disk reads are not necessary for access. This implies lower latency for real-time use cases.</li>
  <li>Horizontal scaling is faster and less complex for in-memory databases when compared to disk-based databases.</li>
  <li>Concurrent requests can truly excel as they do not encounter the bottlenecks that occur when trying to read from disk.</li>
</ul>

<p>On the negative side (against in-memory):</p>

<ul>
  <li>The memory is more expensive than disk, so for a large index, running an in-memory database is costlier.</li>
  <li>Properly persisting an in-memory database requires deliberate effort, as disruptions to the running instance—such as crashes or restarts—can lead to data loss.</li>
  <li>If you are also storing some data in a main database, you need to manage the overhead that comes with keeping both in sync.</li>
</ul>

<p>Side Note: On the topic of speed, you can go through this Stack Exchange explanation of <a href="https://superuser.com/questions/1696557/what-in-the-hardware-makes-ram-faster-than-drive">why memory (RAM) is faster than storage</a> to learn more.</p>

<p>Given these implications, an in-memory database is an excellent choice when speed is a priority. Vector search is one such example, as it involves complex calculations and multiple steps where speed is critical. An in-memory database is also a good option to use when looking to lift the workload of data retrieval from the actual database, using the in-memory database as a cache such that the main database is only queried if there is <a href="https://hazelcast.com/foundations/caching/cache-miss/">a cache miss</a>.</p>

<p>Some examples of where this works:</p>

<p><strong>Analytics Software</strong>: If you are building an analytics software that often processes a lot of compute-heavy queries and has significantly more frequent reads than writes, you don’t want to run all queries directly against the database. You can store computed results from queries in an in-memory database, such that the results are pulled quickly from there if the same query comes in again, relieving the database of the workload.</p>

<p><strong>Recommendation Systems</strong>: If you are building a recommendation system and you have user embeddings and content embeddings. In this situation, you can keep the embeddings for the content in memory as well as the embeddings for active users; this way, you can compute content to show to the users without the latency that will come from disk reads.</p>

<p>There are many other <a href="https://www.gigaspaces.com/blog/in-memory-cache/">use cases</a> and <a href="https://www.prisma.io/dataguide/managing-databases/introduction-database-caching">approaches to using an in-memory database</a>, so you need to think about your context when deciding if and how to use one.</p>

<p>Now that I have given some context on semantic search and in-memory databases, let’s talk about Ahnlich.</p>

<h2 id="what-is-ahnlich">What is Ahnlich?</h2>

<p>Putting together the concepts of an in-memory database and vector search, Ahnlich is a suite of tools built to make it easy for developers to integrate semantic search functionalities in their applications. This is without having to do the amount of work needed to properly integrate semantic search, such as doing the preprocessing, postprocessing, and finding the most similar data points.</p>

<p>It is made up of a couple of components:</p>

<ul>
  <li>The Database</li>
  <li>The AI Service</li>
  <li>The CLI</li>
  <li>Language Clients: Rust and Python</li>
</ul>

<h3 id="the-database">The Database</h3>

<p>This is the part of Ahnlich that stores data; one can consider it to be the most integral part of the whole setup. The database is responsible for saving the data, and it also makes it possible to run the search queries. One can also use the database without having vectors, in which case data access will be via the metadata passed in at indexing time. With the metadata-only setup, Ahnlich would function similarly to Redis.</p>

<h3 id="the-ai-service">The AI Service</h3>

<p>Ahnlich’s AI service helps convert data into embeddings. The embeddings are expected to hold some form of meaning, such that one can make an assumption that two vectors that are close in the domain have similar meanings. The AI service leverages the <a href="https://github.com/pykeio/ort">ONNX runtime</a> and <a href="https://huggingface.co/docs/hub/en/index">Huggingface Hub</a> to facilitate the conversion of data from the multimodal format into embeddings. There are a couple of models available, from the popular <a href="https://huggingface.co/sentence-transformers">sentence transformers</a> AllMiniLM models for generating sentence embeddings, to the <a href="https://huggingface.co/docs/transformers/en/model_doc/clip">CLIP models</a> for image and text embeddings.</p>

<h3 id="the-cli">The CLI</h3>

<p>This is the part of Ahnlich that makes it possible to run queries from the terminal or command prompt. With the CLI service, you can easily create an index, run test queries, and look into your setup without requiring an actual language client. The CLI can also be an avenue to learn more about the various features offered by Ahnlich and perform administrative tasks, all this without having to write any code. However, if you want to use Ahnlich within code, you should use the language clients.</p>

<h3 id="language-clients-rust-and-python">Language Clients: Rust and Python</h3>

<p>The Language Clients serve as a window through which you can access the database and AI service as you would via the CLI, but more natively, through the language of your choice. The language clients that Ahnlich currently provides are Rust and Python; however, there are plans to make it accessible in more languages so it can be used across various language stacks.</p>

<h2 id="why-build-ahnlich">Why Build Ahnlich?</h2>

<p>Ahnlich is not the first technology that exists to provide semantic search functionality. A lot of tools exist; some are <a href="https://en.wikipedia.org/wiki/Vector_database#Implementations">specifically built to serve vector search use cases</a>, and <a href="https://searchanise.io/blog/3-most-popular-search-engine-technologies-in-2020/">some provide great lexical search abilities</a> to go with vector search (an approach referred to as hybrid search).</p>

<p>So why build Ahnlich if something exists?</p>

<p>I have a couple of answers:</p>

<ul>
  <li>Curiosity and Learning</li>
  <li>Providing Model Integration</li>
  <li>Obsessed with Better</li>
</ul>

<h3 id="curiosity-and-learning">Curiosity and Learning</h3>

<p>What does one need to know to build a vector database? What constraints are involved in building one? What languages are best suited?</p>

<p>These are some of the questions serving as internal motivating factors for us to get involved in building Ahnlich. Considering that none of us has built something of this kind before, it also served as a means to learn whatever was needed to achieve it. For me personally, I was looking to get involved in a team doing Rust stuff at work. I had also been doing some vector database work, so it was a good opportunity to learn something cool and also look deeper into the inner workings of the tech I use.</p>

<h3 id="providing-model-integration">Providing Model Integration</h3>

<p>Many vector databases are simply a means of storing embeddings; this means you as a user will have to find your own way to get the embeddings. You can either get the embeddings via third-party providers who expose APIs to their models or by <a href="https://huggingface.co/spaces/mteb/leaderboard">self-hosting your models</a>. In the case of Ahnlich, we wanted to make it possible for users who want to stick to on-device models, i.e., self-hosting, without having to do the work of setting up inference. Hence, one of the reasons Ahlich is a suite of tools, not just a database.</p>

<h3 id="obsessed-with-better">Obsessed with Better</h3>

<p>This is more of a hope, but we are wondering what we can do better in terms of user experience when working with vector databases. In order to do this, we will need to get concrete feedback from users, which can be you. So we need you to use Ahnlich in your side projects and give us feedback on how you want it to be improved upon. As we get to work on the project into the next year, there will be a lot of use cases coming up, and we will be able to work on those and provide a better experience.</p>

<h2 id="what-is-next">What is Next?</h2>

<p>There are a couple of things we are looking to do now that we are done with the initial alpha release. Doing everything on this list does not mean the project is done; it just means it will be one step in the direction we want to go.</p>

<ul>
  <li><strong>Make it production ready</strong>: Ahnlich currently works, but it is not where we want it to be in terms of stability. Improving the error logs, testing it at a larger scale, optimizing the slow parts that we notice after profiling, etc. Getting these changes in will gradually move us towards a point where we can be confident that Ahnlich is ready to be used for production use cases.</li>
  <li><strong>Provide a more Pythonic interface</strong>: Python is a very popular language, so it won’t be surprising if Python becomes the most common Ahnlich client. The challenge with the client is that we use <a href="https://docs.rs/serde-generate/latest/serde_generate/">serde_generate</a> to compile it from Rust, but this is not outputting Pythonic code. Hence, the experience is not the most suitable for Python developers. We need to write a Python wrapper that helps us achieve this objective, where the wrapper’s main job is to give users the Pythonic feel, and we don’t write functionality into the wrapper. We intend to use gRPC to achieve this.</li>
  <li><strong>Support a broader range of multimodal data</strong>: Images and text are the only kinds of data for which we support conversion into embeddings. However, there are many other kinds of multimodal use cases that we would like to cover, such as audio, video, or even stuff like time series data.</li>
</ul>

<h2 id="my-ask">My Ask</h2>

<p>The original purpose of me writing this piece was to share what I have been working on for the last couple of months and also share some of the things I learned while working on it. This is similar to how I <a href="/learning-stock-trading-python/">shared my learnings from working on a trading system sometime last year</a>, even though I did not get to write all the articles I hoped to write.</p>

<p>This time around, I will be writing only three articles about my learnings, and I hope I have the bandwidth to do it this time. The titles will be something in the line of:</p>

<ul>
  <li>How I Built an Embedding Service in Rust</li>
  <li><a href="/ahnlich-ai-embedding-service-surprises/">Building An Embedding Service: Sharing My Three Surprises</a></li>
  <li>How to Debug your Embeddings</li>
</ul>

<p>I will also be asking for two favors; my friends and I would appreciate it if you:</p>

<ul>
  <li>Help <a href="https://github.com/deven96/ahnlich">give us a star on Github</a>.</li>
  <li>Spend some time using Ahnlich in your side projects (it will be a slight deviation from what you already use, I know, I know), but your feedback will help us see what we have done well or wrongly. Any kind of feedback will be appreciated, from using it in an actual project to raising an issue on a bug you experience.</li>
</ul>

<p>If you have read up till this point, thank you very much. Now I have to go and write the articles I have made a commitment to put into the world.</p>]]></content><author><name>Habeeb Shopeju</name><email>shopejuh@gmail.com</email></author><category term="ahnlich" /><summary type="html"><![CDATA[Ahnlich is a suite of tools that help make semantic search possible. This article explains the what, why and what nexts of the project.]]></summary></entry><entry><title type="html">10 Principles that Guide My Work as a Machine Learning Engineer</title><link href="https://www.haksoat.com/principles-machine-learning-engineer/" rel="alternate" type="text/html" title="10 Principles that Guide My Work as a Machine Learning Engineer" /><published>2024-12-09T00:00:00+01:00</published><updated>2024-12-09T00:00:00+01:00</updated><id>https://www.haksoat.com/principles-machine-learning-engineer</id><content type="html" xml:base="https://www.haksoat.com/principles-machine-learning-engineer/"><![CDATA[<p>Hello, dear reader; it has been seven months since my last article on <a href="/why-log-returns/">Why Log Returns</a>. This time, I am doing some introspection on guiding principles that have helped me grow as a machine learning engineer. Such introspections will usually rot in my private notes, but I hope there will be some value in sharing this time. Many of these ideas originate from others through their writeups and speeches, and I am immensely grateful for their willingness to share.</p>

<p><img src="https://res.cloudinary.com/haks/image/upload/v1734828463/HAKSOAT_Blog/guiding-principles-ml/isaac-newton-quote.jpg" alt="Isaac Newton Quote" /></p>

<p>In no specific order, the principles are:</p>

<ul>
  <li>Embrace Checklists</li>
  <li>F*ck and Unf*ck</li>
  <li>Acknowledge Alternatives</li>
  <li>Communicate Often</li>
  <li>Observe and Document</li>
  <li>One Change at a Time</li>
  <li>Embrace Checkpoints</li>
  <li>Be Generous</li>
  <li>Know the Data and Its Transforms</li>
  <li>Embrace Constraints</li>
</ul>

<p>Before diving in, I would like to point out that a more fitting title for this article would have been something like “Some Principles that Guide My Work as a Machine Learning Engineer,” but that did not sound as catchy to me. As I will expand on later in this article, placing a constraint of ten also helped me approach this piece with a clearer mind.</p>

<h2 id="embrace-checklists">Embrace Checklists</h2>

<p><a href="https://en.wikipedia.org/wiki/Checklist">Wikipedia defines a checklist</a> as a type of job aid used in repetitive tasks to reduce failure by compensating for potential limits of human memory and attention. I think that is a great way to put it, especially the bit about compensating for limits of human memory and attention.</p>

<p>Machine learning engineering is a very iterative endeavour, so there are many cases where new tasks pop up as you do the work. For example, if the model doesn’t perform well, you may need to try a different feature engineering or modelling approach. As a result, you may need to update some other part of the system to align with that change, and such modifications are easy to forget.</p>

<p>There was a time when I did not regard checklists highly. What used to happen was that I would remember that some change was necessary, but then something else would pop up, after which I would completely forget to make the change. The reminders would often come at the least desirable times, such as when something crashed or the data pipeline got corrupted.</p>

<p>The story is much different now. I have a checklist for almost everything, whether technical or non-technical. A checklist is very beneficial because it is a tool for keeping track of what I need to do. Before I can say that a task is done, I go through the list and ensure everything is checked or make the conscious decision—acknowledging potential consequences, too—not to do one of the items.</p>

<p>Here is a screenshot of one of my checklists when working on Ahnlich.</p>

<p><img src="https://res.cloudinary.com/haks/image/upload/v1734828632/HAKSOAT_Blog/guiding-principles-ml/checklist-screenshot.png" alt="Screenshot of my checklist." /></p>

<p>My approach to creating a checklist is to define my approach to achieving the task; then, I make the requisite actions or desired attributes of the end goal into entries on the list. If you look at the list sample above, you will see that the list is also nested; this is because I think about the actions necessary for each action until I don’t feel any uneasiness about how to accomplish an item.</p>

<p>That leads to another benefit of using checklists: it exposes my lack of clarity about achieving a task more concretely. My inability to create a checklist often indicates that I need a clearer picture of accomplishing a task. Since I have it written, not just fuzzy in my head, I feel the freedom to ask questions, seek contributions from colleagues, and do the necessary research to get me to the point of more comfort and clarity.</p>

<p>In <a href="https://jamesclear.com/great-speeches/creative-thinking-by-claude-shannon">Claude Shannon’s speech on Creative Thinking</a>, he said: “Suppose you have your problem here and a solution here. You may have too big a jump to take. What you can try to do is to break down that jump into a large number of small jumps.”</p>

<p>The Checklist is my tool for achieving this.</p>

<h2 id="fck-and-unfck">F*ck and Unf*ck</h2>

<p>Sorry to have swear words in this article already. This idea is something I picked up from Tim Ferriss’s book <a href="https://www.amazon.co.uk/Tools-Titans-Billionaires-World-Class-Performers/dp/B082VKL6VC">Tools of Titans</a>. Sadly, I don’t remember which of the guests said it, but it goes something like:</p>

<p>When writing a piece, I am not scared of putting swear words in there or having the first version look like an eyesore. The objective is to ensure that the piece exists, i.e., f*cking my way to completion, after which I must unf*ck it and get it in the best version possible. The work is not done until I am done unf*cking the piece.</p>

<p>I messed up the narration, but I will do a proper attribution when I re-read the book (which should be soon).</p>

<p>The concept of f*ck and unf*ck flows nicely from that of using checklists; it is a nice tool for when a checklist doesn’t cut it. <a href="https://en.wikipedia.org/wiki/Law_of_the_instrument">As Abraham Maslow wrote in 1966</a>, “It is tempting, if the only tool you have is a hammer, to treat everything as if it were a nail.”</p>

<p>Machine learning engineering often involves moving in the dark, sometimes with many unanswered questions, knowledge gaps, and little clarity. When this happens, there will usually be a more generic next step, and you must work your way to precision via action and trying things out. Let’s say you need to deploy a model in a new environment, and you don’t know the platform-specific terminologies or where the tooling is, and there is a bunch of documentation to go through.</p>

<p>F*ck in this situation would be akin to doing some of the following:</p>

<ul>
  <li>skimming through the docs for the most relevant instructions</li>
  <li>using default configurations</li>
  <li>finding a template either from the docs or another codebase to gain more understanding</li>
  <li>iteratively modifying things till it works</li>
</ul>

<p>Unf*ck in this situation would be akin to doing some of the following:</p>

<ul>
  <li>using the setup that works as a guide to finding more specific parts of the docs</li>
  <li>understanding what the default configurations mean and fitting them to the current task</li>
  <li>asking more concrete questions from knowledgeable engineers</li>
  <li>testing that it not only works but works as expected, is resource efficient and secure</li>
</ul>

<p>F*ck and unf*ck is about opening up to a lot less structure at the start to gain momentum and an initial win, then applying discipline after to get the work to shine. It pushes me to get things to work, knowing that the software is far from finished. After this, I work backwards, cleaning up and optimising things to ensure they are properly done. I must admit that there is a tendency not to unf*ck things due to tight timelines or laziness; it often takes a disdain for mediocre work and some discipline to overcome that inclination.</p>

<h2 id="acknowledge-alternatives">Acknowledge Alternatives</h2>

<p>Many mental models, from the <a href="https://fs.blog/the-psychology-of-risk-and-reward/">risk-reward framework</a> to the <a href="https://en.wikipedia.org/wiki/Opportunity_cost">opportunity cost model</a>, have the concept of alternatives at their core. There is a centuries-old proverb that goes, “There is more than one way to skin a cat.” If I were to extend this, I would say, “But some ways are better than others.”</p>

<p>When faced with a situation, there is a tendency to go with what first comes to mind instead of thinking for slightly longer and choosing a better fit. This inclination applies both to problems—there can be value in redefining them or choosing a different one—and to solutions. The cost of not taking some time to think about this and making the wrong choice is that path dependence may come into play; invested resources may not yield desirable outcomes. That you think of alternatives does not eliminate making a less optimal decision, but at least you tried.</p>

<p>I often try to get my teammates involved in deciding between alternatives. As for problems, this can help me quickly find out if a problem is worth solving in the first place, if someone has already solved it, or if I am thinking of it the wrong way. As for solutions, researching the right one for the scenario and getting frequent feedback from my team on things like design or library choices can be invaluable.</p>

<p>Acknowledging alternatives can have a downside. You do not want to consider the tens or hundreds of options available for all situations, as this will quickly lead to <a href="https://thedecisionlab.com/biases/decision-fatigue">decision fatigue</a>. At a deeper level, thinking of alternatives comes down to developing awareness that makes one mindful enough to take a step back and gain a better view of the situation and its possible approaches.</p>

<h2 id="communicate-often">Communicate Often</h2>

<p>There are hundreds of pages on the internet discussing communication, but I still had to include it in this article. The key point here is that it is not just about communicating but doing it often, not only from the angle of telling but also from asking and seeking updates. An engineer needs to be involved in the push-pull process of information flow.</p>

<p>The importance of communication in a complex project cannot be overemphasised; it is usually the primary means through which contributors understand what is going on. Every engineering task builds on the knowledge of the project’s state, so when things change, those developments must be known to avoid efforts in the wrong direction. When I say “things change” here, it could vary from the approach to a problem needing to differ from what was initially discussed to the problem no longer requiring a solution. If a change impacts someone else’s work or perception of the work, it should be communicated.</p>

<p>The most infuriating times for me are when I am working and thinking based on stale knowledge; something has changed, and someone has not passed that information on. I also feel very uncomfortable when there is a new development and my colleagues do not know about it yet.</p>

<p>I like to use various approaches to share information, such as messaging the affected individuals via private chat, shared channels, or setting up a call; the choice depends on the scenario. I also find that standups enable communication. My issue with relying on standups mainly to transmit information is that they are not always daily; you should not wait days to say what you need to say. Also, standups are often team-based and may only cater to some of the colleagues that you work with; others may be on a different team or even in a different organisation.</p>

<h2 id="observe-and-document">Observe and Document</h2>

<p>Observation is a crucial skill for scientists and engineers; it serves as a foundation for many other activities, such as asking questions, seeking improvement, learning from others, and coming up with new ideas.</p>

<p>Reading—more like listening to, I do audiobooks—<a href="https://www.amazon.co.uk/Innovators-DNA-Updated-New-Introduction/dp/1633697207">The Innovator’s DNA: Mastering the Five Skills of Disruptive Innovators</a> made this sink in further. I have become more mindful about observing what is happening during calls, on projects and within my teams. I often look closely to get a good picture of the processes that make things work, how engineers who inspire me do their work, and the philosophy (the why) behind various decisions.</p>

<p>It is easier to spot interesting things when you have some expectation of the entity being observed. For example, if a pricing model is being trained and you expect to see a linear regression model but find that a decision tree is being used. That makes you go: “oh, but why?”, but if you do not even know what it means to train a model model, you would likely not be able to make that observation. When expectations do not exist, it is still possible to observe, but it will be from the perspective of learning alone.</p>

<p>As for documenting things, writing, be it actual notes, short points, or sketches, is incredibly beneficial. While I have a good memory, I often forget things I do not expect to forget. Writing things down ensures I have something to return to without panicking when that happens. Documenting things has benefited me in so many ways, but one of my favourite benefits is that it makes it easy for me to do some retrospection. For example, if I want to think of ways to improve a system or process, it is easier to have a document containing my observations and start from there.</p>

<p><img src="https://res.cloudinary.com/haks/image/upload/v1734828463/HAKSOAT_Blog/guiding-principles-ml/chinese-proverb-ink-memory.png" alt="Chinese Proverb on memory" /></p>

<p>Why do I have “observe and document” as one point?</p>

<p>The issue with observing is that it is often a passive activity. It is hard to do, especially when your mind is yet to be fully engaged with the item to be observed. This is where writing comes in. In the process of putting things down, my false assumptions or expectations jump at me. Many times, when I am documenting a process, I see myself going, “Oh, this is surprising,” which ends up being an observation.</p>

<p>So which comes first, the observation or the documentation?</p>

<p>My answer is that it depends: If I am able to start observing without writing anything down at the start, I then go ahead and write down the things I notice. If I am unable to do this, perhaps because of a lack of full attention, I simply start writing things down, and then observation follows.</p>

<h2 id="one-change-at-a-time">One Change at a Time</h2>

<p>I believe every machine learning engineer will learn the concept of changing one thing at a time, either from experience or through a resource—as you will in some minutes if you did not know of it previously. My first encounter with this idea in writing was through the book <a href="https://www.amazon.co.uk/Debugging-Indispensable-Software-Hardware-Problems/dp/0814474578">9 Rules of Debugging</a>, and it has stuck ever since. The principle is pretty simple: change one thing, then test to see if it works or how it works.</p>

<p><img src="https://res.cloudinary.com/haks/image/upload/v1734828463/HAKSOAT_Blog/guiding-principles-ml/rules-for-debugging.png" alt="Agans' Rules for Debugging" /></p>

<p>When debugging, some scenarios require changing various parts of your code to see if they will fix the error or reveal the root cause. The idea with changing one thing at a time in this context is that you should be able to tell the effects of your changes, especially concerning getting a fix in. Contrast testing one change at a time (reverting if it does not help) with testing only after making five changes (none of those changes helps fix the issue); you will find out that the latter messes things up quite quickly.</p>

<p>During the implementation of machine learning algorithms is another context where one change at a time helps a lot. <a href="https://www.youtube.com/live/mEakLXuCLB8">Machine Learning algorithms are notorious for having silent failures</a>, so the code does not break, but the outputs are wrong and you can’t say why unless you dig deep and try to understand the data. Making one change at a time and looking into the results helps you understand the data flows much better. If you do not make iterative changes, it gets harder to tell if the results are correct.</p>

<p>In a slightly different context, imagine you have an existing model and want to improve it. The recommended approach is to change one variable in the model or training process and then evaluate the model to see how it performs in response to your modifications.</p>

<p>If you really really know what you are doing, it may be okay not to stick to the one-change-at-a-time principle. However, you should know that you may be shooting yourself in the foot.</p>

<h2 id="embrace-checkpoints">Embrace Checkpoints</h2>

<p>As a machine learning engineer, I have run quite a number of scripts that take days to complete. Hence, I can tell from experience that “<a href="https://en.wikipedia.org/wiki/Murphy%27s_law">Anything that can go wrong will go wrong.</a>” There are so many reasons why a script can go off the rails: a wrong transformation, a terminated Linux process, wrong configurations, connectivity issues, files being corrupted, models starting to overfit, etc.</p>

<p>There are various ways to limit the impact of such unpleasant surprises, but having checkpoints at different points in the data transformation pipeline is my favourite. Doing this comes with various benefits, such as resuming processes from the last stable state and using saved outputs for analysis and debugging if something seems off.</p>

<p>The approach to checkpointing will depend on the context; some tasks will have checkpointing functionality that is easily accessible, while others will require you to write more substantial amounts of code. For example, when training a model, PyTorch makes it easy to set up checkpointing of model weights, but writing a custom data processing script may require you to handle checkpointing yourself. Remember to clean up the checkpoints when they no longer provide any value, keeping them around as the files can add up quickly and consume a lot of storage.</p>

<p>Sometimes, I feel lazy; I want to get the process running and be on my way, having to think about checkpoints. In many cases, being lazy in such a manner has come back to bite me in the butt. Now, I simply set up checkpointing and give myself peace of mind, knowing that I do not have to start afresh if something goes wrong.</p>

<h2 id="be-generous">Be Generous</h2>

<p>I was not sure what to call this section, but “Be Generous” seems to do the job. This is a phrase I learned from the book <a href="https://www.amazon.co.uk/Never-Eat-Alone-Relationship-Portfolio/dp/0241004950">Never Eat Alone</a>. However, I would like to think that the mindset is one that I already had and lived by way before reading the book—there is something awesome about being able to put a word to something.</p>

<p>There is only a little to say about this besides what it says. Do not just be fixated on yourself and getting your tickets done. There is value in raising your head to see who needs some assistance or trying to understand how you can provide value to someone, which does not exactly come down to closing tickets. I have some time in the week dedicated to doing this, looking around to see what others are up to and thinking about how I can help.</p>

<p>There is a social side to this, in that you build a better connection with the person and also get fulfilment from them achieving their goal with some contribution from you. I cannot speak for others, but I feel very good when I remember times when I offered to help understand an issue someone was facing, and we came up with a fix. In many cases, it turns out to be a basis for building that relationship.</p>

<p>There is also a development side to this: you get to see what others are working on and can learn from getting involved or even just thinking about a diverse set of challenges. Often, I find myself learning about a new technology, pushing to understand certain concepts better, and revising the fundamentals simply by trying to help.</p>

<p>Being generous does not have to be down to writing code alone or fixing bug issues alone; it also includes things like:</p>

<ul>
  <li>volunteering at conferences</li>
  <li>offering career advice when a friend feels stuck</li>
  <li>giving talks</li>
  <li>sharing lessons and experiences</li>
  <li>writing articles</li>
  <li>referring people you have confidence in</li>
  <li>reviewing people’s documents or write ups</li>
</ul>

<p>I would like to mention that being generous does not include stretching yourself too thin so that you are unable to do the things that are important to you well. Do what you can, and that suffices; it is not an obligation.</p>

<h2 id="know-the-data-and-its-transforms">Know the Data and Its Transforms</h2>

<p>As a machine learning engineer, you will often be the one with knowledge of how the system works end to end. This often means knowing how the data:</p>

<ul>
  <li>gets into the data store</li>
  <li>gets pulled out and is transformed into features</li>
  <li>gets used to train and evaluate the model</li>
  <li>is being processed before and after inference</li>
  <li>is being utilised for monitoring purposes</li>
</ul>

<p>Hence, it is essential to understand the nature of the data. One way to go about this is to spend some time combing through the data, making generalisations about its attributes and what it should look like. You can also use descriptive statistics to get a sense of the data, its main features, variability, distribution, outliers, etc. The benefit of having this kind of feel for the data is that you can have some intuition about whether the data is off based on the business context.</p>

<p>The same idea applies to knowing the transforms the data passes through. When working on a project that spans multiple teams, it is not uncommon to find duplicate transforms or even erroneous ones at various points of the pipeline. Knowing the transforms also makes it possible to collaborate fruitfully with the scientists. You will be in a good place to spot expensive transforms that need optimisation or are impossible to integrate due to various system constraints.</p>

<p>I once worked on a project, specifically on the data pipelines side of things. At a certain section it was fine to have duplicates—based on the id—in which case we would drop them, keeping only one copy and everything else happens as usual. However, in this scenario I observed more duplicates than usual, tracked it back to potential sources that looked suspect and thought of possible solutions to the issues I found. I raised the question with the scientist I was collaborating with who then checked as well, concurred with my findings and went with one of the suggested solutions. The code did not break and it was going to work as usual, but if I did not understand the data, it would have been nearly impossible to observe that something was wrong.</p>

<h2 id="embrace-constraints">Embrace Constraints</h2>

<p>At the start of this piece, I mentioned needing to constrain the number of points I would write about to get myself to do the work. So here is point ten: embrace constraints.</p>

<p>In a world that puts endless options in our faces, one can easily lose the structure that is beneficial for doing great work. It is said that <a href="https://buffer.com/resources/7-examples-of-how-creative-constraints-can-lead-to-amazing-work/">constraints help increase creativity</a>, so I am in the camp that preaches that we should actively pursue constraints. Life in itself has constraints; you can’t live forever, you can’t have infinite money, and you can’t work on all projects. Hence, if you are doing a project or task without constraints, you should look deeper, and you will find them; if you don’t find any, make one.</p>

<p><img src="https://cdn2.miragestudio7.com/wp-content/uploads/2018/11/frank-gehry-architect-architecture-quotes-16.jpg" alt="Frank Gehry, iconic architect on constraints" /></p>

<p>There is a thin line between constraints being of positive or negative value. Constraints should be questioned and pushed against periodically, not just accepted or inherited without any context, enough of being philosophical and back to machine learning talk.</p>

<p>One constraint that will likely piss you off in machine learning—especially if you have an engineering background—is that the predictions will not always be correct, and the generated artefacts can suck on some inputs. I struggled with this at the start of learning the fundamentals, and I had to accept it as part of the nature of machine learning algorithms. Instead of shying away, I made room for such failures in the machine learning systems I built.</p>

<p>Another constraint is that the super cool models require heavy computing resources. Social media might be buzzing with how this model is the best thing since sliced bread. You then try to run it on 100,000 documents only to find it may take a week to complete. Then you realise that machine learning is expensive, and you need to make a trade-off between the time and cost to run.</p>

<p>I can go on and on about the various constraints in the field, but my point here is that constraints should not cause you to give up. Instead, you should find a way to balance things out and make it work. It is also important to communicate the constraints with the necessary stakeholders in the project so everybody is on the same page.</p>

<h2 id="conclusion">Conclusion</h2>

<p>In this article, I wrote about some principles that have guided my machine learning engineering career. I intend to improve at applying them while picking up other beneficial principles as I learn and grow. Every single point on this list has been useful to me, from embracing checklists to embracing constraints. No, they are not easy to adopt; it takes time and conscious application.</p>

<p>This article was difficult to write, but I hope it was much easier to read and that I could clearly communicate my thoughts. Thank you for reading some or all of it. It is my wish that you find these tips beneficial in your life and career or, at the very least, become aware of them and start becoming more mindful.</p>

<p>I will now go ahead and write a couple more pieces. They are about my contributions to <a href="https://github.com/deven96/ahnlich">Ahnlich</a>, an in-memory vector database written in Rust, which <a href="https://x.com/_deven96/status/1864366945916571978">some friends and I worked on this year</a>. I picked up the language to help build it, and it was a great experience.</p>

<p>See you there.</p>]]></content><author><name>Habeeb Shopeju</name><email>shopejuh@gmail.com</email></author><category term="career" /><summary type="html"><![CDATA[Knowing the data and its transformations is a principle that has significantly helped my work as a Machine Learning Engineer. This article examines the importance of understanding the nuances of one's data and covers nine other valuable principles.]]></summary></entry><entry><title type="html">Why Log Returns?</title><link href="https://www.haksoat.com/why-log-returns/" rel="alternate" type="text/html" title="Why Log Returns?" /><published>2024-04-30T00:00:00+01:00</published><updated>2024-04-30T00:00:00+01:00</updated><id>https://www.haksoat.com/why-log-returns</id><content type="html" xml:base="https://www.haksoat.com/why-log-returns/"><![CDATA[<p>I have been reading a couple of books on investments lately and I noticed the common use of log returns. 
It seems to be a standard and I did not understand why that was the case. I had this itch to know why, so I did some extra digging to find the purpose that log returns serve and I thought to write about it for the following reasons:</p>

<ol>
  <li>To serve as a future reference for myself, when I forget this bit of the fundamentals</li>
  <li>To get myself to truly understand it and potentially apply this knowledge to novel situations</li>
  <li>To attempt providing an answer to someone (maybe you), that has the burning question “Why log returns?”</li>
</ol>

<p>Before going in to explain the various concepts, I will like to provide a trivial scenario that will serve as the basis for the breakdown to come. So if at some point, something does not make sense, you can refer to this scenario and hopefully it helps clarify things.</p>

<blockquote>
  <p>A certain investor has \$40,000 (\$40k) and is looking to invest in two stocks, ACO and BCO.</p>

  <p>This investor decides to put in:</p>

  <p>\$30k ⇒ ACO</p>

  <p>\$10k ⇒ BCO</p>

  <p>As at the time when the purchase is made, the prices in dollars are:</p>

  <p>ACO ⇒ 20</p>

  <p>BCO ⇒ 50</p>

  <p>Here are the prices in dollars for the stocks at the end of each month for three months:</p>

  <p>ACO: 21, 24, 22</p>

  <p>BCO: 55, 27.5, 55</p>

  <p>Here are the values of the investments at the end of each month for three months:</p>

  <p>ACO: \$31.5k, \$36k, \$33k</p>

  <p>BCO: \$11k, \$5.5k, \$11k</p>
</blockquote>

<p>Given this context, I will proceed with the article. If you are looking for just information about log returns, you can just go to the <a href="#calculating-log-returns">log returns section</a>.</p>

<h2 id="calculating-dollar-returns">Calculating Dollar Returns</h2>

<p><a href="https://learn.saylor.org/mod/book/view.php?id=53734&amp;chapterid=37840">Dollar returns</a> are very easy to calculate. You simply subtract the old value of the investment from the new value of the investment.</p>

\[\text{return} = \text{new_value} - \text{old_value}\]

<p>This means that the investment on:</p>

<p>ACO goes from \$30k to \$31.5k, giving a positive return of \$1500 (profit).</p>

<p>BCO goes from \$10k to \$11k, giving a positive return of \$1000 (profit).</p>

<p>The dollar return is pretty easy to calculate and intuitive. However, if one is to ask the question: “looking at the dollar returns, which is the most profitable?” Given the picture of just dollar returns alone, the answer is ACO. 
However, when you consider the amount invested, this conclusion is misleading. The reason is, the amounts put into the various investments differ. If you were to put in the same \$30k investment into BCO, it would get to \$33k, giving a positive return of \$3000.</p>

<p>Dollar returns can tell you what the gains or losses are, but you need to know the amount of the original investment to get the full story. This shows why simply calculating the dollar returns is limited and does not provide a means to compare returns fairly across various investments, especially when the invested amount differs. This leads us into simple returns.</p>

<h2 id="calculating-simple-returns">Calculating Simple Returns</h2>

<p>Simple returns can be viewed from two perspectives: percentage and ratio. Both do not require the extra context of the invested amount that dollar returns requires.</p>

<p>Percentage return is calculated by subtracting the old value from the new value then dividing by the old value.</p>

\[\text{simple_return(percentage)} = \frac{\text{new_value} - \text{old_value}}{\text{old_value}}\]

<p>So in the first month, ACO increases by 5%, BCO increases by 10%. With these values, you do not need to know how much was invested, to know which investment had better returns.</p>

<p>If one is to ask another question, “given the prices of BCO across three months, <code class="language-plaintext highlighter-rouge">55, 27.5, 55</code> after a starting price of 50 and having a simple return (percentage) of <code class="language-plaintext highlighter-rouge">10%, -50%, 100%</code>, what is the compound return after three months?”.</p>

<p>Getting the compound return involves multiplying the simple returns, this is because the returns of month 1 influence month 2, the returns of month 1 and 2 influence month 3. If we are to calculate this using simple return (percentage), you will get misleading results.</p>

<p>Here are two reasons:</p>

<ol>
  <li>Percentages can be negative, a single negative will mean the final compound return will be a negative value even if every other return is positive. <code class="language-plaintext highlighter-rouge">10% * -50% * 100%</code> gives <code class="language-plaintext highlighter-rouge">-5%</code> . One negative should not mean that the entire return is negative.</li>
  <li>Percentages are fractions and are commonly in the 0% to 100% range so they are centred around 0, this means that they give lesser values when multiplied. So in the example above, even if the values were <code class="language-plaintext highlighter-rouge">10% * 50% * 100%</code> (note that the middle figure was made positive), the value gives <code class="language-plaintext highlighter-rouge">5%</code> . The compound return should not be having a value that is way less than the individual returns.</li>
</ol>

<p><strong><em>Enter simple return (ratio)…</em></strong></p>

<p>The simple return (ratio) is very similar to simple return (percentage), with a slight difference in the numerator as seen below:</p>

\[\text{simple_return(ratio)} = \frac{\text{new_value}}{\text{old_value}}\]

<p>It also has a relationship with simple return (percentage), meaning that it is possible to simply switch when necessary:</p>

\[\text{simple_return(percentage)} + 1 = \text{simple_return(ratio)}\]

<p>Given this formula above, the addition of 1 to simple return (percentage), makes all of the difference and fixes the two issues raised with percentages.</p>

<ol>
  <li>By converting percentage to ratio (adding 1 to the percentage), the values will always be positive. Yes, -200% is a theoretically possible value, such that you get -2+1=-1 which is a negative value, but in the domain of stocks, the worst that can happen to a stock’s value is that it drops to by 100%. But I digress, the values <code class="language-plaintext highlighter-rouge">10%, -50%, 100%</code>, become <code class="language-plaintext highlighter-rouge">1.1, 0.5, 2</code>.</li>
  <li>Since the values are now centred around 1, a profit amplifies the compound return and a loss diminishes it. Going by the values <code class="language-plaintext highlighter-rouge">1.1, 0.5, 2</code>, the compound return becomes: <code class="language-plaintext highlighter-rouge">1.1</code>, converting this ratio to percentage, we get <code class="language-plaintext highlighter-rouge">1.1 - 1</code> which gives <code class="language-plaintext highlighter-rouge">0.1</code> meaning <code class="language-plaintext highlighter-rouge">10%.</code> Compare this to the calculation using percentages, where we even assumed that the 50% loss was a <code class="language-plaintext highlighter-rouge">50%</code> gain and the compound return was still <code class="language-plaintext highlighter-rouge">5%</code> , very misleading.</li>
</ol>

<p>One more thing is that the ratio happens to be more directly interpretable than percentage, with respect to the investment amount. For example, when one says the final value of BCO is 1.1 times the initial investment, this is more intuitive than saying BCO rose by 10%.</p>

<p>The formula to get the final value is just as the interpretation says:</p>

\[\text{new_value} = \text{ratio_return} * \text{old_value}\]

<p>Following the format of asking questions, if one is to ask “given the BCO simple return ratios of <code class="language-plaintext highlighter-rouge">1.1, 0.5, 2</code> what is the monthly average of returns?”</p>

<p>In other to calculate this, you may try to use the formula for averages: $\frac{1}{N} * \sum_{i=1}^{N} x_i$.</p>

<p>For BCO, this means:</p>

\[\text{average_simple_return} = \frac{1.1 + 0.5 + 2}{3} = 1.2\]

<p><strong><em>But wait…</em></strong></p>

<p>Yes, we are following the formula for calculating averages, but this approach means that we are throwing the compounding effect out of the window. This should not be the case as the return for the second month is dependent on those for the first month, and those for the third month are dependent on the second and first month. 
The challenge here is that to integrate the compounding effect, we need to multiply, but the formula for averages requires summation instead.</p>

<p>There is also this slight issue that one can observe with the returns from the second and third month i.e., <code class="language-plaintext highlighter-rouge">0.5</code> and <code class="language-plaintext highlighter-rouge">2</code>. This is: simple returns lack symmetry and is not very intuitive as a result. 
Where the value of <code class="language-plaintext highlighter-rouge">0.5</code> meant that the investment went from $11k to $5.5k, it can be confusing to see that it takes a simple return of <code class="language-plaintext highlighter-rouge">2</code> instead of <code class="language-plaintext highlighter-rouge">1.5</code> to get the investment back to $11k. This asymmetry is caused by the changing denominator (old_value) in the formula for simple returns.</p>

<p>These two issues lead us into log returns.</p>

<h2 id="calculating-log-returns">Calculating Log Returns</h2>

<p>Log returns are achieved by calculating the natural log of the simple return (ratio), yes, it’s that simple. When you have the log returns, you can go in the other direction and get the simple return (ratio) by calculating the exponent of the log return.</p>

\[\text{log_return} = log(\text{simple_return})\]

\[\text{simple_return} = exp(\text{log_return})\]

<p>So how do logarithms fix the issue of integrating the compounding effect into the calculation of averages? It comes down to the product rule:</p>

\[log_{a}(X * Y) \leftrightarrow log_{a}X + log_{a}Y\]

<p>This implies that we can do summation using the logarithmic values to meet the requirements of the formula for averages and also integrate the compounding effect gained from multiplication. After the calculation, we can undo the logarithmic transformation by calculating the exponent.</p>

\[\text{avg_simple_return} = exp(\frac{1}{N} * \sum_{i=1}^{N} log(x_i))\]

<p>This means:</p>

\[\text{avg_simple_return} = \frac{log(1.1) + log(0.5) + log(2)}{3} = exp(0.0317) = 1.0323\]

<p>Following the simple_return(percentage) formula from earlier, $\text{simple_return(percentage)} = \text{simple_return(ratio)} - 1$.</p>

\[\text{simple_return(percentage)} = 1.0323 - 1 = 0.0323 = 3.23\%\]

<p>Does the average of <code class="language-plaintext highlighter-rouge">3.23%</code> make sense? Yes. Considering that the second and third months were spent losing and making the money back, it is understandable that the average return is the <code class="language-plaintext highlighter-rouge">10%</code> made from the first month divided by 3. NB: <a href="https://gregorygundersen.com/blog/2022/02/06/log-returns/#approximations">Calculations using logarithm give an approximate value of returns</a>, which is why the return is <code class="language-plaintext highlighter-rouge">3.23</code> which is not exactly the result of dividing <code class="language-plaintext highlighter-rouge">10%</code> by 3 i.e. <code class="language-plaintext highlighter-rouge">3.33%</code> .</p>

<p>On the issue with symmetry, log returns do not suffer from this problem. The logarithm of <code class="language-plaintext highlighter-rouge">0.5</code> and <code class="language-plaintext highlighter-rouge">2</code> which are the simple returns for the second and third months, are <code class="language-plaintext highlighter-rouge">-0.6931</code>  and <code class="language-plaintext highlighter-rouge">0.6931</code> respectively. This clearly passes the information that the losses from the second month are recovered in the third month.</p>

<p>The scenarios provided so far give context about the various kinds of returns, where they fall short and how another return fills its place. But for the sake of being direct, here are more succinct reasons why log returns are quite popular:</p>

<ul>
  <li>They support time additivity without losing the compounding effect.</li>
  <li>Log additions are better than multiplications as <a href="https://cs.stackexchange.com/questions/77135/why-is-adding-log-probabilities-faster-than-multiplying-probabilities">the former avoids exponential growth or decay</a> that comes with the latter.</li>
  <li>Logarithmic transformations are used in various financial formulas and models, so log returns maintain the continuity and provide mathematical convenience.</li>
  <li><a href="https://www.investopedia.com/articles/investing/102014/lognormal-and-normal-distribution.asp">Stock prices are assumed to have a log normal distribution</a>, so calculating their log returns helps get a normal distribution which is more suitable for different statistical models with assumptions of such a distribution. NB: The assumption of a log normal distribution for stock prices is not always true, and can be argued to not be a strong case for using log returns.</li>
</ul>

<p>That’s the end of the article, I hope my explanation has helped provide clear answers to the question “Why log returns?”. If I missed something, I would appreciate a comment to help address this. Also if you have any further questions, they are welcome.</p>

<h2 id="further-reading">Further Reading</h2>

<p>Data Preprocessing - Python for Finance Cookbook. <a href="https://www.amazon.co.uk/Python-Finance-Cookbook-effective-financial/dp/1803243198">Amazon</a></p>

<p>Time Stamps And Financial Modeling - Doing Data Science. <a href="https://www.amazon.co.uk/Doing-Data-Science-Straight-Frontline/dp/1449358659">Amazon</a></p>

<p>FRM: Why we use log returns in finance. <a href="https://www.youtube.com/watch?v=PtoUlt3V0CI">YouTube</a></p>

<p>Why we use Ln returns in finance. <a href="https://www.youtube.com/watch?v=47h5VsGahfc">YouTube</a></p>

<p>Log returns are awesome - how to apply them to trading. <a href="https://www.reddit.com/r/PMTraders/comments/10mdmsu/log_returns_are_awesome_how_to_apply_them_to/">Reddit</a></p>

<p>The Intuition of Log Returns - <a href="https://robotwealth.com/the-intuition-of-log-returns/">Robot Wealth</a></p>]]></content><author><name>Habeeb Shopeju</name><email>shopejuh@gmail.com</email></author><category term="stock-trading" /><summary type="html"><![CDATA[Log returns are commonly used in investing but why? This article provides some answers.]]></summary></entry><entry><title type="html">I Reverse-Engineered Trading212’s Web APIs</title><link href="https://www.haksoat.com/reverse-engineering-trading212/" rel="alternate" type="text/html" title="I Reverse-Engineered Trading212’s Web APIs" /><published>2024-02-18T00:00:00+01:00</published><updated>2024-02-18T01:20:02+01:00</updated><id>https://www.haksoat.com/reverse-engineering-trading212</id><content type="html" xml:base="https://www.haksoat.com/reverse-engineering-trading212/"><![CDATA[<p>Hi there, this is the third article I am writing from the <a href="https://www.haksoat.com/learning-stock-trading-python/">learning about stock trading with python</a> series. 
In this article, I write about my experience reverse-engineering Trading212’s APIs and building a <a href="https://github.com/HAKSOAT/tradingTOT">custom Python package</a> for placing trades using Trading212. 
You may wonder, why do this rather than use something off the shelf? This leads me to the first part of this article; the backstory.</p>

<h1 id="the-backstory">The Backstory</h1>

<p>In the <a href="https://www.haksoat.com/building-trading-system/#a-broker">What Goes Into Building a Trading System</a> article, I wrote about my experience trying to find a broker for placing trades but struggling to find one. 
I had done some research about various platforms, including trying to use Interactive Brokers. However, Trading212 seemed to be an easy-to-use trading platform with zero commission fees and a user-friendly interface. 
Hence, I set out to learn more about what they had to offer in terms of APIs and the ability to place trades programmatically.</p>

<h1 id="trading212-clients">Trading212 Clients</h1>

<p>The platform offers its product to customers across different platforms, including the web and mobile platforms. I came across some news on their forum about <a href="https://community.trading212.com/t/new-equity-trading-api-in-beta-try-it-out-in-practice-mode/61788">the availability of a beta API for testing purposes</a> and the thread links to an <a href="https://t212public-api-docs.redoc.ly/">API documentation</a> too. 
On going through the thread, I noticed the API does not work in live trading scenarios and is far from stable. NB: On doing one more check while writing this article, I saw they made the API <a href="https://community.trading212.com/t/new-equity-trading-api-in-beta-try-it-out-in-practice-mode/61788/37">accessible to live account users</a> at some point, but <a href="https://community.trading212.com/t/new-equity-trading-api-in-beta-try-it-out-in-practice-mode/61788/143">further development remains paused</a>.</p>

<p>I also came across a couple of unofficial Trading212 Python packages such as <a href="https://github.com/BenTimor/Trading212API/">Trading212API</a> for programmatically buying and selling on the platform. Sadly, it was broken, and it didn’t seem like a good idea trying to fix it (maybe I was itching to build something myself too).</p>

<p class="text-center"><img src="http://res.cloudinary.com/haks/image/upload/v1708180415/HAKSOAT_Blog/reverse-engineering-trading212/trading212-api-pause.png" alt="Screenshot of Trading212 API Pause" class="align-center" />
A conversation on the Trading212 forum about the pause on API development.</p>

<h1 id="studying-the-apis">Studying the APIs</h1>

<p>Behind every web application are API calls that make the functionalities work. Where each API endpoint can be considered as some sort of LEGO block, and one can combine the various blocks to get a final product. When looking to build a package such as the one I write about in this article, it is necessary to see how the endpoints correlate.</p>

<p>While it is not my first time reverse-engineering web APIs, something I found interesting was that many endpoints were reliant on calling <code class="language-plaintext highlighter-rouge">/rest/v1/webclient/authenticate</code> first. Where such a call was missing, I got errors relating to lack of authentication.</p>

<p>Some kudos to the engineering by Trading212, I noticed that the demo environment was some mirror of the live environment. Hence, after confirming that things were working as expected in demo, all I did was to substitute a variable and start operating in a real environment. For context, I had urls written in a way similar to <code class="language-plaintext highlighter-rouge">f"https://{environment}.trading212.com/rest/v1/webclient/authenticate"</code>, where environment can be <code class="language-plaintext highlighter-rouge">live</code> or <code class="language-plaintext highlighter-rouge">demo</code>.</p>

<p>I also noticed their use of Algolia for their search functionality and the Algolia API was being called for endpoints relating to equities. Therefore, I needed to understand how to extract the application id and the <code class="language-plaintext highlighter-rouge">x-algolia-api-key</code> they use, which was accessible through Devtools.</p>

<p>While it was a good thing that I could access such data from studying the APIs, I wonder, aren’t there risks of storing the key like that? If you are a frontend person, do chime in with your thoughts on if there is a better way to go about this from an engineering and security perspective.</p>

<p>On understanding these behaviours, I sought to find the other endpoints that influenced the behaviours I was hoping to control. Some of them include:</p>

<ul>
  <li><code class="language-plaintext highlighter-rouge">/rest/v1/equity/value-order/validate</code>: To check if an order is valid. This endpoint is to be used before placing the actual order call.</li>
  <li><code class="language-plaintext highlighter-rouge">/rest/v1/equity/value-order/review</code>: To view the costs of placing the order.</li>
  <li><code class="language-plaintext highlighter-rouge">/rest/v1/equity/value-order</code>: To actually place the order.</li>
  <li><code class="language-plaintext highlighter-rouge">/rest/trading/v1/accounts/summary</code>: To check for placed orders. It also returns the cash and value summary of a trader’s account.</li>
</ul>

<p>It was quite fun to see how the APIs integrate to make Trading212 usable for the web user. Do note that this is not the first time I am reverse-engineering web APIs. I have done something similar with platforms like Rightmove, Zoopla and even <a href="https://github.com/HAKSOAT/Bittimi/blob/main/utils.py">built a custom web application</a> on reverse-engineering <a href="https://www.bitrefill.com/gb/en/">Bitrefill</a>.</p>

<p><img src="http://res.cloudinary.com/haks/image/upload/v1708181253/HAKSOAT_Blog/reverse-engineering-trading212/tradingTOT-demo.gif" alt="TradingTOT demo" class="align-center" /></p>

<p class="text-center">A TradingTOT package demo.</p>

<h1 id="some-interesting-ideas">Some Interesting Ideas</h1>

<p>After understanding how the APIs interacted, I moved on to build <a href="https://github.com/HAKSOAT/tradingTOT">the Trading212 package</a> that I would go on to use in the basic trading system I was working on. 
While doing this, I came across and applied some interesting ideas, and I would like to share them in this section.</p>

<ul>
  <li>Devtools Preserve Log</li>
  <li>Selenium Plus Python Requests</li>
  <li>Enforce Auth as a Decorator</li>
  <li>Selenium Stealth</li>
  <li>Selenium ActionChains</li>
  <li>Converting JSON to Pydantic Models using ChatGPT</li>
</ul>

<h2 id="devtools-preserve-log">Devtools Preserve Log</h2>

<p>When looking to reverse engineer APIs, it is important to understand the flow of various API calls. Many web browsers provide the “preserve log” functionality; it helps keep the logs across multiple page loads. 
Sadly, this feature is disabled by default and if you are unaware of its availability, you will end up missing out on the edge it offers.</p>

<p>One use case for me was in situations where there was a new page being loaded after clicking a certain button. This meant was that before I could go through the various API calls resulting from the click, a new page was loaded and the logs are refreshed. 
Interestingly, I only got to know about this feature on this project and I have always studied API calls without it, but I guess the need for preserving logs got me to find out about it.</p>

<p><img src="https://res.cloudinary.com/haks/image/upload/v1708180613/HAKSOAT_Blog/reverse-engineering-trading212/preserve-log.png" alt="Preserve Log Checkbox" class="align-center" /></p>

<p class="text-center">A screenshot of the preserve log checkbox.</p>

<h2 id="combining-selenium-and-python-requests">Combining Selenium and Python Requests</h2>

<p>In this project, I was hoping to do everything without Selenium as I was concerned about the overhead that comes along with it. However, I was not successful with this because I could not figure what API Trading212 was using to send email and password to the backend. In the end, I used Selenium to extract something Trading212 calls a <code class="language-plaintext highlighter-rouge">LOGIN_TOKEN</code> and also to extract the parts of the header crucial to making an API call.</p>

<p>On getting these values, I updated the headers and cookies in a <code class="language-plaintext highlighter-rouge">requests.Session</code> object. The implication of this is that from that point on, I could use Python’s Requests package to send the API requests. Using Selenium to extract credentials in the first stage was unpleasant despite it being a onetime process, but this shows it is possible to use both tools in the same workflow.</p>

<p>The workflow looks something like:</p>

<figure class="highlight"><pre><code class="language-python" data-lang="python"><span class="n">driver</span> <span class="o">=</span> <span class="n">load_driver</span><span class="p">()</span>
<span class="n">driver</span> <span class="o">=</span> <span class="n">login_trading212</span><span class="p">(</span><span class="n">driver</span><span class="p">,</span> <span class="n">os</span><span class="p">.</span><span class="n">environ</span><span class="p">.</span><span class="n">get</span><span class="p">(</span><span class="s">"TRADING212_EMAIL"</span><span class="p">),</span>
                          <span class="n">os</span><span class="p">.</span><span class="n">environ</span><span class="p">.</span><span class="n">get</span><span class="p">(</span><span class="s">"TRADING212_PASSWORD"</span><span class="p">))</span>
<span class="n">headers</span> <span class="o">=</span> <span class="n">generate_headers</span><span class="p">(</span><span class="n">driver</span><span class="p">)</span>
<span class="n">auth_cookies</span> <span class="o">=</span> <span class="p">{</span><span class="s">'LOGIN_TOKEN'</span><span class="p">:</span> <span class="n">get_login_token</span><span class="p">(</span><span class="n">driver</span><span class="p">)}</span>
<span class="n">driver</span><span class="p">.</span><span class="n">close</span><span class="p">()</span>
<span class="n">session</span> <span class="o">=</span> <span class="n">requests</span><span class="p">.</span><span class="n">Session</span><span class="p">()</span>
<span class="n">session</span><span class="p">.</span><span class="n">headers</span><span class="p">.</span><span class="n">update</span><span class="p">(</span><span class="n">headers</span><span class="p">)</span>
<span class="n">session</span><span class="p">.</span><span class="n">cookies</span><span class="p">.</span><span class="n">update</span><span class="p">(</span><span class="n">auth_cookies</span><span class="p">)</span>
<span class="n">session</span><span class="p">.</span><span class="n">post</span><span class="p">(</span><span class="n">ACCOUNT_SUMMARY_URL</span><span class="p">,</span> <span class="n">json</span><span class="o">=</span><span class="p">[]).</span><span class="n">json</span><span class="p">()</span></code></pre></figure>

<h2 id="enforce-auth-as-a-decorator">Enforce Auth as a Decorator</h2>

<p>Earlier, I talked about some endpoints relying on an initial call of the <code class="language-plaintext highlighter-rouge">/rest/v1/webclient/authenticate</code> endpoint. I did not want to bake the authentication call into the functions that make those calls, so I chose to use a decorator to extend them.</p>

<p>In Python, the concept of a decorator is a function that extends the behaviour of another function it receives without modifying the contents of this received function. It does this by wrapping the contents of the received function in the extra behaviour.</p>

<p>A basic Python decorator looks something like this:</p>

<figure class="highlight"><pre><code class="language-python" data-lang="python"><span class="k">def</span> <span class="nf">my_decorator</span><span class="p">(</span><span class="n">func</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">wrapper</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
        <span class="c1"># Do something before the function call
</span>        <span class="n">result</span> <span class="o">=</span> <span class="n">func</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>
        <span class="c1"># Do something after the function call
</span>        <span class="k">return</span> <span class="n">result</span>
    <span class="k">return</span> <span class="n">wrapper</span></code></pre></figure>

<p>The decorator I came up with looks something like this:</p>

<p>This decorator looked something like:</p>

<figure class="highlight"><pre><code class="language-python" data-lang="python"><span class="kn">from</span> <span class="nn">functools</span> <span class="kn">import</span> <span class="n">wraps</span>

<span class="k">def</span> <span class="nf">enforce_auth</span><span class="p">(</span><span class="n">func</span><span class="p">:</span> <span class="n">Callable</span><span class="p">):</span>
    <span class="o">@</span><span class="n">wraps</span><span class="p">(</span><span class="n">func</span><span class="p">)</span>
    <span class="k">def</span> <span class="nf">wrapper</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
        <span class="n">instance</span> <span class="o">=</span> <span class="n">kwargs</span><span class="p">.</span><span class="n">get</span><span class="p">(</span><span class="s">"self"</span><span class="p">,</span> <span class="n">args</span><span class="p">[</span><span class="mi">0</span><span class="p">])</span>

        <span class="k">try</span><span class="p">:</span>
            <span class="n">auth_response</span> <span class="o">=</span> <span class="n">instance</span><span class="p">.</span><span class="n">session</span><span class="p">.</span><span class="n">get</span><span class="p">(</span><span class="n">AUTHENTICATE_URL</span><span class="p">)</span>
            <span class="n">is_auth</span> <span class="o">=</span> <span class="bp">True</span> <span class="k">if</span> <span class="n">auth_response</span><span class="p">.</span><span class="n">status_code</span> <span class="o">==</span> <span class="mi">200</span> <span class="k">else</span> <span class="bp">False</span>
        <span class="k">except</span> <span class="nb">ConnectionError</span><span class="p">:</span>
            <span class="n">is_auth</span> <span class="o">=</span> <span class="bp">False</span>

        <span class="k">while</span> <span class="ow">not</span> <span class="n">is_auth</span><span class="p">:</span>
            <span class="n">login_and_update_cookies</span><span class="p">()</span>

        <span class="k">if</span> <span class="n">kwargs</span><span class="p">.</span><span class="n">get</span><span class="p">(</span><span class="s">"self"</span><span class="p">):</span>
            <span class="n">kwargs</span><span class="p">[</span><span class="s">"self"</span><span class="p">]</span> <span class="o">=</span> <span class="n">instance</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="n">args</span> <span class="o">=</span> <span class="nb">list</span><span class="p">(</span><span class="n">args</span><span class="p">)</span>
            <span class="n">args</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">=</span> <span class="n">instance</span>
            <span class="n">args</span> <span class="o">=</span> <span class="nb">tuple</span><span class="p">(</span><span class="n">args</span><span class="p">)</span>

        <span class="k">return</span> <span class="n">func</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span></code></pre></figure>

<p>Here extraction of the <code class="language-plaintext highlighter-rouge">self</code> argument is because the decorator is being used on instance methods. Hence, the instance is being modified after the extended functionality of the decorator is applied. 
You may notice the use of the <code class="language-plaintext highlighter-rouge">wraps</code> decorator function from <code class="language-plaintext highlighter-rouge">functools</code>. When a decorator is used, it alters the original function, hence a call like <code class="language-plaintext highlighter-rouge">help(original_function)</code> will only return the docstring from the altered function. This is likely undesirable behaviour and can make life hard for IDEs and when debugging. <code class="language-plaintext highlighter-rouge">wraps</code> ensures that the metadata returned is that of the original function rather than the altered one.</p>

<p>Below is an example application of this decorator:</p>

<figure class="highlight"><pre><code class="language-python" data-lang="python"><span class="o">@</span><span class="n">enforce_auth</span>
<span class="k">def</span> <span class="nf">get_account_details</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="n">Dict</span><span class="p">:</span>
    <span class="s">"""Get the value of assets in account."""</span>
    <span class="n">response</span> <span class="o">=</span> <span class="bp">self</span><span class="p">.</span><span class="n">session</span><span class="p">.</span><span class="n">post</span><span class="p">(</span><span class="n">ACCOUNT_SUMMARY_URL</span><span class="p">,</span> <span class="n">json</span><span class="o">=</span><span class="p">[]).</span><span class="n">json</span><span class="p">()</span>
    <span class="n">details</span> <span class="o">=</span> <span class="p">{</span>
        <span class="s">"cash"</span><span class="p">:</span> <span class="n">response</span><span class="p">.</span><span class="n">get</span><span class="p">(</span><span class="s">"cash"</span><span class="p">).</span><span class="n">get</span><span class="p">(</span><span class="s">"freeForStocks"</span><span class="p">),</span>
        <span class="s">"total"</span><span class="p">:</span> <span class="n">response</span><span class="p">.</span><span class="n">get</span><span class="p">(</span><span class="s">"cash"</span><span class="p">).</span><span class="n">get</span><span class="p">(</span><span class="s">"total"</span><span class="p">)</span>
    <span class="p">}</span>

    <span class="k">return</span> <span class="n">details</span></code></pre></figure>

<p>By applying this <code class="language-plaintext highlighter-rouge">enforce_auth</code> decorator, the authenticate endpoint is always called before any attempt to extract the account details. I have always used decorators from third-party libraries and frameworks, but it was nice to have a use case to create one myself.</p>

<h2 id="selenium-stealth">Selenium Stealth</h2>

<p>As I mentioned earlier, I used Selenium to log in to Trading212 before extracting the login token. All of this worked properly when using Selenium in its default configuration. However, this does not provide a good user experience for a package as Selenium will try to spin up an interactive browser. Imagine calling <code class="language-plaintext highlighter-rouge">tradingTOT().get_account_details()</code> and having a browser triggered, not good. So I decided to use Selenium’s headless mode and to my dismay, I was greeted with an access denied error. I did some research about this and came across Selenium Stealth. It turns out that <a href="https://stackoverflow.com/questions/33225947/can-a-website-detect-when-you-are-using-selenium-with-chromedriver">Selenium has some indicators</a> that web platforms often check to detect automated clients. Selenium Stealth makes it harder to detect the browser in automated mode.</p>

<p>It is also quite easy to use, one call wrapping Selenium’s <code class="language-plaintext highlighter-rouge">Driver</code> object is all that is needed.</p>

<figure class="highlight"><pre><code class="language-python" data-lang="python"><span class="n">stealth</span><span class="p">(</span><span class="n">driver</span><span class="p">,</span> <span class="n">languages</span><span class="o">=</span><span class="p">[</span><span class="s">"en-US"</span><span class="p">,</span> <span class="s">"en"</span><span class="p">],</span>
        <span class="n">vendor</span><span class="o">=</span><span class="s">"Google Inc."</span><span class="p">,</span> <span class="n">platform</span><span class="o">=</span><span class="s">"Win32"</span><span class="p">,</span>
        <span class="n">webgl_vendor</span><span class="o">=</span><span class="s">"Intel Inc."</span><span class="p">,</span> <span class="n">renderer</span><span class="o">=</span><span class="s">"Intel Iris OpenGL Engine"</span><span class="p">,</span>
        <span class="n">fix_hairline</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span></code></pre></figure>

<p>One thing to note is that Selenium Stealth only supports Google Chrome. Hence, while tradingTOT supports Microsoft Edge and Safari too, Chrome is encouraged as it increases the chances of a smooth execution.</p>

<h2 id="selenium-actionchains">Selenium ActionChains</h2>

<p>Before working on this project, I knew about the <code class="language-plaintext highlighter-rouge">ActionChains</code> class, but I did not quite understand the use case. 
Previously, I observed that whenever I tried to perform some automation tasks such as clicking and it did not work; I used <code class="language-plaintext highlighter-rouge">ActionChains</code> and it worked.
Why exactly, this was the case, I was not sure.</p>

<p>However, on this project, while trying to emulate a user behaviour before login, it all clicked.</p>

<p>Below is a sample use case:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">login_action</span> <span class="o">=</span> <span class="n">ActionChains</span><span class="p">(</span><span class="n">driver</span><span class="p">)</span>

<span class="n">password_input</span> <span class="o">=</span> <span class="n">driver</span><span class="p">.</span><span class="n">find_element</span><span class="p">(</span>
    <span class="n">By</span><span class="p">.</span><span class="n">XPATH</span><span class="p">,</span> <span class="s">"//input[@name='password' and @type='password']"</span>
<span class="p">)</span>
<span class="n">login_action</span><span class="p">.</span><span class="n">move_to_element</span><span class="p">(</span>
    <span class="n">password_input</span><span class="p">).</span><span class="n">click</span><span class="p">(</span>
    <span class="n">password_input</span><span class="p">).</span><span class="n">send_keys</span><span class="p">(</span><span class="n">password</span><span class="p">).</span><span class="n">pause</span><span class="p">(</span><span class="mf">0.1</span><span class="p">)</span>

<span class="n">login_button</span> <span class="o">=</span> <span class="n">driver</span><span class="p">.</span><span class="n">find_element</span><span class="p">(</span>
    <span class="n">By</span><span class="p">.</span><span class="n">XPATH</span><span class="p">,</span> <span class="s">"//input[@type='submit' and @value='Log in']"</span>
<span class="p">)</span>
<span class="n">login_action</span><span class="p">.</span><span class="n">move_to_element</span><span class="p">(</span>
    <span class="n">login_button</span><span class="p">).</span><span class="n">click</span><span class="p">(</span><span class="n">login_button</span><span class="p">).</span><span class="n">pause</span><span class="p">(</span><span class="mf">0.1</span><span class="p">)</span>

<span class="n">login_action</span><span class="p">.</span><span class="n">perform</span><span class="p">()</span>
</code></pre></div></div>

<p>It occurred to me that <code class="language-plaintext highlighter-rouge">ActionChains</code> is a great way to combine multiple actions, such that you can decide when to execute with the <code class="language-plaintext highlighter-rouge">perform</code> method.
From the code sample above, I can simulate the mouse moving to various elements, sending keys, pausing before the next action. 
If I am to do this without <code class="language-plaintext highlighter-rouge">ActionChains</code>, it would be:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">password_input</span> <span class="o">=</span> <span class="n">driver</span><span class="p">.</span><span class="n">find_element</span><span class="p">(</span>
    <span class="n">By</span><span class="p">.</span><span class="n">XPATH</span><span class="p">,</span> <span class="s">"//input[@name='password' and @type='password']"</span>
<span class="p">)</span>
<span class="n">password_input</span><span class="p">.</span><span class="n">send_keys</span><span class="p">(</span><span class="n">password</span><span class="p">)</span>

<span class="n">time</span><span class="p">.</span><span class="n">sleep</span><span class="p">(</span><span class="mf">0.1</span><span class="p">)</span>

<span class="n">login_button</span> <span class="o">=</span> <span class="n">driver</span><span class="p">.</span><span class="n">find_element</span><span class="p">(</span>
    <span class="n">By</span><span class="p">.</span><span class="n">XPATH</span><span class="p">,</span> <span class="s">"//input[@type='submit' and @value='Log in']"</span>
<span class="p">)</span>
<span class="n">login_button</span><span class="p">.</span><span class="n">click</span><span class="p">()</span>
</code></pre></div></div>

<p>This approach:</p>

<ol>
  <li>will not automate the mouse movements</li>
  <li>does not have a pause mechanism as it relies on Python <code class="language-plaintext highlighter-rouge">time.sleep</code></li>
  <li>can become messy especially if multiple complex actions are necessary</li>
</ol>

<p>I will keep using <code class="language-plaintext highlighter-rouge">ActionChains</code> going forward for my automation tasks. In the previous example, you can see how I created <code class="language-plaintext highlighter-rouge">login_action</code> action chain. 
If I need other complex actions such as reset password, sign up, I can create separate action chains for them and execute using <code class="language-plaintext highlighter-rouge">perform</code>.</p>

<h2 id="converting-json-to-pydantic-models-using-chatgpt">Converting JSON to Pydantic Models using ChatGPT</h2>

<p>When working on this package, one of my main concerns was:</p>

<blockquote>
  <p>If Trading212 changes something in the API, what is the safest and fastest way to know?</p>
</blockquote>

<p>My answer to this was:</p>

<ol>
  <li>Build Pydantic classes from the API responses</li>
  <li>Use those Pydantic classes in tests</li>
  <li>Run such tests frequently</li>
  <li>Plug in notifications at the end of test runs</li>
</ol>

<p>This means that whenever the API breaks, there will be an awareness of this breaking change. Not to go into the details of the tests as I am more interested in talking about one use case of ChatGPT I came across.
I gave ChatGPT the API responses I was looking to generate Python classes from, for example:</p>

<figure class="highlight"><pre><code class="language-json" data-lang="json"><span class="p">{</span><span class="w">
    </span><span class="nl">"cash"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w">
        </span><span class="nl">"free"</span><span class="p">:</span><span class="w"> </span><span class="s2">"VALUE"</span><span class="p">,</span><span class="w">
        </span><span class="nl">"total"</span><span class="p">:</span><span class="w"> </span><span class="s2">"VALUE"</span><span class="p">,</span><span class="w">
        </span><span class="nl">"interest"</span><span class="p">:</span><span class="w"> </span><span class="s2">"VALUE"</span><span class="p">,</span><span class="w">
        </span><span class="err">...</span><span class="w">
        </span><span class="nl">"blockedForStocks"</span><span class="p">:</span><span class="w"> </span><span class="s2">"VALUE"</span><span class="p">,</span><span class="w">
        </span><span class="nl">"pieCash"</span><span class="p">:</span><span class="w"> </span><span class="s2">"VALUE"</span><span class="w">
    </span><span class="p">},</span><span class="w">
    </span><span class="nl">"open"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w">
        </span><span class="nl">"unfilteredCount"</span><span class="p">:</span><span class="w"> </span><span class="s2">"VALUE"</span><span class="p">,</span><span class="w">
        </span><span class="nl">"items"</span><span class="p">:</span><span class="w"> </span><span class="p">[</span><span class="w">
            </span><span class="p">{</span><span class="w">
                </span><span class="nl">"positionId"</span><span class="p">:</span><span class="w"> </span><span class="s2">"ID1"</span><span class="p">,</span><span class="w">
                </span><span class="nl">"humanId"</span><span class="p">:</span><span class="w"> </span><span class="s2">"ID1"</span><span class="p">,</span><span class="w">
                </span><span class="nl">"created"</span><span class="p">:</span><span class="w"> </span><span class="s2">"DATE"</span><span class="p">,</span><span class="w">
                </span><span class="err">...</span><span class="w">
                </span><span class="nl">"maxBuy"</span><span class="p">:</span><span class="w"> </span><span class="s2">"VALUE"</span><span class="p">,</span><span class="w">
                </span><span class="nl">"maxSell"</span><span class="p">:</span><span class="w"> </span><span class="s2">"VALUE"</span><span class="p">,</span><span class="w">
                </span><span class="nl">"maxOpenBuy"</span><span class="p">:</span><span class="w"> </span><span class="s2">"VALUE"</span><span class="p">,</span><span class="w">
                </span><span class="nl">"maxOpenSell"</span><span class="p">:</span><span class="w"> </span><span class="s2">"VALUE"</span><span class="p">,</span><span class="w">
            </span><span class="p">},</span><span class="w">
        </span><span class="p">]</span><span class="w">
    </span><span class="p">},</span><span class="w">
    </span><span class="err">...</span><span class="w">
</span><span class="p">}</span></code></pre></figure>

<p>I was impressed to see that it did a good job of generating the classes. Here are the classes it generated, matching the example above:</p>

<figure class="highlight"><pre><code class="language-python" data-lang="python"><span class="k">class</span> <span class="nc">Position</span><span class="p">(</span><span class="n">BaseModel</span><span class="p">):</span>
    <span class="n">positionId</span><span class="p">:</span> <span class="nb">str</span>
    <span class="n">humanId</span><span class="p">:</span> <span class="nb">str</span>
    <span class="n">created</span><span class="p">:</span> <span class="nb">str</span>
    <span class="p">...</span>
    <span class="n">maxBuy</span><span class="p">:</span> <span class="nb">float</span>
    <span class="n">maxSell</span><span class="p">:</span> <span class="nb">float</span>
    <span class="n">maxOpenBuy</span><span class="p">:</span> <span class="nb">float</span>
    <span class="n">maxOpenSell</span><span class="p">:</span> <span class="nb">float</span>


<span class="k">class</span> <span class="nc">Open</span><span class="p">(</span><span class="n">BaseModel</span><span class="p">):</span>
    <span class="n">unfilteredCount</span><span class="p">:</span> <span class="nb">int</span>
    <span class="n">items</span><span class="p">:</span> <span class="n">List</span><span class="p">[</span><span class="n">Position</span><span class="p">]</span>


<span class="k">class</span> <span class="nc">Cash</span><span class="p">(</span><span class="n">BaseModel</span><span class="p">):</span>
    <span class="n">free</span><span class="p">:</span> <span class="nb">float</span>
    <span class="n">total</span><span class="p">:</span> <span class="nb">float</span>
    <span class="n">interest</span><span class="p">:</span> <span class="nb">float</span>
    <span class="p">...</span>
    <span class="n">blockedForStocks</span><span class="p">:</span> <span class="nb">float</span>
    <span class="n">pieCash</span><span class="p">:</span> <span class="nb">int</span></code></pre></figure>

<p>On getting the classes generated, I made modifications such as setting default values where I deemed fit. 
After this, I parse responses gotten from sending HTTP requests, using the generated Pydantic classes.</p>

<p>For example, here is how I parse the response on calling the summary endpoint:</p>

<figure class="highlight"><pre><code class="language-python" data-lang="python"><span class="n">response</span> <span class="o">=</span> <span class="n">session</span><span class="p">.</span><span class="n">post</span><span class="p">(</span><span class="n">ACCOUNT_SUMMARY_URL</span><span class="p">,</span> <span class="n">json</span><span class="o">=</span><span class="p">[]).</span><span class="n">json</span><span class="p">()</span>
<span class="n">SummarySchema</span><span class="p">.</span><span class="n">model_validate</span><span class="p">(</span><span class="n">response</span><span class="p">)</span></code></pre></figure>

<p>If at any point the resulting json from the API call changes, the <code class="language-plaintext highlighter-rouge">model_validate</code> call fails with pointers to the attributes not meeting the requirements.
Aside from this making it easy to trust the tests, it also makes it easy to know what changed in the response and a hint of what to change in the package’s logic to keep things working as expected.</p>

<p>I have an idea to make use of ChatGPT to generate code fixes and a corresponding PR when such breaking changes happen. If I ever get to it, I will definitely be writing an article on it.</p>

<h1 id="conclusion">Conclusion</h1>

<p>Trading212 does not provide an API that enables the programmatic trading of equities, outside CFDs. Hence, I dug deep to reverse-engineer the APIs and build something for <a href="https://www.haksoat.com/learning-stock-trading-python/">my use case</a>. In this article, I wrote about how I went about building a <a href="https://github.com/HAKSOAT/tradingTOT">custom Python package</a> for placing trades using Trading212. 
I also wrote briefly about some cool things I came across along the way, such as Selenium Stealth and the use case of using ChatGPT to generate Pydantic models from JSON files.
If you have a project where you are looking to reverse-engineer web APIs and feel free to <a href="https://linkedin.com/in/habeebshopeju">reach out to me on LinkedIn</a>.</p>

<p>Next steps for me will be to plug this package into my existing <a href="https://www.backtrader.com/">Backtrader</a> setup and use in trading algorithms, demo environments then slowly transitioning to the live environments. 
On the side, I will gradually clean up and add more documentation to the package, then publish on PyPi, so it is easily accessible by others.</p>

<p>Side note: From writing <a href="https://www.haksoat.com/openbb-experience/">my last article on OpenBB</a>, I got some feedback on how it is possible to purchase stocks using MQL5. However, on checking the website, I do not quite understand how to go about this. So if you read till this point and have used MQL5 to trade stocks, please help me out.</p>]]></content><author><name>Habeeb Shopeju</name><email>shopejuh@gmail.com</email></author><category term="stock-trading-project" /><summary type="html"><![CDATA[I reverse-engineered Trading212's web APIs, then built a Python package for programmatic trading on the platform.]]></summary></entry><entry><title type="html">It’s Like The Bloomberg Terminal, But Open Source, My Experience using OpenBB</title><link href="https://www.haksoat.com/openbb-experience/" rel="alternate" type="text/html" title="It’s Like The Bloomberg Terminal, But Open Source, My Experience using OpenBB" /><published>2023-11-17T00:00:00+01:00</published><updated>2023-11-18T01:20:02+01:00</updated><id>https://www.haksoat.com/openbb-experience</id><content type="html" xml:base="https://www.haksoat.com/openbb-experience/"><![CDATA[<p>Hello all, this is the second article in <a href="https://www.haksoat.com/learning-stock-trading-python/">this series</a>. In this article, I will write about OpenBB and my experience using it as a data source for a trading system. I struggled to find a data source that is easy to use, but I can imagine there are tools out there that serve this purpose. If you know of or have used any, I would appreciate a mention in the comments.</p>

<p>I know that this article is supposed to be about OpenBB. However, permit me to divert briefly and write about the Bloomberg Terminal. The <a href="https://en.wikipedia.org/wiki/Bloomberg_Terminal">Bloomberg Terminal</a> is a financial software by Bloomberg L.P. It is widely known for its large array of financial functionalities and notably provides data such as news, ticker data, financial statements, economic indicators, etc. This data richness makes it very valuable to financial analysts, investment bankers, and traders, just to mention a few. But there is a huge price to pay. It is said that <a href="https://www.investopedia.com/articles/professionaleducation/11/bloomberg-terminal.asp">the Bloomberg Terminal costs around $24,000 per year</a>. This price is a huge deterrent for non-professionals and trading enthusiasts. Given this context, let’s see what OpenBB is about.</p>

<h2 id="what-is-openbb">What is OpenBB?</h2>

<p><a href="https://openbb.co/">OpenBB</a> looks to provide open source, free and easy access to financial data, providing Bloomberg terminal-like features. OpenBB provides access to data such as:</p>

<ul>
  <li>Stock prices, indicators for technical analysis</li>
  <li>Financial and SEC disclosure statements for fundamental analysis</li>
  <li>News, social media and sentiment data for behavioural analysis</li>
</ul>

<p><a href="https://github.com/OpenBB-finance/OpenBBTerminal">OpenBB is available on GitHub</a>, hence, open for contributions. As of the time of writing this article, it has three offerings: The Terminal, SDK and Bot.</p>

<p><a href="https://docs.openbb.co/terminal">The Terminal</a> provides access to financial data through the terminal or command prompt. It is available on Linux, macOS and Windows, through different installation methods.</p>

<p><a href="https://docs.openbb.co/sdk">The SDK</a> is a Python package that allows programmatic access to the features available in the terminal. While doing the research for this article, I realized some interesting functionality such as the <a href="https://docs.openbb.co/sdk/reference/forecast">Forecast module</a>. It has feature engineering, exploratory analysis and prediction functionality. I think this is quite cool and I should play around with those features.</p>

<p><a href="https://docs.openbb.co/bot">The Bot</a> is a chatbot integration currently available on Discord and Telegram. I have not made use of this integration, but I would like to imagine that they provide the same functionality as the Terminal based on existing Discord and Telegram features.</p>

<p>I recognize new OpenBB features from the last time I did some research on it, which is a sign of it being a fast-growing project. Some of these include:</p>

<ul>
  <li>a waiting list for <a href="https://my.openbb.co/app/pro">Terminal Pro</a> which promises a better interface and official partnerships with data providers</li>
  <li>the availability of API keys, which I believe should imply improved SDK reliability</li>
  <li>a community to network</li>
</ul>

<p>Given this, I believe some of the challenges I experienced will be addressed by these functionalities when they are released.</p>

<h2 id="my-experience">My Experience</h2>

<p>Overall, I think I had a good experience with OpenBB. Most of my usage was from the SDK, so there is not much to say about the other products. I did face some challenges, but I was able to use it for my experiments regardless. When I resume this project, still intend to continue using OpenBB.</p>

<h3 id="ease-of-use">Ease of Use</h3>
<p>I found it easy to use the SDK. The installation process was smooth. I installed it in a Google Colab notebook with a command as simple as <code class="language-plaintext highlighter-rouge">pip install openbb</code> and I was also able to set it up on <a href="https://python-poetry.org/">Poetry</a>.</p>

<p>I liked the separation of the modules based on the kind of data as it made it easy to figure out where certain functionalities live. For example, to access stock prices all you need is <code class="language-plaintext highlighter-rouge">openbb.stocks.load(...)</code> and <code class="language-plaintext highlighter-rouge">openbb.stocks.news(...)</code> to access news data. In the case of fundamental analysis, you can access <a href="https://www.investopedia.com/terms/1/10-k.asp">SEC 10K filings</a> using: <code class="language-plaintext highlighter-rouge">openbb.stocks.fa.analysis(...)</code> after which the document is parsed into groups such as Risk factors, Discussions and Analysis.</p>

<p>While my interests are in stocks, the SDK also provides access to data in other kinds of securities such as Crypto, Forex, Futures, etc.</p>

<h3 id="pandas-integration">Pandas Integration</h3>
<p>I believe one of the best decisions made by the OpenBB team was to return requested data as pandas DataFrames. This reduces the learning curve for the average Python developer who has some experience with Pandas. This decision implies that I was able to use Pandas functions such as the rolling window when processing stock prices for my algorithms.</p>

<h3 id="challenges">Challenges</h3>
<p>While I think OpenBB is nice, I experienced some challenges while using it. These are:</p>

<ul>
  <li>
    <p><strong>News window limitation</strong>: I was hoping to experiment with news data for predicting stock prices. However, I quickly realized that the API only returned very recent news data. For example, on checking $TSLA news on November 16, 2023, the oldest news was from November 2, 2023. I think the tool being free means little room to store lots of data, so I hope the Pro version tackles this.</p>
  </li>
  <li>
    <p><strong>Data load time</strong>: It took a long time to load data across say 15-year timespans, and there was no caching involved. Hence, for backtesting, this process became prohibitively slow especially when running the backtests repeatedly. My solution here was to implement some caching myself, but I believe it would have been more efficient to have this implemented on their end.</p>
  </li>
  <li>
    <p><strong>Reliability</strong>: I experienced the SDK breaking when I made a lot of requests for stock prices. Say I have a list of ticker symbols, I would usually loop through them individually to get the needed data. I do not believe this should be an issue as they are not being made concurrently or in parallel. However, I realized the API would break with errors relating to the ticker symbol not existing, when in fact it did exist. My bypass was to add <code class="language-plaintext highlighter-rouge">time.sleep</code> in between the requests, but the implication was that it took longer to get all the data.</p>
  </li>
</ul>

<h2 id="final-thoughts">Final Thoughts</h2>
<p>I am looking forward to the progress the team makes on the project in the coming year. I intend to continue to use the tool as infrastructure for my stock trading experiments.</p>

<p>While I have written about the challenges faced using the SDK, I realize that I can very well contribute to the project and give a helping hand to the team. I hope I can do a bit of this when I have some free time. Let me take this opportunity to encourage you to contribute to <a href="https://github.com/OpenBB-finance/OpenBBTerminal">OpenBB</a> if you are looking to do some open-source work.</p>]]></content><author><name>Habeeb Shopeju</name><email>shopejuh@gmail.com</email></author><category term="stock-trading-project" /><summary type="html"><![CDATA[A review of OpenBB and my experience using it.]]></summary></entry><entry><title type="html">What Goes Into Building a Trading System</title><link href="https://www.haksoat.com/building-trading-system/" rel="alternate" type="text/html" title="What Goes Into Building a Trading System" /><published>2023-11-13T00:00:00+01:00</published><updated>2023-11-13T01:20:02+01:00</updated><id>https://www.haksoat.com/building-trading-system</id><content type="html" xml:base="https://www.haksoat.com/building-trading-system/"><![CDATA[<p>Hello all, this is the first article in <a href="https://www.haksoat.com/learning-stock-trading-python/">this series</a>.
I will be writing about my learnings about some of the key components that go into building a trading system.
I realize that such a system is complex and there are some components involved that I may have left out;
in this case, I would appreciate briefly mentioning them in the comments.
My hope is that this article gives you an insight into the needed components
and perhaps can be beneficial to you.</p>

<p>These are the components I had to work with:</p>

<ul>
  <li>
    <p>Data Source: Trades are placed based on ticks or other financial data, this comes from a data provider.</p>
  </li>
  <li>
    <p>Algorithms: This determines the approach for making trades and it is often dependent on the data.</p>
  </li>
  <li>
    <p>Backtesting: This is an approach to testing how well an algorithm works; the results can influence the decision to deploy an algorithm.</p>
  </li>
  <li>
    <p>A Broker: The broker grants access to doing business in the stock market and places your trades.</p>
  </li>
  <li>
    <p>Capital &amp; Risk Management: Your capital determines how long you can play the game, hence, it is important to stay in it as long as possible by keeping a balance between risk and potential returns.</p>
  </li>
</ul>

<p>So, the short of the story is that these components are interwoven and all need to be properly implemented to have a successful trading system. If you are still interested in learning about these components and my thoughts, you can keep reading.</p>

<h2 id="data-source">Data Source</h2>

<p>The process of trading stocks or other investments is heavily influenced by data, all algorithms or strategies I know of depend on some history of the investment in focus. As a result, data drives the quality of investment decisions. The data needs to come from a trustworthy source, otherwise, you may end up making confident decisions on a weak foundation.</p>

<p>Since data influences how much money is to be made or lost, you can expect that quality data is expensive to access.
Platforms such as the <a href="https://en.wikipedia.org/wiki/Bloomberg_Terminal">Bloomberg Terminal</a> and <a href="https://en.wikipedia.org/wiki/Eikon">Eikon</a> charge lots of money
(in the tens of thousands) to stream their data.
There are also free and cheaper sources such as <a href="https://en.wikipedia.org/wiki/Yahoo!_Finance">Yahoo Finance</a>,
<a href="https://github.com/OpenBB-finance/OpenBBTerminal">OpenBB</a>,
<a href="https://www.ycombinator.com/companies/alpha-vantage">Alpha Vantage</a>,
etc. I used OpenBB in my experiments and I experienced some issues,
however, it was free and I can’t complain much.</p>

<p>There are a couple of factors that should influence your choice to go with a data source. These are:</p>

<ul>
  <li>
    <p><strong>Reliability</strong>: The data source needs to reliably provide data. Sadly, it is not a given that data sources will dependably serve requests. For different reasons, it is not uncommon for the APIs provided by cheap data sources to be broken. In an automated trading system, this can be catastrophic, especially when you have open positions.</p>
  </li>
  <li>
    <p><strong>Frequency</strong>: The frequency of data from the data source determines the kind of algorithms or approaches you take. Some data sources only provide hourly or daily data. If your algorithm requires data as it comes in per minute, but your data source only provides data per hour, this won’t be compatible.</p>
  </li>
  <li>
    <p><strong>Accuracy</strong>: Different data sources may provide varying data prices for the same stock. There are many reasons for these deviations, some include adjusting the prices for dividends, and errors from processing numbers by the data providers. It is hard to tell if the data is accurate as this problem is only visible when a comparison is done. That said, it is important to ensure that the data obtained from your data source is accurate.</p>
  </li>
  <li>
    <p><strong>Promptness</strong>: The stock market is always on the move, hence it is important for the data source to stream data as soon as it becomes available. For example, if the algorithm works on hourly data, but it takes more than an hour to gain access to the data, this information is already stale. As a result, you may be making the wrong decisions acting on such data as though it is current.</p>
  </li>
  <li>
    <p><strong>Market Presence</strong>: The <a href="https://en.wikipedia.org/wiki/Nasdaq">NASDAQ</a> and <a href="https://en.wikipedia.org/wiki/New_York_Stock_Exchange">NYSE</a> are two of the most popular exchanges in the world and many data providers will have data for stocks listed there. However, you may be interested in trading in stocks on other exchanges such as the <a href="https://en.wikipedia.org/wiki/London_Stock_Exchange">London Stock Exchange</a> and face difficulty finding data sources that cater to them. It is also possible to have cases where certain securities are not available despite the exchange being supported.</p>
  </li>
  <li>
    <p><strong>Variety</strong>: When it comes to stock trading, the ticker data is the most common; such ticker data usually includes the stock price, volume, high, and low during a specific period. However, there can be other types of data such as news, social media, earnings reports, industry performance, etc. If you intend to make use of data outside stock prices in making trading decisions, it is important to have a data source for such data.</p>
  </li>
  <li>
    <p><strong>Delistings</strong>: <a href="https://www.investopedia.com/terms/s/survivorshipbias.asp">Survivor’s bias</a> is something to be wary of when building trading systems. The absence of delisted stocks can lead to such a bias. When stocks are delisted, their data is often removed from the index by data providers. The implication of this is that you would never have an idea what patterns lead to stocks being removed from an exchange, and if it happens in the future, there will be a near-zero chance of seeing it coming.</p>
  </li>
</ul>

<p>The factors above are those I experienced while searching for data sources and when making use of <a href="https://github.com/OpenBB-finance/OpenBBTerminal">the sole data source</a> in my side project. Everything relating to the data is crucial as it is the foundation upon which the other components are built. Data influences the algorithms, backtesting, capital management, risk management, and interaction with the broker.</p>

<h2 id="algorithms">Algorithms</h2>

<p>The act of trading stocks primarily involves executing a buy or sell action. You buy when you see patterns that make you believe you can sell at a higher price. A simple naive algorithm could be, buy when the price increases from the last time, and sell when the price decreases from the last time. Simply put, you can put your rules into code.</p>

<p>There are a lot of trading algorithms that have been made popular through academic research, trial and error outside of academia, and experience from trading the stock market manually. While there are different categories of trading algorithms, the two main I am familiar with are:</p>

<ul>
  <li>Momentum</li>
  <li>Mean Reversion</li>
</ul>

<h3 id="momentum">Momentum</h3>

<p>These are algorithms that are based on trends identified in the previous prices of a stock. For example, if the price of a stock keeps rising daily for 3 days, you can probably make a guess that this momentum will carry on for 3 more days, so you can buy at the current price and sell for whatever the price is at after 3 days. <a href="https://www.investopedia.com/trading/introduction-to-momentum-trading/">Momentum algorithms</a> can be way more complex than this, but the main concept is the same for all its derivatives.</p>

<h3 id="mean-reversion">Mean Reversion</h3>
<p>These algorithms put a huge emphasis on the mean price of a security.
The idea of <a href="https://en.wikipedia.org/wiki/Mean_reversion_(finance)">mean reversion</a> is that the price of a stock can move up and down due to many unknown factors
influencing the stock market,
however, the prices will always revert to the mean at some point.
Hence, if the prices are currently lower than the mean,
you can buy the stock and sell when the prices revert to the mean.
On the other hand, you already own a stock and the prices are way above the mean,
you can sell at that price with the expectation that the prices will go down.</p>

<p>Mean reversion and momentum algorithms are often useful for traders who intend to short a stock. Here, shorting implies “borrowing” a stock from a broker and selling it at a price with the expectation that the prices will drop. Then you can buy back the stock when the prices have dropped, return it back to the broker and take the profit. While I do not have an interest in the concept of shorting stocks, I mention this concept here as something that is commonly combined with these algorithms.</p>

<h3 id="machine-learning">Machine Learning</h3>

<p>I am not sure if I should consider machine learning to be a category of trading algorithms,
but adding it as an honourable mention.
Machine learning can be used to improve the accuracy of existing algorithms
and it can also be used to predict buy or sell decisions directly.
Since stock prices take the form of a time-series dataset,
they can serve as data for training a classification or regression algorithm.
When working on this project,
I tried using Linear Regression and XGBoost models to classify time-series inputs into buy or do-not-buy classes.
Outside numeric data, machine learning can also be applied to other kinds of data;
for example, using Natural Language Processing to find the sentiment from news and social media posts.</p>

<p>Still on algorithms, I think the use of indicators can be put in the same category.
Indicators are algorithms that traders often rely on to influence their decisions.
Indicators are a tool for analysis.
There are many <a href="https://www.ig.com/uk/trading-strategies/10-trading-indicators-every-trader-should-know-190604">commonly used indicators</a>,
such as Moving Averages, Relative Strength Index and Bollinger Bands.
I came across <a href="https://github.com/twopirllc/pandas-ta">Pandas-ta</a>
which has a list of 130+ technical indicators and integrates nicely with Pandas dataframes.
There are many other technical analysis libraries out there,
and you can explore them to find something that works for you.
It is important to know what an indicator implies and what it says about the market before acting on its values,
also one single indicator will usually not provide all information needed about the market.</p>

<h2 id="backtesting">Backtesting</h2>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>"Those who have knowledge, don't predict. Those who predict, don't have knowledge."

– Lao Tzu
</code></pre></div></div>
<p>Backtesting is the process of assessing the quality of a trading algorithm or model before pushing it into a live trading environment. When coming up with an algorithm to trade in the stock market, it is common that this involves some modelling of historical data. After coming up with a set of algorithms, it is important to do some testing before picking the suitable ones.</p>

<p>One can choose to not test the algorithms and put them in the real world, trading with real money.
However, this is a naive approach as it means you will lose money and there will be no room for mistakes.
A better way to do this is
to make use of the <a href="https://www.investopedia.com/terms/p/papertrade.asp">paper trading functionality</a>
if your broker supports it;
with this approach, mistakes are not costly as the money lost will not be actual funds.
While paper trading is great, its downside is that it takes time to get results from your evaluation efforts.
You may have to wait months to finally have an idea of how well the algorithm(s) performs.</p>

<p>The right approach to this is to take historical data and split it into three parts: train, validation and test. If you are familiar with machine learning, yes, it is <a href="https://machinelearningmastery.com/train-test-split-for-evaluating-machine-learning-algorithms/">the same data-splitting concept</a>. You should use the train set for study purposes and for formulating the algorithm, then the validation set for seeing how well the algorithm works. If one algorithm does not meet your expectations, you try another by studying the training set and validating again. This cycle continues till you are satisfied and choose the best algorithm from your various experiments.</p>

<p>After multiple cycles of experimentation, you then test your algorithm on the test dataset.
If the algorithm performs poorly,
you have saved yourself the possible heartache of seeing the algorithm fail in a live trading environment.
If it performs well, that’s good news but does not still mean that things can go wrong in a live trading environment,
so it is always advisable to tread with caution.
The reason for not using the test set in the experimentation cycles is
to avoid modifying the algorithm so much that it overfits the test dataset and gives a wrong impression of its true quality.</p>

<p>It is also advisable to still make use of the chosen model first in a paper trading environment for extra validation. One can choose to skip this step if the situation warrants an almost immediate deployment into a live trading environment, however, you should really know what you are doing.</p>

<p>There are two ways to perform backtesting (do let me know if another approach exists):</p>

<ul>
  <li>Vectorized Backtesting</li>
  <li>Event-driven Backtesting</li>
</ul>

<h3 id="vectorized-backtesting">Vectorized Backtesting</h3>

<p>This approach to backtesting involves treating the validation set as a vector, and then making predictions on that set through <a href="https://www.pythonlikeyoumeanit.com/Module3_IntroducingNumpy/VectorizedOperations.html">vectorized operations</a>. The implication of this is that the validation process becomes faster than it would be if you simply looped through each data point; this approach comes in handy when the validation set is large. When trying to understand how vectorized backtesting works, Python’s Numpy library plays a crucial role in providing the capability for running such operations. I would like to think that this is also possible in other languages too.</p>

<p>If you intend to dig deeper, you can check out the chapter on “Mastering Vectorized Backtesting” from the book <a href="https://www.amazon.co.uk/Python-Algorithmic-Trading-Cloud-Deployment/dp/149205335X">Python for Algorithmic Trading</a>.</p>

<h3 id="event-driven-backtesting">Event-driven Backtesting</h3>

<p>Unlike vectorized backtesting, this is easier to understand as it is simply the sequential approach to programming. It also involves an attempt at setting up an environment similar to what you will have when placing an order through a broker such that you can track cash and investment value. When a buy order is placed, cash is reduced and the amount goes into investment value. When a sell order is placed, cash is increased and the amount is removed from investment value.</p>

<p>This approach to testing takes a longer time than vectorized backtesting. However, it has a couple of advantages. One of which is room to model a trading environment as realistically as possible. When backtesting, it is beneficial to simulate scenarios that can differ per trade, this is complex to achieve with vectorized backtesting. Some examples of such include the deduction of <a href="https://www.investopedia.com/terms/c/commission.asp">trade-based commissions</a>, simulation of <a href="https://www.investopedia.com/terms/s/slippage.asp">slippage</a>, integration of leverage into capital, etc. Another advantage of event-driven backtesting is that it does not require access to all the data at once as is the case with vectorized backtesting.</p>

<p>I made use of event-driven backtesting as it was easier to find errors in the algorithms. I believe this is a better approach and one should only resort to vectorized backtesting for optimization purposes. Python’s <a href="https://github.com/mementum/backtrader">Backtrader library</a> is a robust tool that makes event-driven backtesting a breeze.</p>

<h2 id="a-broker">A Broker</h2>

<p>A stockbroker is an entity (company or individual)
that acts as an intermediary between the trading system and the stock market.
The stockbroker places orders as needed and often charges some amount for this service.
There are a lot of platforms out there that serve this purpose such as <a href="https://en.wikipedia.org/wiki/Interactive_Brokers">Interactive Brokers</a>,
<a href="https://en.wikipedia.org/wiki/Fidelity_Investments">Fidelity</a>,
<a href="https://en.wikipedia.org/wiki/Charles_Schwab_Corporation">Charles Schwab</a>,
etc. The Motley Fool provides a <a href="https://www.fool.com/the-ascent/buying-stocks/">list of amazing trading platforms
that serve as brokers</a>.
These platforms usually have a high barrier to entry,
such as having a minimum limit to the amount deposited before making trades.</p>

<p>The bar set by Interactive Brokers did not put me off, as they only had a minimum requirement of about £200. However, my application was rejected. I have reasons to believe that my nationality played a role in this decision. I remember having to tick a box if I was from a small list of “special” countries (sadly, I do not have a screenshot of that page), I may be wrong though.</p>

<p>Like the data source, you do not have control over the broker component as it is usually an external part of the trading set-up. There are also a couple of things to watch out for in a broker:</p>

<ul>
  <li>
    <p><strong>Commission per trade</strong>: You do not want to pay a lot of money per trade if your algorithm requires lots of transactions. Some brokers charge a monthly fee instead. Some brokers do not charge anything whatsoever, but you may be paying for their services somehow through marked-up security prices or slow execution speed.</p>
  </li>
  <li>
    <p><strong>Accuracy of data used by the broker</strong>: If the data relied upon by the broker is erroneous, then such errors will propagate into the actual values of securities when you place an order.</p>
  </li>
  <li>
    <p><strong>Speed of placing trades</strong>: If your algorithm is reliant on trades being executed in the shortest time possible, this becomes an important factor.</p>
  </li>
  <li>
    <p><strong>The availability of paper trading functionality</strong>: The availability of such functionality makes it possible to test your algorithm and see how your trades may perform in a live environment. However, you are not using actual funds in a paper environment.</p>
  </li>
  <li>
    <p><strong>Presence or absence of leverage depending on your preference</strong>: If you are hoping to take advantage of margin in your trading strategy, it is necessary to confirm that the broker offers such services.</p>
  </li>
  <li>
    <p><strong>Availability of an API</strong>: If you intend to place trades automatically, then the broker needs to provide an API so you can place trades through code. Not all brokers have an API, so this is something to watch out for.</p>
  </li>
</ul>

<p>In my side project, I ended up making use of a free trading platform called <a href="https://www.trading212.com/">Trading212</a>.
This was
because I could not find a paid brokerage platform with a straightforward registration process and without massive minimum deposit requirements.
Trading212 does not have a public API,
however,
I spent some time reverse-engineering the APIs used on the web platform and built a custom library for this purpose.</p>

<h2 id="capital--risk-management">Capital &amp; Risk Management</h2>

<p>Capital is the lifeblood of trading securities. You are able to buy only because there is capital, after which you hope that you keep your capital and have returns when you sell. If it happens that you lose all of your capital, the game ends and you will no longer be able to trade, in more catastrophic scenarios you end up in debt.</p>

<p>I did not get to do anything hands-on in relation to this component as I only had in mind to trade with negligible amounts of money, so I was fine with ending up with losses in that scenario. If you ask me, that itself is a form of capital management.</p>

<p>Some of the interesting concepts I came across while learning about capital management are:</p>

<ul>
  <li>Kelly Criterion</li>
  <li>Leverage</li>
</ul>

<h3 id="kelly-criterion">Kelly Criterion</h3>

<p><a href="https://en.wikipedia.org/wiki/Kelly_criterion">Kelly criterion</a> is a portfolio optimization technique that aims to maximize the returns on trades while keeping risk in check. With Kelly criterion, given a number of stocks, you can decide how much to allocate to each. This concept has practical applications in gambling but turned out to be applicable when trading securities.</p>

<p>Here’s the Kelly Criterion formula as applied to trading stocks:</p>

\[f^* = w - \frac{1 - w}{R}\]

<p>Where:</p>

<ul>
  <li>$f^*$ represents the fraction of the capital to be put into a single trade of a stock.</li>
  <li>$w$ is the probability of making a profit or loss based on previous trades of a stock.</li>
  <li>$R$ is the win/loss ratio (i.e., the profit made divided by losses incurred from trading the stock across multiple trades).</li>
</ul>

<p>Kelly criterion has various constraints which I am not covering in this article. One of them is that it tries to maximize returns a little too aggressively, which means more risk, traders with a low-risk appetite tend to make use of a fraction of Kelly criterion. For example, Half Kelly, which is investing half of what the technique proposes.</p>

<p>I did not make use of the Kelly criterion. However, one of the first questions I had when learning about it was: What do you do when you have not made any trades on a stock and as a result have no estimates for profit/loss probability or win/loss ratio?</p>

<p>Some ideas include:</p>

<ul>
  <li>estimating a low-win probability and win/loss ratio</li>
  <li>using a fixed small amount in making the trade until there is sufficient history to rely on for placing the trades.</li>
</ul>

<h3 id="leverage">Leverage</h3>

<p><a href="https://www.ig.com/uk/risk-management/what-is-leverage">Leverage</a> is the use of borrowed capital from a broker for trading securities. The broker usually states the terms of leverage transactions. Some of the terms will be related to when the borrowed funds are expected to be returned, the maximum or minimum to be borrowed, the interest expected when it is being returned, etc.</p>

<p>Say one has a particular stock in mind but does not have enough capital to make that purchase, some brokers provide the capability to go ahead and buy. The borrowed funds will then be returned later. The trader performs this transaction with the hope that profits will be made to return the borrowed funds. However, it is also possible that such a trade can lead to losses, after which the trader still needs to pay back the borrowed amount.</p>

<p>The upside to leverage is that it gives a trader room to make money from nonexistent capital. In the same vane, it means the trader can possibly end up in huge losses and may be unable to pay, considering they did not even have sufficient capital in the first place. I personally have zero interest in leverage.</p>

<p>While capital management is focused on ensuring that you don’t experience losses that wipe out your account, risk management focuses on keeping your losses smaller than your gains. The concepts are similar, but require a slight change in perspective.</p>

<p>Some of the interesting concepts I came across while learning about risk management are:</p>

<ul>
  <li>Risk-free rate</li>
  <li>Volatility</li>
  <li>Drawdown Analysis</li>
</ul>

<h3 id="risk-free-rate">Risk-free rate</h3>

<p>A risk-free rate is the rate of return you get on an investment with zero risk. Investments that are often considered to have a risk-free rate include the US Treasury bill in the United States and Government bonds in the United Kingdom. It is important to state that while it is rare, <a href="https://www.investopedia.com/terms/s/sovereign-default.asp">it is possible for the government to default on its debt</a>.</p>

<p>The way I understand it though, the real value of a risk-free rate is not about the government being able to pay back with profits or not, but that the rate can be used as a benchmark for other investments. For example, if you have £50 to invest in a stock and believe you can earn about 4% in return, but the theoretical risk-free rate is 5%, then you may have to rethink if the potential return is worth the risk of investing your £50. You can instead put this money in an investment with a risk-free rate and not have to worry.</p>

<h3 id="volatility">Volatility</h3>

<p><a href="https://www.investopedia.com/terms/v/volatility.asp">Volatility</a> is a measure of how the price of a security fluctuates. A stock that has prices with lots of huge changes is considered to be highly volatile when compared to one with fewer price movements. The implication is that a highly volatile stock can be risky as it is harder to place a bet on how the price will swing. Traders with less appetite for risk can take high volatility as a signal of an investment being unsuitable for them.</p>

<p>The formula for volatility, typically represented as the standard deviation of returns, can be expressed as follows:</p>

\[\sigma = \sqrt{\frac{1}{N-1} \sum_{i=1}^{N} (R_i - \bar{R})^2}\]

<p>Where:</p>

<ul>
  <li>$\sigma$ is the volatility (standard deviation).</li>
  <li>$N$ is the number of observations (periods).</li>
  <li>$R_i$ is the return in period $i$.</li>
  <li>$\bar{R}$ is the average return over the $N$ periods.</li>
</ul>

<p>There are various arguments on <a href="https://www.advisorperspectives.com/articles/2022/05/23/why-volatility-is-the-wrong-measure-of-investment-risk">why volatility is not a good measure of investment risk</a>. One of them is that since volatility is dependent on standard deviation, it treats upwards movements the same as downward movements. Hence, a stock with lots of positive movements may have similar volatility to a stock with lots of negative movements making it hard to differentiate such nuances.</p>

<h3 id="drawdown-analysis">Drawdown Analysis</h3>

<p>The concept of drawdown introduces two other concepts: peak and trough. Peak is the highest price a security attains in a certain period. Following the peak, the lowest price experienced before the highest price is met again is the trough.</p>

<p><img src="http://res.cloudinary.com/haks/image/upload/v1699747884/HAKSOAT_Blog/building-trading-system/stock-drawdown.png" alt="Graph illustrating Drawdown" class="align-center" /></p>

<p>In the image above, the first peak is around £52, the trough is around £17, and the second peak is around £52.</p>

<p>Now that this is out of the way, drawdown is the ratio of the difference in price between the peak and the trough price to the peak price; this value is then often represented as a percentage i.e., the ratio * 100. In the example above, the drawdown is:</p>

\[\frac{52-17}{52} * 100 = 67\%\]

<p>A drawdown analysis is useful when combined with a backtest as it gives a good picture of the potential experience in a live trading scenario.</p>

<p>Will the trader have the ability to stomach such a drawdown percentage? Can the trader endure a drawdown for such periods? How will the trader handle a situation where the stock never recovers? Is it a good idea to decide what the maximum drawdown is?</p>

<p>I have not applied this knowledge in my side project yet, but it is one of the most interesting concepts I learned about risk management.</p>

<h2 id="final-points">Final Points</h2>

<p>In this article, I discussed some of the components one needs to think about when building a trading system. All of these concepts I learned through reading books and taking a course, all of which I will point out in the <a href="#further-reading">further reading section</a>. I also shared my experiences working with the various concepts. I intend to <a href="https://www.haksoat.com/learning-stock-trading-python/">write more articles about my learnings</a> and they cover some of the components discussed in this article.</p>

<h2 id="further-reading">Further Reading</h2>

<p>Python for Algorithmic Trading: From Idea to Cloud Deployment, <a href="https://www.amazon.co.uk/Python-Algorithmic-Trading-Cloud-Deployment/dp/149205335X">Amazon</a>.</p>

<p>Successful Algorithmic Trading, <a href="https://www.goodreads.com/en/book/show/29005500">Goodreads</a>.</p>

<p>Machine Learning Algorithms for Trading Bootcamp, <a href="https://learning.oreilly.com/live-events/machine-learning-algorithms-for-trading-bootcamp/0636920082023/0636920088138/">Oreilly</a>.</p>]]></content><author><name>Habeeb Shopeju</name><email>shopejuh@gmail.com</email></author><category term="stock-trading-project" /><summary type="html"><![CDATA[A look into the high-level components needed in a trading system.]]></summary></entry></feed>