<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Prabav Murali on Medium]]></title>
        <description><![CDATA[Stories by Prabav Murali on Medium]]></description>
        <link>https://medium.com/@prabavmurali09?source=rss-eb75631f2466------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*nZXtvw4Po3-idHfMh1weXQ.jpeg</url>
            <title>Stories by Prabav Murali on Medium</title>
            <link>https://medium.com/@prabavmurali09?source=rss-eb75631f2466------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 09:36:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@prabavmurali09/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Overthink = Overexplain = Good AI Prompter]]></title>
            <link>https://medium.com/@prabavmurali09/overthink-overexplain-good-ai-prompter-132d11661870?source=rss-eb75631f2466------2</link>
            <guid isPermaLink="false">https://medium.com/p/132d11661870</guid>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Prabav Murali]]></dc:creator>
            <pubDate>Sat, 22 Nov 2025 04:28:23 GMT</pubDate>
            <atom:updated>2025-11-22T04:37:48.502Z</atom:updated>
            <content:encoded><![CDATA[<p>Once, a guy said:</p><p><em>“Do not put down any quality or trait just because you don’t have it. In the future, even overthinking can be a skill.”</em></p><p>That guy? Yep. Me. B|</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*VyK9-SRnTxz8zQ1g9U40Cg.png" /></figure><p>We never imagined a world where we could get answers to almost anything simply by describing how we feel or what we want. Better yet, now we can generate technical information, creative content, or even business ideas just by telling AI what we want to learn in two or three sentences. ChatGPT isn’t the only AI tool anymore — new ones are appearing almost weekly.</p><p>And here’s the kicker: overthinkers have a secret weapon in this brave new AI world — their very own brains are built-in <strong>prompt optimizers</strong>.</p><h3>Overthinkers Are Better at AI Prompts (Because We Think, Therefore We Prompt)</h3><p>It might sound counterintuitive, but in today’s AI era, chronic overthinkers have a secret weapon: <strong>their own brain is a built-in prompt optimizer</strong>. That tiny voice that asks, <em>“</em><strong><em>But what if</em></strong><em>…?”</em> isn’t just nagging — it’s doing the heavy lifting for AI. Ethan Mollick calls interacting with AI “programming with words”. If overthinkers are programming experts in disguise, then every AI prompt is just a gentle nudge from our inner monologue: <em>“Go ahead, make my brain proud, son!”</em></p><h3>The Overthinking Advantage: When “Too Much” Becomes Just Right</h3><p>Overthinkers don’t do things halfway — they take the scenic route in their own minds. Research shows that exploring more possibilities makes people better problem-solvers . Overthinkers naturally mull over scenarios, options, and edge cases, which means when it comes to prompts, <strong>the devil is in the detail..</strong></p><p>Creativity research even notes that the most innovative minds “spend more time deliberately attempting to be creative” . So if you’ve ever spent 20 minutes drafting the perfect question for ChatGPT, congratulations: you’re basically a prompt Picasso, painting with words.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*Uq5sLayIZtPiUierZTWy1A.gif" /><figcaption>Thinking about Overthinking</figcaption></figure><h3>Traits of Effective AI Prompts (And Why Overthinkers Nail Them)</h3><p>The checklist for a great prompt reads like an overthinker’s dream journal:</p><ul><li><strong>Specific and Detailed:</strong> Overthinkers naturally add details because “good enough” is never enough. MIT Sloan recommends including concrete constraints like dates, examples, or parameters. More detail = less guesswork for the AI. Less detail = AI shrug emoji.</li><li><strong>Context-Rich:</strong> Setting the scene changes everything. Telling AI, <em>“You are an experienced wildlife biologist explaining this to a child,”</em> yields a far better response than <em>“Explain wildlife.”</em> Overthinkers live in context — even imagining IKEA-style furniture diagrams in their heads if necessary.</li><li><strong>Role-Play and Scenarios:</strong> Great prompts tell the AI who it is or where it is. Overthinkers are natural scenarists, running mental simulations of every <em>“what if”</em> in life. Ever heard of zero-shot, one-shot, and few-shot learning? It’s basically what we do automatically.</li><li><strong>Step-by-Step (Chain-of-Thought):</strong> IBM research shows that breaking down problems improves results. Overthinkers do this internally anyway; telling AI to do the same just makes it official. It’s like giving your inner monologue a coworker.</li><li><strong>Constraints and Rules:</strong> Overthinkers love rules. Word count, tone, format — this is where we shine. Specifying, <em>“Keep it under 150 words, in a witty tone, using bullet points,”</em> is like giving AI a treasure map. X marks the output.</li></ul><p>In short: overthinkers are detail-happy, scenario-obsessed, step-structured, rule-loving humans. AI prompts? Basically our playground.</p><h3>Overthinking in Action: A Prompt Example</h3><p>A casual user might type: <em>“Write a mission statement for a startup.”</em></p><p>An overthinker will go further:<br> <em>“Imagine you are a branding expert for a five-person biotech startup in urban farming. Draft a clear, inspiring mission statement that specifies the target audience, tone, and core values.”</em></p><p>Notice the difference? One is a whisper; the other is a TED Talk. More context = better output. More detail = less AI guesswork. More <em>“me overthinking”</em> = exactly why we’re awesome at prompts.</p><p>Image prompts follow the same rule. A novice might type <em>“sunny forest,”</em> while an overthinker says:<br> <em>“A sun-dappled forest in early autumn, with golden leaves reflecting on a winding stream, illustrated in Studio Ghibli style, cinematic lighting, vibrant colors, and a hint of morning mist.”</em></p><p>That’s basically the difference between <em>meh</em> and <em>masterpiece.</em></p><h3>The Science of Prompting</h3><p>Prompt design isn’t just art — it’s science. Writing a prompt is “a real-time experiment in human decision-making.” Adding context and rules “steers the model” toward intended answers. Experts even call prompt engineering “the bridge between human intent and machine intelligence.” Overthinkers naturally bring intent, bridges, and maybe a little too much coffee to the table.</p><h3>Tips for the Prompt-Minded (Not an Expert’s Advice)</h3><p><strong>For Overthinkers:</strong> Structure your prompt in layers. Start with context (role, goal, audience), add specifics (tone, examples, constraints), and then let AI do the heavy lifting. Avoid analysis paralysis: if your prompt feels like a novel, break it into bullet points or iterations. Even Shakespeare would’ve appreciated brevity sometimes.</p><p><strong>For Non-Overthinkers:</strong> Don’t panic. You don’t need to draft a Tolstoy-length prompt. Add at least one context or constraint. Iterative prompting works wonders: refine, clarify, adjust tone. Think of it as speed dating with AI — short, but meaningful.</p><p>Remember: If you really want to succeed in AI prompting, practice overthinking. (No, I don’t mean it, its just a throwaway) :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=132d11661870" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Frugal Architect: How to Build AWS Systems Without Burning Your Budget (or Your Brain)]]></title>
            <link>https://medium.com/@prabavmurali09/the-frugal-architect-how-to-build-aws-systems-without-burning-your-budget-or-your-brain-0a1d057a3ea4?source=rss-eb75631f2466------2</link>
            <guid isPermaLink="false">https://medium.com/p/0a1d057a3ea4</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[cloud]]></category>
            <dc:creator><![CDATA[Prabav Murali]]></dc:creator>
            <pubDate>Thu, 18 Sep 2025 08:18:41 GMT</pubDate>
            <atom:updated>2025-09-18T08:51:41.896Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*SzQJj0OoqArWEyUO.gif" /><figcaption>Engineer me on my way to recommend Kubernetes for my 10-users workload</figcaption></figure><p>So.. I actually learnt Cloud by “Watch and learn” method… from someone whom I chose as a mentor. When I attended some cloud architecture sessions in the re:Invent, everything made sense. Architecting is about continuous learning (I mean it), with trying out things also by failing fast, also by checking boxes, also by following best-practices, also by monitoring costs, also by…..</p><p>I’m interested in architecting solutions in the cloud and its about starting small and knowing to visualize how everything fits together.</p><p>When I came across <em>The Frugal Architect </em>recently, I thought: “Finally, someone gets it! Stop over-engineering, start saving brain cycles and AWS dollars.” As an AWS Architect or DevOps engineer, we often fall into the trap of overcomplicating things — multi-region everything, redundant everything, alerting for alerts’ sake. But frugality in architecture is not about being cheap; it’s about <strong>efficient, scalable, and maintainable systems</strong>. Use Lambdas (unless you are forced not to!)</p><p>In this article, we’ll translate the key principles of <em>The Frugal Architect</em> into <strong>AWS and DevOps best practices</strong>, sprinkled with examples and practical tips.</p><h3>1. Keep it Simple, Sherlock</h3><p>The first principle of frugality is simplicity. Extra layers, over-engineered pipelines, and unnecessary microservices might look impressive in a diagram, but they often lead to <strong>technical debt, longer bills, and hair loss</strong>.</p><p><strong>AWS Example:</strong><br>Use API Gateway, Lambdas for that button click that you want to integrate to generate reports with Claude and dropping in S3 buckets? Simple and effective, and yeah definitely frugal.</p><p>(Or)</p><p>You don’t need Kubernetes (EKS) all the time, buddy! Just go with ECS.</p><h3>2. Be Cost-Aware: Don’t Let AWS Bill Shock You</h3><p>Frugal architecture means <strong>thinking about the money while thinking about the system</strong>. AWS gives you all the tools, but you need to read the fine print (or at least glance at it occasionally).</p><p><strong>Practical Tip(s):</strong></p><ul><li>Use <strong>AWS Cost Explorer</strong> to track your spending trends, and send that report to your email?</li><li>Set <strong>AWS Budgets</strong> with alerts to avoid unnecessary surprises.</li><li><strong>Compute Optimizer</strong> will help you right-size EC2 instances. (You dont want that <strong>m7a.xlarge</strong> all the time)</li><li>For variable workloads, use Spot Instances (with interruption handling) or AWS Batch for batch-heavy jobs. Use Lambda for event-driven spiky workloads..</li><li>Example: Migrating a batch process from an <strong>m5.large EC2</strong> to <strong>Lambda with S3 triggers</strong> can save hundreds monthly — without a single punchline lost.</li><li>Use tag-based scheduling of instances that you are running so that it can be stopped when not used/off-business hours.</li></ul><p><strong>P.S:</strong> “Don’t lambda your wallet away; serverless is cheaper but not free.”</p><h3>3. Resilience Without Redundancy Waste</h3><p>Redundancy is essential for reliability — but <strong>frugal architects don’t throw money at every failure scenario</strong>.</p><p><strong>AWS Implementation:</strong></p><ul><li><strong>Amazon RDS Multi-AZ</strong> gives you high availability without manually maintaining standby servers.</li><li><strong>S3 with versioning and lifecycle rules</strong> ensures durability without paying for over-provisioned storage.</li><li><strong>CloudWatch alarms</strong> for real issues, not for every minor hiccup, keep your mental health intact.</li></ul><p><strong>Pun:</strong> “Redundancy is like insurance — necessary, but overkill can bankrupt you faster than a lambda cold start.”</p><h3>4. Iterative Design: Don’t Bet the Farm on Day One!</h3><p>Start small. Scale as needed. Measure. Optimize. Repeat.</p><p><strong>Case Study:</strong><br> Imagine building a serverless web application:</p><ul><li><strong>Before (over-engineered):</strong> EC2 fleet, manual load balancer, complex CI/CD, manual backups.</li><li><strong>After (frugal):</strong> Lambda functions, API Gateway, DynamoDB, S3 for static content, CI/CD with Jenkins/Codepipeline</li></ul><p>Not only is the “After” scenario cheaper, but it’s also <strong>easier to maintain and faster to iterate</strong>. It’s like moving from a typewriter to an IDE — productivity skyrockets.</p><p><strong>Tip:</strong> Keep monitoring costs and performance. AWS Trusted Advisor can be your BFF here.</p><h3>5. Practical Tips for Budding Architects/DevOps Engineers</h3><ol><li><strong>Measure before optimizing:</strong> Don’t guess — monitor.</li><li><strong>Managed services &gt; DIY:</strong> Use AWS-managed solutions whenever possible.</li><li><strong>Event-driven architecture for unpredictable workloads:</strong> AWS Lambda, SQS, SNS.</li><li><strong>Automate smartly:</strong> CI/CD pipelines are great, but don’t over-engineer them.</li></ol><p><strong>Pun:</strong> “Automate, but don’t over-automate; otherwise, you’ll spend more time debugging pipelines than deploying features.”</p><h3>Conclusion</h3><p>Being a frugal architect isn’t about being cheap — it’s about <strong>smart, efficient, and resilient design</strong>. If you’re an AWS Architect or DevOps engineer, adopting these principles can <strong>save costs, reduce complexity, and make your architecture truly scalable</strong>.</p><p>Remember: The goal is not to build the most complicated system; it’s to build the system that <strong>actually works and is easy to maintain.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0a1d057a3ea4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Wanna build your AI model with RAG? This is how I built mine.]]></title>
            <link>https://ai.plainenglish.io/wanna-build-your-ai-model-with-rag-this-is-how-i-built-mine-4ef68d0f0dfa?source=rss-eb75631f2466------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ef68d0f0dfa</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Prabav Murali]]></dc:creator>
            <pubDate>Tue, 08 Jul 2025 00:28:05 GMT</pubDate>
            <atom:updated>2025-07-11T15:13:38.370Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>A bit about “Why I did it?”</strong></p><p>When I started my Machine Learning journey back in 2019, I thought AI was too far away from everyday life. All people knew was the chess game they played on the computer, or probably the robots that labs built. All people started with Linear Regression, then moved on to Random Forest. Anywhere and everywhere was a Random Forest classification. But yeah, it is a great model. I agree.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kQuToOBh-VLN63htQ2XCAA.png" /><figcaption>AI generated image</figcaption></figure><p>But my journey did not stagnate there. I began my Master’s journey to dive deep into ML, and that’s when I discovered that math and statistics played a paramount role. Oh man! Did I underestimate it? Absolutely not. In fact, it was great to learn different kinds of algorithms, methods, and problem-solving techniques. At that time, I thought BERT (Bidirectional Encoder Representations from Transformers) was the most superior model among other techniques and that we could create chatbots easily with it. And then I studied GPT (Generative Pre-trained Transformers). It blew me away! The former is an encoder-only model, while the latter is a decoder-only model. Meaning — Encoder models understands the input and patterns and gives a prediction (Doesn’t generate any output) which makes it useful for text classification etc., but a Decoder model on the other hand, generates an output step-by-step based on the previous tokens. Now, we are talking!</p><p>That is where my boy ChatGPT comes into the picture. ChatGPT changed everything. I repeat — everything! Now, almost everyone has AI at their fingertips. Just ask a question to ChatGPT and you can solve any kind of problem. Some people even ask life-based questions. I’m part of that “some” sometimes :D</p><p>We are evolving as rapidly as we can, and it is important to adapt to it. So let me make it quick, aye?</p><p>ChatGPT is trained on so much web content and all kinds of information, and it is so powerful that it needs approximately US$700,000 per day for operations.</p><p>So I wanted to research how to build my own model using a favorite book of mine.</p><ul><li>So I built a character-level tokenizer to train my custom GPT model on a book.</li><li>Trained on the book <em>Ikigai</em>.</li><li>Created a custom GPT model with Rotary Positional Embeddings (RoPE). The custom GPT acts like a style-and-knowledge expert, while the retriever acts like a fact-checker pulling exact text.</li><li>Searches relevant passages with FAISS vector search (RAG-based approach to bridge the gap).</li><li>Generates answers locally with Ollama and Llama 3.</li></ul><p>In this post, I will explain how each piece works, along with practical insights to help you build your own custom knowledge LLMs.</p><p><em>I did not use the OpenAI wrapper</em> :P</p><p><strong>Challenges I had</strong>:</p><ul><li>LLMs like GPT-4 sometimes “make up” answers.</li><li>They don’t remember entire books unless you feed them all the context at once.</li></ul><p><strong>The Solution</strong>:</p><ul><li>Use RAG (Retrieval-Augmented Generation) — search for relevant text, then feed that to your LLM.</li><li>So, I combined both together.Fine-tune your own GPT so it “speaks” in the style you want.</li><li>Use RoPE embeddings to handle longer context windows naturally.</li><li>Run everything locally using Ollama, so your data stays yours.</li></ul><p>Custom Tokenizer: CharTokenizer<br> What it does:</p><ul><li>Splits your text into characters.</li><li>Maps each char to an index.</li><li>Adds an [UNK] token for unknown chars.</li><li>Saves your vocab to avoid token size mismatches later.</li></ul><pre>class CharTokenizer:<br>    def __init__(self, text):<br>        chars = sorted(list(set(text)))<br>        self.vocab = [&#39;[UNK]&#39;] + chars<br>        self.stoi = {ch: i+1 for i, ch in enumerate(chars)}<br>        self.stoi[&#39;[UNK]&#39;] = 0<br>        self.itos = {i: ch for ch, i in self.stoi.items()}<br><br>        self.vocab_size = len(self.vocab)<br><br>    def encode(self, s):<br>        return [self.stoi.get(ch, 0) for ch in s]<br><br>    def decode(self, l):<br>        return &#39;&#39;.join([self.itos.get(i, &#39;[UNK]&#39;) for i in l])</pre><p>Why this matters:</p><ul><li>Keeps your GPT’s input consistent with your training data</li><li>Simpler than BPE for small text sets.<br> Learn more: <a href="https://huggingface.co/docs/tokenizers/en/index">https://huggingface.co/docs/tokenizers/en/index</a></li></ul><p><strong>Training the GPT: (train.py)</strong></p><p>I fine-tuned my GPT on <em>Ikigai</em> using PyTorch.</p><p><strong>Choices made:</strong></p><ul><li>block_size = 128 → How many tokens your model “sees” at once.</li><li>n_embd = 256 → Embedding size, balances detail vs. compute.</li><li>n_head = 4 → Number of attention heads.</li><li>n_layer = 4 → Transformer layers depth.</li><li>AdamW → Good optimizer for language models</li></ul><p><strong>Why RoPE?</strong><br><strong>Rotary Positional Embeddings (RoPE)</strong> outperform classic sinusoidal embeddings for transformers. Why? Because:</p><ul><li>They encode relative position instead of absolute by adding a rotation angle (theta θ) to a token, whereas sinusoidal embeddings are absolute.</li><li>They generalize better for longer context windows. They’re popularly used in Llama models.</li></ul><p>Example: “Live to eat” and “Eat to live” have two different meanings, right? (I do both) But imagine a two-dimensional word vector for “Live.” To encode its position in a sentence, RoPE rotates its vector. The angle of rotation (θ) is proportional to the word’s position in the sentence.</p><p><strong>Why Causal Self-attention and MoE?</strong></p><p>Causal self-attention ensures the model uses preceding tokens to train and not the succeeding ones — otherwise, the model could “cheat” by looking at future tokens for prediction.</p><p>MoE (Mixture of Experts) is a popular model implemented by DeepSeek to train models at the lowest cost. A gating mechanism dynamically chooses which expert to activate, allowing the model to perform different expert-based tasks with less computation. [Refer to: <a href="https://milvus.io/ai-quick-reference/how-does-the-deepseekmoe-model-work">https://milvus.io/ai-quick-reference/how-does-the-deepseekmoe-model-work</a> ]</p><p>Read more: <a href="https://arxiv.org/abs/2104.09864">https://arxiv.org/abs/2104.09864</a></p><pre>class RotaryEmbedding(nn.Module):<br>    def __init__(self, dim):<br>        super().__init__()<br>        inv_freq = 1.0 / (10000 ** (torch.arange(0, dim, 2).float() / dim))<br>        self.register_buffer(&quot;inv_freq&quot;, inv_freq)<br><br>    def forward(self, seq_len, device):<br>        t = torch.arange(seq_len, device=device).type_as(self.inv_freq)<br>        freqs = torch.einsum(&quot;i,j-&gt;ij&quot;, t, self.inv_freq)<br>        emb = torch.cat((freqs.sin(), freqs.cos()), dim=-1)<br>        return emb<br>class CausalSelfAttention(nn.Module):<br>    def __init__(self, config):<br>        super().__init__()<br>        assert config.n_embd % config.n_head == 0<br>        self.n_head = config.n_head<br>        self.head_dim = config.n_embd // config.n_head<br>        self.scale = 1 / math.sqrt(self.head_dim)<br><br>        self.key = nn.Linear(config.n_embd, config.n_embd)<br>        self.query = nn.Linear(config.n_embd, config.n_embd)<br>        self.value = nn.Linear(config.n_embd, config.n_embd)<br>        self.proj = nn.Linear(config.n_embd, config.n_embd)<br>        self.dropout = nn.Dropout(0.1)<br><br>        self.rotary_emb = RotaryEmbedding(self.head_dim)<br><br>    def forward(self, x):<br>        B, T, C = x.size()<br>        nh, hd = self.n_head, self.head_dim<br><br>        q = self.query(x).view(B, T, nh, hd).transpose(1, 2)<br>        k = self.key(x).view(B, T, nh, hd).transpose(1, 2)<br>        v = self.value(x).view(B, T, nh, hd).transpose(1, 2)<br><br>        sincos = self.rotary_emb(T, x.device)<br>        sincos = sincos.unsqueeze(0).unsqueeze(0)<br>        sin, cos = sincos[..., :hd//2], sincos[..., hd//2:]<br>        sin = torch.repeat_interleave(sin, 2, dim=-1)<br>        cos = torch.repeat_interleave(cos, 2, dim=-1)<br><br>        print(&quot;q shape&quot;, q.shape)<br>        print(&quot;sin shape&quot;, sin.shape)<br><br>        # print(&quot;q:&quot;, q.shape)<br>        # print(&quot;sin:&quot;, sin.shape)<br><br>        q, k = apply_rotary_pos_emb(q, k, sin, cos)<br><br>        att = (q @ k.transpose(-2, -1)) * self.scale<br><br>        mask = torch.tril(torch.ones(T, T, device=x.device)).unsqueeze(0).unsqueeze(0)<br>        att = att.masked_fill(mask == 0, float(&quot;-inf&quot;))<br><br>        att = F.softmax(att, dim=-1)<br>        att = self.dropout(att)<br><br>        y = att @ v<br>        y = y.transpose(1, 2).contiguous().view(B, T, C)<br><br>        return self.proj(y)<br><br>class MoE(nn.Module):<br>    def __init__(self, dim, num_experts=4, k=2):<br>        super().__init__()<br>        self.num_experts = num_experts<br>        self.k = k<br>        self.experts = nn.ModuleList([nn.Sequential(<br>            nn.Linear(dim, 4*dim),<br>            nn.GELU(),<br>            nn.Linear(4*dim, dim)<br>        ) for _ in range(num_experts)])<br>        self.gate = nn.Linear(dim, num_experts)<br><br>    def forward(self, x):<br>        B, T, C = x.size()<br>        x_flat = x.view(B*T, C)<br>        gate_logits = self.gate(x_flat)<br>        topk_vals, topk_idx = torch.topk(gate_logits, self.k, dim=1)<br>        topk_scores = F.softmax(topk_vals, dim=1)<br><br>        expert_outputs = torch.zeros_like(x_flat)<br>        for i in range(self.k):<br>            mask = (topk_idx[:, i].unsqueeze(1) == torch.arange(self.num_experts).to(x.device)).float()<br>            expert_input = x_flat * mask.sum(dim=1, keepdim=True)<br>            expert_out = torch.stack([self.experts[idx](x_flat[j]) for j, idx in enumerate(topk_idx[:, i])])<br>            expert_outputs += expert_out * topk_scores[:, i].unsqueeze(1)<br><br>        return expert_outputs.view(B, T, C)</pre><p><strong>Semantic Search: FAISS</strong><br><em>Why does retrieval matter?</em><br>Instead of prompting the LLM with your whole book, I used an embedder to find relevant chunks.</p><p><strong>How I did it:</strong></p><ul><li>I used Sentence Transformers to turn text into vectors.</li><li>Used <strong>IndexFlatL2</strong> (L2 Euclidean distance-based search) for fast vector search.</li></ul><pre>import torch<br>from torch.utils.data import Dataset, DataLoader<br>from tokenizer import CharTokenizer<br>from model import GPT, GPTConfig<br>import pickle as pkl<br><br>with open(&quot;Ikigai.txt&quot;, &quot;r&quot;, encoding=&quot;utf-8&quot;) as f:<br>    text = f.read()<br><br>tokenizer = CharTokenizer(text)<br><br>data = torch.tensor(tokenizer.encode(text), dtype=torch.long)<br><br>class TextDataset(Dataset):<br>    def __init__(self, data, block_size):<br>        self.data = data<br>        self.block_size = block_size<br>    def __len__(self):<br>        return len(self.data) - self.block_size<br>    def __getitem__(self, idx):<br>        x = self.data[idx : idx + self.block_size]<br>        y = self.data[idx + 1 : idx + self.block_size + 1]<br>        return x, y<br><br>block_size = 128<br>batch_size = 32<br>device = &#39;cuda&#39; if torch.cuda.is_available() else &#39;cpu&#39;<br><br>dataset = TextDataset(data, block_size)<br>loader = DataLoader(dataset, batch_size=batch_size, shuffle=True)<br><br>config = GPTConfig(<br>    vocab_size=tokenizer.vocab_size,<br>    block_size=block_size,<br>    n_embd=256,<br>    n_head=4,<br>    n_layer=4,<br>    use_moe=False<br>)<br><br>model = GPT(config).to(device)<br>optimizer = torch.optim.AdamW(model.parameters(), lr=3e-4)<br><br>for epoch in range(5):<br>    model.train()<br>    total_loss = 0.0<br>    count = 0<br>    for x, y in loader:<br>        x, y = x.to(device), y.to(device)<br>        logits, loss = model(x, y)<br>        optimizer.zero_grad()<br>        loss.backward()<br>        optimizer.step()<br>        total_loss += loss.item()<br>        count += 1<br>    avg_loss = total_loss / count<br>    print(f&quot;Epoch {epoch + 1} Loss: {avg_loss:.4f}&quot;)<br><br>torch.save(model.state_dict(), &quot;/CustomGPT/custom_gpt_full.pt&quot;)<br>print(&quot;Training complete, yayyy!&quot;)<br><br>with open(&quot;/CustomGPT/tokenizer.pkl&quot;, &quot;wb&quot;) as f:<br>    pkl.dump(tokenizer, f)<br>print(&quot;Tokenizer saved, yayyy!&quot;)</pre><p><strong>Why FAISS over keyword search?</strong></p><p>Dense semantic embeddings capture meaning, while BM25 or classic search only match words, not ideas.</p><p>Learn more: <a href="https://engineering.fb.com/2017/03/29/data-infrastructure/faiss-a-library-for-efficient-similarity-search/">FAISS by Facebook</a></p><p><strong>Generating Answers: Ollama</strong><br> <strong>What is Ollama?</strong></p><p>A tool for running LLMs locally with a simple ollama run llama3 command.</p><p>It means your data stays local, and you can experiment with different open weights.</p><p><strong>How I call it?</strong></p><pre>embedder = SentenceTransformer(&#39;all-MiniLM-L6-v2&#39;) #Simple right?<br><br>def chunk_text(text, chunk_size=500, overlap=50):<br>    words = text.split()<br>    chunks = []<br>    for i in range(0, len(words), chunk_size - overlap):<br>        chunk = &quot; &quot;.join(words[i:i+chunk_size])<br>        chunks.append(chunk)<br>    return chunks<br><br>chunks = chunk_text(book_text)<br>chunk_embeddings = embedder.encode(chunks, convert_to_numpy=True)<br><br>dimension = chunk_embeddings.shape[1]<br>index = faiss.IndexFlatL2(dimension)<br>index.add(chunk_embeddings)<br><br>def retrieve(query, top_k=3):<br>    q_emb = embedder.encode([query])<br>    distances, indices = index.search(q_emb, top_k)<br>    return [chunks[i] for i in indices[0]]<br><br>def generate_with_ollama(prompt):<br>    process = subprocess.Popen(<br>        [&quot;ollama&quot;, &quot;run&quot;, &quot;llama3&quot;],<br>        stdin=subprocess.PIPE,<br>        stdout=subprocess.PIPE,<br>        stderr=subprocess.PIPE,<br>        text=True<br>    )<br>    stdout, stderr = process.communicate(input=prompt)<br><br>    if process.returncode != 0:<br>        print(&quot;Error:&quot;, stderr)<br>        return &quot;Error generating answer&quot;<br><br>    return stdout.strip()</pre><p><strong><em>P.S: If you get an [ERROR] like - ollama not responding or app not found, install ollama and pull with command: ollama pull llama3 and also run ollama serve</em></strong></p><p><strong>Why not OpenAI API call?</strong></p><ul><li>Because I wanted to try :D</li></ul><p><strong>A Chat UI?</strong></p><p>You have a lot of options for a chat interface from Gradio to Streamlit to Librechat etc. I have used <strong>Streamlit</strong> as it is easy to configure and run as an app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x9lgGbP4dq52d9Sy3ltKVg.png" /></figure><p><strong>TLDR; [Just have code snippets in the blog for understanding]</strong></p><ol><li>In the Streamlit app chat UI, the user asks: “What is Ikigai?”</li><li>The embedder searches the top 3 relevant book chunks.</li><li>These chunks form the context.</li><li>Context + question = new prompt.</li><li>Ollama runs the LLM and generates the answer.</li></ol><p><strong>What will I do next?</strong></p><ul><li>Experiment with larger embedding models like BGE Large.</li><li>Try multi-lingual tokenizers like SentencePiece.</li><li>Explore LoRA fine-tuning on your Ollama model for even more personalization.</li></ul><p><strong>Final Thoughts</strong></p><p>Combining <strong>RAG</strong> with a Custom GPT and RoPE helped me turn a static book into a dynamic, factual Q&amp;A system. The best part? Everything runs on my machine.</p><p><strong>Let’s Connect!</strong></p><p>If you enjoyed this, follow me on Medium! Let’s stay connected!</p><h3>Thank you for being a part of the community</h3><p><em>Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/@InPlainEnglish"><strong>YouTube</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a> | <a href="https://twitch.tv/inplainenglish"><strong>Twitch</strong></a></li><li><a href="https://differ.blog/"><strong>Start your own free AI-powered blog on Differ</strong></a> 🚀</li><li><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Join our content creators community on Discord</strong></a> 🧑🏻‍💻</li><li>For more content, visit <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> + <a href="https://stackademic.com/"><strong>stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ef68d0f0dfa" width="1" height="1" alt=""><hr><p><a href="https://ai.plainenglish.io/wanna-build-your-ai-model-with-rag-this-is-how-i-built-mine-4ef68d0f0dfa">Wanna build your AI model with RAG? This is how I built mine.</a> was originally published in <a href="https://ai.plainenglish.io/">Artificial Intelligence in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Buffett and the Bubble of US Stock Markets: In depth Analysis]]></title>
            <link>https://medium.com/@prabavmurali09/buffett-and-the-bubble-of-us-stock-markets-in-depth-analysis-1bcca1b05751?source=rss-eb75631f2466------2</link>
            <guid isPermaLink="false">https://medium.com/p/1bcca1b05751</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[usa]]></category>
            <category><![CDATA[warren-buffett]]></category>
            <category><![CDATA[stock-market]]></category>
            <dc:creator><![CDATA[Prabav Murali]]></dc:creator>
            <pubDate>Tue, 18 Feb 2025 05:36:35 GMT</pubDate>
            <atom:updated>2025-02-18T06:09:48.864Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Money Game:</h3><p>“<em>No one knows how stock markets function, but all we know is our money compounds over time</em>”. Can anyone actually predict the stock market performance? I don’t think so. Let me know if you can. Day to day performance of stock markets and economies depends on so many variables, and to understand some of the important ones, we need to get to the basics of capital markets. But before diving into that, let us look at the definition of Economy!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rCumSNOdtTZi_CATqjF4Yg.png" /><figcaption><strong><em>Image generated using AI</em></strong></figcaption></figure><p>To explain in simple terms, the design of a country’s economy plays a paramount role in bringing food to your table. How? There is a term called <strong>GDP (Gross Domestic Product) </strong>which all of us would have studied in our academia. GDP is nothing but [consumer spending + business investment + government spending + net exports]. In simple terms, it is the production of goods and services by a country in a specific period of time. A stronger GDP translates to a stronger economy which attracts more FDI (Foreign Direct Investments), more business growth indicating a high growth potential of the country. The GDP of US now stands at US$ 29 Trillion with a per capita income of US$ 81,695.19 (2023) approximately.</p><p>The United States of America began liberalizing their economy in the early 1930s and post WW2 era making them an open market to do businesses. Below image shows ease of doing business by countries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*Jnil2EY6a4xZPIWd.png" /><figcaption>Image from <a href="https://researchfdi.com/ease-of-doing-business-in-the-u-s-a-major-draw-for-foreign-investor/">https://researchfdi.com/ease-of-doing-business-in-the-u-s-a-major-draw-for-foreign-investor/</a></figcaption></figure><p>But why did the US dollar become the default currency for trade? The US dollar became the official reserve currency in 1944, delegated by 44 allied countries called the Bretton Woods Agreement. Before World War II, the United States served as the Allies’ supplier of weapons and other goods. Most countries paid in gold, making the US the owner of a majority of gold by the end of the war. A return to the gold standard became impossible as countries depleted their reserves. Delegates from 44 Allied countries met in Bretton Wood, New Hampshire, in 1944 to develop a system to manage <a href="https://www.investopedia.com/terms/f/foreign-exchange.asp">f</a>oreign exchange that would not disadvantage any country. The delegation decided that the world’s currencies would no longer be linked to gold but peggedto the US dollar. [<em>Source: </em><a href="https://www.investopedia.com/articles/forex-currencies/092316/how-us-dollar-became-worlds-reserve-currency.asp"><em>https://www.investopedia.com/articles/forex-currencies/092316/how-us-dollar-became-worlds-reserve-currency.asp</em></a>]</p><p>The US economy and its stock market are some of the most scrutinized markets in the world. With economic cycles that span decades and markets that oscillate between periods of boom and bust, understanding the fundamentals is critical for long-term investors or even short-term investors to make profits. Among all the investors, there is one “<strong>Big</strong> <strong>Bull</strong>” investor called <strong>Warren Buffett</strong>. Buffett is the Chair person of a conglomerate called Berkshire Hathaway. He is one of the most famous and successful investors there is in the entire stock market. In 2001, Buffett proposed a term called “Buffett Indicator” which is used to identify the stock market’s valuation and performance at any point of time.</p><p>In this article, I present a detailed analysis of the US economy, stock market performance, and the Buffett Indicator. Using Python, I’ve conducted a thorough investigation of historical trends, key economic data, and how the Buffett Indicator can help us understand current market conditions. The analysis combines macroeconomic indicators, stock market performance, and valuation metrics, giving investors a comprehensive understanding of where the market might be heading.</p><h3>Let us understand the US Economy!</h3><p>Before we delve into the stock market, it’s essential to understand the macroeconomic backdrop. The US economy is a complex system driven by consumer spending, government policies, trade, and capital formation. Here, we’ll review some of the most important economic indicators:</p><h4>Some of the economic indicators</h4><ul><li><strong>GDP</strong>: The Gross Domestic Product (GDP) is a key indicator of a country’s economic health. It measures the total market value of all goods and services produced within a country. A negative GDP growth for two consecutive quarters indicates a country in recession.</li><li><strong>PCE (Personal Consumer Expenditures): </strong>PCE is a measure of how much the American residents spend on goods and services. It’s an important indicator of consumer spending and a country’s economic growth.</li><li><strong>S&amp;P500: </strong>The Standard and Poor’s 500, or simply the S&amp;P 500, is a stock market index tracking the stock performance of 500 of the largest companies listed on stock exchanges in the United States [<em>Source: </em><a href="https://en.wikipedia.org/wiki/S%26P_500"><em>Wikipedia</em></a>]</li><li><strong>Bond Return/Yield: </strong>A bond’s yield is the return an investor receives on a bond, which is based on the interest payments and principal. It’s a summary of the overall return on the investment. [<em>Source: </em><a href="https://www.investopedia.com/terms/b/bond-yield.asp#:~:text=A%20bond%20yield%20is%20the,up%2C%20its%20yield%20goes%20down"><em>https://www.investopedia.com/terms/b/bond-yield.asp#:~:text=A%20bond%20yield%20is%20the,up%2C%20its%20yield%20goes%20down</em></a><em>.</em>]</li><li><strong>Federal Reserve Interest Rates</strong>: The Federal Reserve’s decisions on interest rates influence borrowing costs, consumer spending, and investment in the economy.</li></ul><h4>Let’s get into the Analysis part now:</h4><p>By analyzing these datasets, we can observe trends and make predictions about future economic performance. I collected all the data from different sources like trading economics and yfinance etc.</p><pre>#!pip install plotly_express yfinance<br>import matplotlib.pyplot as plt<br>import yfinance as yf</pre><pre>import pandas as pd # &lt;&lt;&lt;&lt;&lt;&lt;------ Importing this late to prove I&#39;m different than other data people!(Should I feel proud?)<br>import numpy as np<br>import seaborn as sns<br>import plotly.graph_objects as go<br>import plotly.express as px</pre><pre>import os<br>import warnings</pre><pre>warnings.filterwarnings(action=&#39;ignore&#39;)</pre><pre>us_gdp = pd.read_csv(&#39;US-GDP.csv&#39;)<br>pce = pd.read_csv(&#39;US-PCE.csv&#39;)<br>bofa_bondret = pd.read_csv(&#39;BofA-HighYield-Bondreturns-1988-2025.csv&#39;)<br>us_dttogdp = pd.read_csv(&#39;US-Debt-to_GDP.csv&#39;)<br>fedintrate = pd.read_csv(&#39;fed-funds-rate-historical-chart.csv&#39;)<br>buffind = pd.read_csv(&#39;Wilshire5000toGDP.csv&#39;)</pre><pre>display(us_gdp.head())</pre><pre>print(us_gdp.isna().sum())</pre><pre>gdpline = px.line(us_gdp, x=us_gdp[&#39;observation_date&#39;], y=us_gdp[&#39;GDP&#39;], template=&#39;plotly_dark&#39;, width=1100) # I like dark theme</pre><pre>gdpline</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O5NWkdh_gA3RUggL6xj0zQ.png" /></figure><pre>display(pce.head())</pre><pre>print(pce.isna().sum())</pre><pre>pceline = px.line(pce, x=pce[&#39;observation_date&#39;], y=pce[&#39;PCECTPI&#39;], template=&#39;plotly_dark&#39;, width=1100)</pre><pre>pceline #PCE is the Personal Consumer Expenditure which you can see has grown along with the GDP which is usual</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8Cvc_rHu0zuV1U_0OmzuDw.png" /></figure><pre>print(us_dttogdp.isna().sum())</pre><pre>dbgdp_line = px.line(us_dttogdp, x=us_dttogdp[&#39;observation_date&#39;], y=us_dttogdp[&#39;GFDEGDQ188S&#39;], template=&#39;plotly_dark&#39;, width=1100) # I like dark theme</pre><pre>dbgdp_line</pre><pre>## We can notice the Debt to GDP line increasing for a brief period in 2020 due to Covid...</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NFcxTH7AQl9GJEeYDmRHkA.png" /></figure><pre>bofa_bondret = bofa_bondret.rename(columns={&#39;BAMLHYH0A0HYM2TRIV&#39;: &#39;HYBondReturns&#39;})</pre><pre>## If you see the data, it has some NaN (Null values). Let&#39;s clean it up!</pre><pre>display(bofa_bondret.isna().sum()) ## There are 1118 null values and lets where they are...</pre><pre>bofa_bondret = bofa_bondret.dropna().reset_index()</pre><pre>display(bofa_bondret.head())</pre><pre>bndret_line = px.line(bofa_bondret, x=bofa_bondret[&#39;observation_date&#39;], y=bofa_bondret[&#39;HYBondReturns&#39;], template=&#39;plotly_dark&#39;, width=1100)</pre><pre>bndret_line</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZDw6wxjpWV992mb3A3ZB5A.png" /></figure><pre>fedintrate.info()</pre><pre>fedintrate.dropna(inplace=True)</pre><pre>fedintrate.head()</pre><pre>fedintrate[&#39;Date&#39;] = pd.to_datetime(fedintrate[&#39;Date&#39;], dayfirst=True, errors=&#39;coerce&#39;)</pre><pre>fedintrate.set_index(&#39;Date&#39;, inplace=True)</pre><pre>monthly_fint = fedintrate.resample(&#39;M&#39;).mean()</pre><pre>monthly_fint.reset_index(inplace=True)</pre><pre>monthly_fint.head()</pre><pre>fig = px.line(monthly_fint, x=&#39;Date&#39;, y=&#39;Value&#39;, title=&quot;Fed Monthly Average Interest Rate (1954-2025)&quot;)</pre><pre>fig.update_layout(xaxis_title=&quot;Year&quot;, yaxis_title=&quot;Interest Rate (%)&quot;, hovermode=&quot;x unified&quot;, template=&#39;plotly_dark&#39;)</pre><pre>fig.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-0vWjBhiTkVfZVzSj9fmOw.png" /></figure><p>This code can be extended to other economic indicators like unemployment rate and inflation, with similar data fetching and visualization techniques.</p><h3>Let’s see what the Fear and Greed index is…</h3><p>Fear and Greed index is a market sentiment indicator operating on different factors with respect to the stock market like Stock strength, S&amp;P500 Market momentum etc. It has 5 signals: Extreme Greed, Greed, Neutral, Fear and Extreme Fear. It will give an understanding of how people perceive stock market is for buying/selling stocks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YMvpJaTkltD-ZbTM5WqBCg.png" /><figcaption>Image source: <a href="https://www.cnn.com/markets/fear-and-greed">https://www.cnn.com/markets/fear-and-greed</a></figcaption></figure><pre>spstock = yf.Ticker(&quot;^GSPC&quot;).history(period=&quot;6y&quot;) # Let&#39;s take 6 years of data to analyze pre-covid data too...</pre><pre>display(spstock.head())</pre><pre>spstock.drop(columns=[&#39;Dividends&#39;, &#39;Stock Splits&#39;], inplace=True)</pre><pre>spstock = spstock.reset_index()<br>display(spstock.tail())</pre><p>We take the moving averages of the S&amp;P500 stocks for 50 days and 200 days. Typically, this is the number of days usually considered by traders to identify the bearish and bullish trends. A 50-day Moving Average (MA) usually depicts the resistance level whereas 200 days is usually for analyzing the overall market trend.</p><p>One important trend to infer from the graph below would be if the 50 day MA goes above the 200 day MA, it indicates a Bullish market (Golden Cross) whereas if the 50-day MA goes below the 200-day MA, it indicates a Bearish market (Death Cross)</p><pre>spstock[&#39;50ma&#39;] = spstock[&#39;Close&#39;].rolling(window=50).mean()</pre><pre>spstock[&#39;200ma&#39;] = spstock[&#39;Close&#39;].rolling(window=200).mean()</pre><pre>spstock_melted = spstock.melt(id_vars=[&#39;Date&#39;], value_vars=[&#39;Close&#39;, &#39;50ma&#39;, &#39;200ma&#39;],<br>                        var_name=&#39;Type&#39;, value_name=&#39;Price&#39;)</pre><pre># We do melting to convert the dataframe from wide to long format keeping one or more columns as identifiers...</pre><pre>fig = px.line(spstock_melted, x=&#39;Date&#39;, y=&#39;Price&#39;, color=&#39;Type&#39;,<br>              title=&quot;S&amp;P500 Closing Price with 50-day and 200-day Moving Averages&quot;, template=&#39;plotly_dark&#39;)</pre><pre>fig.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f8VnV9bfwiiK4S-xahhq-w.png" /><figcaption><strong><em>Golden curve all the way!</em></strong></figcaption></figure><p>Yeah! It has been good for sometime… IT HAS BEEN A BULL MARKET 📈. But I have a question here! If there is Bull market for sometime, why is Warren Buffett dumping his stocks for the past 2 odd years. Especially, the dumping is done for some his favorite stocks like APPLE (AAPL), Coca-Cola (KO) abd Bank of America (BAC).</p><p>Warren Buffett once said: “<strong><em>We own Coca-Cola, which is a wonderful business,” Buffett said. “And we own Apple, which is an even better business, and we will own, unless something really extraordinary happens, we will own Apple and American Express and Coca-Cola</em></strong>”. But what is happening to his portfolio currently?</p><pre># Lets look at Buffett&#39;s portfolio...</pre><pre>wb_pf = pd.read_csv(&#39;Warren_Buffett_Portfolio.csv&#39;)</pre><pre>display(wb_pf.head())</pre><pre>## Let&#39;s use Stacked bar chart to display his top 10 positions over the years...</pre><pre>wb_melted = wb_pf[[&#39;Period&#39;, &#39;Position1&#39;, &#39;Position2&#39;, &#39;Position3&#39;, &#39;Position4&#39;, &#39;Position5&#39;]].copy()<br>wb_melted = wb_melted.melt(id_vars=[&#39;Period&#39;], var_name=&#39;Position&#39;, value_name=&#39;Company&#39;)<br>wb_melted[&#39;Rank&#39;] = wb_melted[&#39;Position&#39;].str.extract(r&#39;(\d+)&#39;).astype(int)<br>wb_melted[&#39;Position&#39;] = pd.Categorical(wb_melted[&#39;Position&#39;], categories=[&#39;Position1&#39;, &#39;Position2&#39;, &#39;Position3&#39;, &#39;Position4&#39;, &#39;Position5&#39;], ordered=True)<br>wb_melted = wb_melted.sort_values(by=[&#39;Period&#39;, &#39;Rank&#39;])</pre><pre>wb_melted[&#39;Count&#39;] = 1</pre><pre>fig = px.bar(<br>    wb_melted,<br>    x=&#39;Period&#39;,<br>    y=&#39;Count&#39;,<br>    color=&#39;Company&#39;,<br>    title=&quot;Warren Buffett&#39;s Portfolio - Company Rankings&quot;,<br>    labels={&#39;Count&#39;: &#39;Portfolio Position&#39;, &#39;Period&#39;: &#39;Quarter&#39;},<br>    orientation=&#39;v&#39;,<br>    category_orders={&#39;Position&#39;: [&#39;Position1&#39;, &#39;Position2&#39;, &#39;Position3&#39;, &#39;Position4&#39;, &#39;Position5&#39;]},<br>    text=&#39;Company&#39;<br>)</pre><pre>fig.update_yaxes(autorange=&#39;reversed&#39;, tickmode=&#39;array&#39;, tickvals=[1, 2, 3, 4, 5], ticktext=[&#39;1&#39;, &#39;2&#39;, &#39;3&#39;, &#39;4&#39;, &#39;5&#39;])</pre><pre>fig.update_layout(<br>    legend_title=&quot;Companies in Portfolio&quot;,<br>    legend=dict(<br>        itemsizing=&#39;constant&#39;,<br>        traceorder=&#39;normal&#39;,<br>        orientation=&#39;h&#39;<br>    ),<br>    margin={&quot;t&quot;: 50, &quot;b&quot;: 50},<br>    uniformtext_minsize=10,<br>    uniformtext_mode=&quot;hide&quot;<br>)</pre><pre>fig.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VJZVUCbm5AyHgVYfuM2JPQ.png" /><figcaption>Warren Buffett’s portfolio of top 5 companies over the years.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m13vLsFmcXzREkjr1GxPXg.png" /><figcaption><strong>Looks like Warren Buffett is reducing his position with Apple and Coca-cola and even dumping VOO. (Damn thats alarming!)</strong></figcaption></figure><p><strong>The Buffett Indicator? What’s that and why are traders and investors talking about it?</strong></p><p><em>Buffett Indicator is a unique way of understanding the total stock market value at any given point of time. It is used to valuate how the stocks or stock market is priced. It is calculated by finding the total value of the stock market (S&amp;P500 stocks) divided by the GDP of United States 🇺🇸. If the Buffett Indicator value is 100, stocks are correctly priced, underpriced if less than 100 and overpriced if more than 100.</em></p><h4>The Buffett Indicator Formula:</h4><p><em>Buffett Indicator=Market Capitalization of All US Stocks / GDP of the US</em></p><ul><li><strong>Overvalued Market</strong>: A Buffett Indicator above 100% signals that the stock market is overvalued relative to the size of the economy.</li><li><strong>Undervalued Market</strong>: A Buffett Indicator below 50% suggests that the stock market is undervalued.</li></ul><p>I have used Wilshire 5000 Total Market Index for the Buffett indicator calculations.</p><h4>Historical Context of the Buffett Indicator</h4><p>Over time, the Buffett Indicator has provided valuable insights into market cycles. When the ratio has been high, such as during the dot-com bubble and pre-2008 financial crisis, it often signaled an impending correction. On the other hand, lower ratios have historically indicated buying opportunities. One specific scenario where Buffett smartly used this strategy was before the 2008 financial crisis to become one of the major shareholder of major bank(s) in the US. Currently, Buffett is sitting with <strong>US$ 325 Billion Cash reserves </strong>which is more than some of the countries’ economies. FASCINATING!!</p><pre>display(buffind.tail())</pre><pre>buffind_line = px.line(buffind, x=buffind[&#39;DateTime&#39;], y=buffind[&#39;Wilshire 5000 to GDP Ratio&#39;], template=&#39;plotly_dark&#39;, width=1100) # I like dark theme</pre><pre>buffind_line</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EDpCWeY5gz2SUObMQaVBSA.png" /><figcaption><strong>Look at the three red lines — 2000 had the Dot-com bubble, 2008 had the financial crisis, 2020 had the Covid slowdown, and its rising again. Anddddd rising again, but at a dangerous percentage of about 208%. :(</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lr4-p8Vi6bDKokE7ap-ixg.png" /></figure><p>If you look at the correlation plot, the indicators are strong and as Buffett once said: “<strong><em>Interest rates are to asset prices like gravity is to the apple</em></strong>”. Low Fed rates means more spending and more thriving in the stock market. But correlation is not causation. So, let’s look at Granger Causality test now.</p><pre># In most cases, correlation is not causation... Let&#39;s check that with the Granger Causality test...</pre><pre>from statsmodels.tsa.stattools import grangercausalitytests</pre><pre>max_lags = 2<br>for col in df_merged.columns[1:]:<br>    if col != &#39;GDP&#39;:<br>        print(f&quot;\nGranger Causality Test: {col} → GDP\n&quot;)<br>        grangercausalitytests(df_merged[[&#39;GDP&#39;, col]].dropna(), max_lags, verbose=True)</pre><p><strong>Granger Causality is to reject the null hypothesis:</strong></p><ul><li>If the p-value is below your chosen significance level (e.g., 0.05), you reject the null hypothesis and conclude that there is evidence of causality. A high p-value more than 0.05 suggests that you cannot reject the null hypothesis, implying that there is no evidence of Granger causality between the variables.</li></ul><pre>Granger Causality Test: PCE → GDP<br></pre><pre>Granger Causality<br>number of lags (no zero) 1<br>ssr based F test:         F=5.7170  , p=0.0225  , df_denom=34, df_num=1<br>ssr based chi2 test:   chi2=6.2215  , p=0.0126  , df=1<br>likelihood ratio test: chi2=5.7505  , p=0.0165  , df=1<br>parameter F test:         F=5.7170  , p=0.0225  , df_denom=34, df_num=1</pre><pre>Granger Causality<br>number of lags (no zero) 2<br>ssr based F test:         F=1.1851  , p=0.3192  , df_denom=31, df_num=2<br>ssr based chi2 test:   chi2=2.7525  , p=0.2525  , df=2<br>likelihood ratio test: chi2=2.6523  , p=0.2655  , df=2<br>parameter F test:         F=1.1851  , p=0.3192  , df_denom=31, df_num=2</pre><pre>Granger Causality Test: HighYieldBond → GDP<br></pre><pre>Granger Causality<br>number of lags (no zero) 1<br>ssr based F test:         F=3.5577  , p=0.0678  , df_denom=34, df_num=1<br>ssr based chi2 test:   chi2=3.8717  , p=0.0491  , df=1<br>likelihood ratio test: chi2=3.6822  , p=0.0550  , df=1<br>parameter F test:         F=3.5577  , p=0.0678  , df_denom=34, df_num=1</pre><pre>Granger Causality<br>number of lags (no zero) 2<br>ssr based F test:         F=1.4366  , p=0.2531  , df_denom=31, df_num=2<br>ssr based chi2 test:   chi2=3.3365  , p=0.1886  , df=2<br>likelihood ratio test: chi2=3.1908  , p=0.2028  , df=2<br>parameter F test:         F=1.4366  , p=0.2531  , df_denom=31, df_num=2</pre><pre>Granger Causality Test: FedRate → GDP<br></pre><pre>Granger Causality<br>number of lags (no zero) 1<br>ssr based F test:         F=0.0232  , p=0.8799  , df_denom=34, df_num=1<br>ssr based chi2 test:   chi2=0.0252  , p=0.8738  , df=1<br>likelihood ratio test: chi2=0.0252  , p=0.8738  , df=1<br>parameter F test:         F=0.0232  , p=0.8799  , df_denom=34, df_num=1</pre><pre>Granger Causality<br>number of lags (no zero) 2<br>ssr based F test:         F=1.2698  , p=0.2951  , df_denom=31, df_num=2<br>ssr based chi2 test:   chi2=2.9491  , p=0.2289  , df=2<br>likelihood ratio test: chi2=2.8345  , p=0.2424  , df=2<br>parameter F test:         F=1.2698  , p=0.2951  , df_denom=31, df_num=2</pre><pre>Granger Causality Test: S&amp;P500 → GDP<br></pre><pre>Granger Causality<br>number of lags (no zero) 1<br>ssr based F test:         F=13.6890 , p=0.0008  , df_denom=34, df_num=1<br>ssr based chi2 test:   chi2=14.8968 , p=0.0001  , df=1<br>likelihood ratio test: chi2=12.5186 , p=0.0004  , df=1<br>parameter F test:         F=13.6890 , p=0.0008  , df_denom=34, df_num=1</pre><pre>Granger Causality<br>number of lags (no zero) 2<br>ssr based F test:         F=2.8376  , p=0.0738  , df_denom=31, df_num=2<br>ssr based chi2 test:   chi2=6.5905  , p=0.0371  , df=2<br>likelihood ratio test: chi2=6.0520  , p=0.0485  , df=2<br>parameter F test:         F=2.8376  , p=0.0738  , df_denom=31, df_num=2</pre><pre>## To find if one variable&#39;s shock affects another variable, we can use methods called VAR (Vector Autoregression)<br>## and IRF (Impulse Response Function)</pre><pre>from statsmodels.tsa.api import VAR</pre><pre>from sklearn.preprocessing import StandardScaler</pre><pre>scaler = StandardScaler()</pre><pre>df_merged = df_merged.apply(pd.to_numeric, errors=&#39;coerce&#39;)</pre><pre>df_scaled = pd.DataFrame(scaler.fit_transform(df_merged), columns=df_merged.columns, index=df_merged.index)</pre><pre>model = VAR(df_scaled)<br>results = model.fit(maxlags=1)<br>print(results.summary())</pre><pre>irf = results.irf(10)<br>irf.plot(orth=True)<br>plt.show()</pre><pre>Summary of Regression Results   <br>==================================<br>Model:                         VAR<br>Method:                        OLS<br>--------------------------------------------------------------------<br>No. of Equations:         6.00000    BIC:                   -38.2872<br>Nobs:                     37.0000    HQIC:                  -39.4711<br>Log likelihood:           469.138    FPE:                3.89011e-18<br>AIC:                     -40.1158    Det(Omega_mle):     1.37548e-18<br>--------------------------------------------------------------------<br>Results for equation observation_date<br>======================================================================================<br>                         coefficient       std. error           t-stat            prob<br>--------------------------------------------------------------------------------------<br>const                       0.091189         0.000020         4642.424           0.000<br>L1.observation_date         1.000113         0.000216         4631.979           0.000<br>L1.PCE                     -0.000070         0.000281           -0.250           0.803<br>L1.GDP                     -0.000060         0.000289           -0.207           0.836<br>L1.HighYieldBond            0.000006         0.000106            0.053           0.957<br>L1.FedRate                  0.000007         0.000039            0.180           0.857<br>L1.S&amp;P500                   0.000007         0.000087            0.082           0.935<br>======================================================================================</pre><pre>Results for equation PCE<br>======================================================================================<br>                         coefficient       std. error           t-stat            prob<br>--------------------------------------------------------------------------------------<br>const                       0.107762         0.008904           12.103           0.000<br>L1.observation_date        -0.089272         0.097876           -0.912           0.362<br>L1.PCE                      0.790875         0.127184            6.218           0.000<br>L1.GDP                      0.274635         0.130957            2.097           0.036<br>L1.HighYieldBond           -0.048938         0.048085           -1.018           0.309<br>L1.FedRate                 -0.040924         0.017470           -2.343           0.019<br>L1.S&amp;P500                   0.080841         0.039367            2.054           0.040<br>======================================================================================</pre><pre>Results for equation GDP<br>======================================================================================<br>                         coefficient       std. error           t-stat            prob<br>--------------------------------------------------------------------------------------<br>const                       0.104350         0.007543           13.835           0.000<br>L1.observation_date        -0.095769         0.082910           -1.155           0.248<br>L1.PCE                     -0.039558         0.107737           -0.367           0.713<br>L1.GDP                      1.056207         0.110934            9.521           0.000<br>L1.HighYieldBond            0.013157         0.040732            0.323           0.747<br>L1.FedRate                 -0.043857         0.014799           -2.964           0.003<br>L1.S&amp;P500                   0.097071         0.033347            2.911           0.004<br>======================================================================================</pre><pre>Results for equation HighYieldBond<br>======================================================================================<br>                         coefficient       std. error           t-stat            prob<br>--------------------------------------------------------------------------------------<br>const                       0.080828         0.023057            3.506           0.000<br>L1.observation_date         0.131716         0.253444            0.520           0.603<br>L1.PCE                     -0.492027         0.329337           -1.494           0.135<br>L1.GDP                      0.742675         0.339108            2.190           0.029<br>L1.HighYieldBond            0.917437         0.124513            7.368           0.000<br>L1.FedRate                 -0.017334         0.045237           -0.383           0.702<br>L1.S&amp;P500                  -0.309659         0.101938           -3.038           0.002<br>======================================================================================</pre><pre>Results for equation FedRate<br>======================================================================================<br>                         coefficient       std. error           t-stat            prob<br>--------------------------------------------------------------------------------------<br>const                       0.001954         0.081533            0.024           0.981<br>L1.observation_date        -2.031111         0.896233           -2.266           0.023<br>L1.PCE                     -0.666453         1.164606           -0.572           0.567<br>L1.GDP                      2.360775         1.199157            1.969           0.049<br>L1.HighYieldBond           -0.020034         0.440305           -0.046           0.964<br>L1.FedRate                  0.403702         0.159968            2.524           0.012<br>L1.S&amp;P500                   0.092551         0.360474            0.257           0.797<br>======================================================================================</pre><pre>Results for equation S&amp;P500<br>======================================================================================<br>                         coefficient       std. error           t-stat            prob<br>--------------------------------------------------------------------------------------<br>const                       0.100039         0.041061            2.436           0.015<br>L1.observation_date         0.164702         0.451352            0.365           0.715<br>L1.PCE                     -0.577642         0.586508           -0.985           0.325<br>L1.GDP                      0.576057         0.603908            0.954           0.340<br>L1.HighYieldBond            0.291951         0.221742            1.317           0.188<br>L1.FedRate                  0.052598         0.080562            0.653           0.514<br>L1.S&amp;P500                   0.628485         0.181539            3.462           0.001<br>======================================================================================</pre><pre>Correlation matrix of residuals<br>                    observation_date       PCE       GDP  HighYieldBond   FedRate    S&amp;P500<br>observation_date            1.000000 -0.101027 -0.192048      -0.060345 -0.129036 -0.126389<br>PCE                        -0.101027  1.000000  0.750459       0.293516  0.158399  0.371423<br>GDP                        -0.192048  0.750459  1.000000       0.545753  0.233359  0.708762<br>HighYieldBond              -0.060345  0.293516  0.545753       1.000000  0.020357  0.801819<br>FedRate                    -0.129036  0.158399  0.233359       0.020357  1.000000  0.106752<br>S&amp;P500                     -0.126389  0.371423  0.708762       0.801819  0.106752  1.0000</pre><p><strong>Please look carefully at the GDP Equation:</strong></p><p>The coefficient for GDP is statistically significant with a large t-statistic, showing that past GDP values are important predictors for current GDP. Fed Rate and S&amp;P500<strong> </strong>also has a significant influence on GDP, with a p-value below 0.05.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aeZV74GZYkizLE3k7k151w.png" /></figure><p>Now look at the IRF (Impulse Response Function) graph shows how one variable’s shock can impact another variable:</p><p><strong>PCE’s shock on GDP</strong>: We can see how GDP responds to a shock in PCE (Personal Consumption Expenditures). A positive shock to PCE seems to lead to an increase in GDP<strong> </strong>(Look at the upward trend).</p><p><strong>Fed Rate’s shock on GDP</strong>: Look how the GDP has an impact when FedRate (Federal interest rates) goes through a shock meaning, any changes in interest rates impact economic growth.</p><p>With the stock market at historically high valuations, we just have to wait and watch. However, as the economy continues to recover from global challenges after covid, opportunities for growth may still exist.</p><p><strong>Disclaimer: I’m not a licensed professional/advisor for fund portfolio management. Please consult with a licensed advisor if needed</strong>. :)</p><h3>Final Thoughts? Yeah!</h3><p>This analysis has only scratched the surface of understanding the US economy and stock market using Python. Are you asking me if a stock market crash is coming? I don’t know! Are you going to panic sell all your stocks? I’m not recommending that anywhere. Probably a better idea is to move with the tide. See you again soon!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1bcca1b05751" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploy a full-stack web application on Kubernetes: A Full Course meal]]></title>
            <link>https://blog.devops.dev/deploy-a-full-stack-web-application-on-kubernetes-a-full-course-meal-0ab9579d3d78?source=rss-eb75631f2466------2</link>
            <guid isPermaLink="false">https://medium.com/p/0ab9579d3d78</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[tech]]></category>
            <dc:creator><![CDATA[Prabav Murali]]></dc:creator>
            <pubDate>Tue, 14 Jan 2025 21:47:05 GMT</pubDate>
            <atom:updated>2025-07-15T15:48:09.743Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you asked anyone in the tech community what Kubernetes is? Oh my bad! <strong>Kooobernetiss</strong> it is. If so, the answer would have been “a container orchestration tool” or “Ah! Its complicated to explain”. But, lets look at something beyond the definition. As a full course meal!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*oor8lB_eb4uVv5jD.jpg" /><figcaption><strong><em>An AI generated image</em></strong></figcaption></figure><p>Ingredients:</p><ul><li>1 React application</li><li>1 Flask application</li><li>1 RDS MySQL database</li><li>Some Docker images</li><li>Some Helm Charts</li><li>Kubernetes environment</li></ul><p>P.S: Please have a custom web application ready with a frontend, backend with database operations before you start. It can be a very basic application.</p><h3>Before starting, let’s look at K8’s history…</h3><p><em>Kubernetes has its roots in Google’s internal </em><a href="https://research.google/pubs/pub43438/"><em>Borg System</em></a><em>, introduced between 2003 and 2004. Later, </em><a href="https://blog.risingstack.com/the-history-of-kubernetes/"><em>in 2013</em></a><em>, Google released another project known as Omega, a flexible, scalable scheduler for large compute clusters. In that same year, McLuckie, Beda, and Burns set out to develop a “minimally viable orchestrator.” The desired set of essential features for the orchestrator included:</em></p><ul><li><strong><em>Replication</em></strong><em>: to deploy multiple instances of an application</em></li><li><strong><em>Load balancing and service discovery</em></strong><em>: to route traffic to these replicated containers</em></li><li><strong><em>Basic health checking and repair</em></strong><em>: to ensure a self-healing system</em></li><li><strong><em>Scheduling</em></strong><em>: to group many machines into a single pool and distribute work to them</em></li></ul><p><em>The following year, Kubernetes was released.Today, Kubernetes has 1800+ contributors, 500+ meetups worldwide, and 42,000+ users (many of them joining the public #kubernetes-dev channel on Slack). 83% of enterprises </em><a href="https://www.cncf.io/blog/2020/11/17/cloud-native-survey-2020-containers-in-production-jump-300-from-our-first-survey/"><em>surveyed by the Cloud Native Computing Foundation (CNCF) in 2020</em></a><em> are using Kubernetes</em>. [Source: <a href="https://www.opsramp.com/guides/why-kubernetes/who-made-kubernetes/">https://www.opsramp.com/guides/why-kubernetes/who-made-kubernetes/</a>]</p><p>When it comes to deploying modern web applications, Kubernetes has a lot to offer ensuring scalability and reliability. Let’s go on to deploy the Full-stack application to Kubernetes using helm packaging tool. Helm is nothing but a packaging tool for Kubernetes in the form of charts which contains files that define the Kubernetes cluster resources (Basically making our life easier) :)</p><h3>Step 1: Containerize the React and Flask Applications</h3><p>Both the React frontend and Flask backend need to be containerized using Docker. Below are sample Dockerfiles for each component.</p><h4>Dockerfile for React frontend:</h4><p>In the below Dockerfile, I have chosen v20 from the LTS version (Stable) list. You can choose your desired node version by running ‘<strong>nvm list available’ </strong>in shell/terminal. We do the <strong>‘npm run build’ </strong>to create a production ready application. (You can do a docker run after building the image)</p><pre>FROM node:20-alpine AS build<br>WORKDIR /app<br>COPY package.json package-lock.json ./<br>RUN npm install<br>COPY . .<br>RUN npm run build<br><br>FROM nginx:alpine<br>COPY ./build /usr/share/nginx/html<br>EXPOSE 80<br>CMD [&quot;nginx&quot;, &quot;-g&quot;, &quot;daemon off;&quot;]</pre><h4>Dockerfile for Flask backend:</h4><p>So, I have used the slim image of python311 because thats the version in my local. But you are free to use the version you desire. Before you build the docker image, make sure you create the requirements.txt. The command for that is: ‘<strong>pip freeze &gt; requirements.txt’</strong>. You can remove the unnecessary libraries from the requirements file (If you are not using a virtual environment)</p><pre>FROM python:3.11-slim<br>WORKDIR /app<br>COPY requirements.txt .<br>RUN pip install -r requirements.txt<br>RUN pip install gunicorn<br>COPY . .<br>EXPOSE 5000<br>CMD [&quot;gunicorn&quot;, &quot;-w&quot;, &quot;4&quot;, &quot;-b&quot;, &quot;0.0.0.0:5000&quot;, &quot;app:app&quot;]</pre><p>Now, build and push the Docker images to your container registry (e.g., Docker Hub, AWS ECR). Here, I used Docker Hub.</p><pre>#frontend<br>docker build -t &lt;reponame&gt;/myfrontend:latest .<br>docker push docker.io/&lt;reponame&gt;/myfrontend<br><br>#backend<br>docker build -t &lt;reponame&gt;/mybackend:latest .<br>docker push docker.io/&lt;reponame&gt;/mybackend<br></pre><h3>Step 2: Create a RDS MySQL database and access it with the Kubernetes Cluster</h3><p>Create an AWS free tier account for creating a RDS MySQL database. If you are unaware of the steps, you can refer to this documentation: <a href="https://aws.amazon.com/getting-started/hands-on/create-mysql-db/">https://aws.amazon.com/getting-started/hands-on/create-mysql-db/</a></p><p>After the database becomes publicly available (Check settings), Copy the RDS Endpoint and go to Security tab and click on the Security group which redirects to EC2 → Security Group and edit the <strong>Ingress rules</strong>. Add an entry to it to connect from MySQL workbench:</p><p>Protocol: MySQL/Aurora</p><p>Port Range: 3306</p><p>Source: Your IP address</p><p>Now, go to MySQL workbench and add a new connection. Paste the Endpoint address in Hostname, Username, Password and connect to the database. Now you can create tables according the web application requirements. We will do the same thing again after we create the Kubernetes Clusters.</p><h3>Step 3: Install Kubernetes, Helm and create templates for Kubernetes Deployment</h3><p>If you have Docker desktop, you can enable Kubernetes and wait for the engine to start running. Run <strong>‘kubectl get pods’ </strong>to check if its installed. You can refer to the official Kubernetes documentation <a href="https://kubernetes.io/docs/tasks/tools/">https://kubernetes.io/docs/tasks/tools/</a> for installation in other OS’es. Helm is an amazing tool! If you don’t have helm installed in your machine, you can refer to this URL: <a href="https://helm.sh/docs/intro/install/">https://helm.sh/docs/intro/install/</a>. If you are a Mac user, go to the terminal: ‘<strong>brew install helm’</strong></p><p>Now go to application directory and run <strong>‘helm create &lt;ChartName&gt;’</strong></p><h4>Helm Chart creation:</h4><p>Create a directory for your Helm:</p><pre>helm create myapp</pre><p>This generates a basic Helm chart(s) structure, which actually halves the deployment work. We need to replace the default templates with customized Kubernetes manifests/values.</p><h4>Deployment for React frontend:</h4><p>templates/frontend-deployment.yaml</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: {{ .Release.Name }}-frontend<br>  labels:<br>    app: {{ .Release.Name }}-frontend<br>spec:<br>  {{- if not .Values.autoscaling.enabled }}<br>  replicas: {{ .Values.frontend.replicas }}<br>  {{- end }}<br>  selector:<br>    matchLabels:<br>      app: {{ .Release.Name }}-frontend<br>  template:<br>    metadata:<br>      {{- with .Values.podAnnotations }}<br>      annotations:<br>        {{- toYaml . | nindent 8 }}<br>      {{- end }}<br>      labels:<br>        app: {{ .Release.Name }}-frontend #Pay attention to the matchlabel for later<br>        {{- with .Values.podLabels }}<br>        {{- toYaml . | nindent 8 }}<br>        {{- end }}<br>    spec:<br>      {{- with .Values.imagePullSecrets }}<br>      imagePullSecrets:<br>        {{- toYaml . | nindent 8 }}<br>      {{- end }}<br>      serviceAccountName: {{ include &quot;myapp.serviceAccountName&quot; . }}<br>      securityContext:<br>        {{- toYaml .Values.podSecurityContext | nindent 8 }}<br>      containers:<br>        - name: {{ .Chart.Name }}<br>          securityContext:<br>            {{- toYaml .Values.securityContext | nindent 12 }}<br>          image: &quot;{{ .Values.frontend.image.repository }}:{{ .Values.frontend.image.tag | default .Chart.AppVersion }}&quot;<br>          imagePullPolicy: {{ .Values.frontend.image.pullPolicy }}<br>          ports:<br>            - name: http<br>              containerPort: {{ .Values.service.port }}<br>              protocol: TCP<br>          livenessProbe:<br>            {{- toYaml .Values.livenessProbe | nindent 12 }}<br>          readinessProbe:<br>            {{- toYaml .Values.readinessProbe | nindent 12 }}<br>          resources:<br>            {{- toYaml .Values.resources | nindent 12 }}<br>          {{- with .Values.volumeMounts }}<br>          volumeMounts:<br>            {{- toYaml . | nindent 12 }}<br>          {{- end }}<br>      {{- with .Values.volumes }}<br>      volumes:<br>        {{- toYaml . | nindent 8 }}<br>      {{- end }}<br>      {{- with .Values.nodeSelector }}<br>      nodeSelector:<br>        {{- toYaml . | nindent 8 }}<br>      {{- end }}<br>      {{- with .Values.affinity }}<br>      affinity:<br>        {{- toYaml . | nindent 8 }}<br>      {{- end }}<br>      {{- with .Values.tolerations }}<br>      tolerations:<br>        {{- toYaml . | nindent 8 }}<br>      {{- end }}</pre><h4>Deployment for Flask</h4><p>templates/backend-deployment.yaml</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: {{ .Release.Name }}-backend<br>  labels:<br>    app: {{ .Release.Name }}-backend<br>spec:<br>  replicas: {{ .Values.backend.replicas }}<br>  selector:<br>    matchLabels:<br>      app: {{ .Release.Name }}-backend<br>  template:<br>    metadata:<br>      labels:<br>        app: {{ .Release.Name }}-backend<br>    spec:<br>      containers:<br>      - name: backend<br>        image: {{ .Values.backend.image.repository }}:{{ .Values.backend.image.tag }}<br>        env:<br>        - name: DB_HOST<br>          value: {{ .Values.backend.dbHost }}<br>        - name: DB_USER<br>          value: {{ .Values.backend.rootUsername }}<br>        - name: DB_PASSWORD<br>          value: {{ .Values.backend.rootPassword }}<br>        ports:<br>        - containerPort: 5000</pre><h4>Service:</h4><p>templates/service.yaml</p><pre>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: {{ include &quot;myapp.fullname&quot; . }}<br>  labels:<br>    {{- include &quot;myapp.labels&quot; . | nindent 4 }}<br>spec:<br>  type: {{ .Values.service.type }}<br>  ports:<br>    - port: {{ (.Values.service).port | default 80 }}<br>      targetPort: 80<br>      protocol: TCP<br>      name: http<br>  selector:<br>    {{- include &quot;myapp.selectorLabels&quot; . | nindent 4 }} # &lt;- Also look at the selector label here.</pre><h4>Secrets:</h4><p>templates/secret.yaml</p><pre>apiVersion: v1<br>kind: Secret<br>metadata:<br>  name: {{ .Release.Name }}-mysql-secret<br>type: Opaque<br>data:<br>  DB_HOST: {{ .Values.backend.dbHost | b64enc}}<br>  DB_USER: {{ .Values.backend.rootUsername | b64enc}}<br>  DB_PASSWORD: {{ .Values.backend.rootPassword | b64enc}}</pre><h4>Values:</h4><p>templates/values.yaml</p><pre># Default values for myapp.<br># This is a YAML-formatted file.<br># Declare variables to be passed into your templates.<br><br>frontend:<br>  # This will set the replicaset count. More information can be found here: https://kubernetes.io/docs/concepts/workloads/controllers/replicaset/<br>  replicas: 1<br><br>  # This sets the container image. More information can be found here: https://kubernetes.io/docs/concepts/containers/images/<br>  image:<br>    repository: docker.io/&lt;reponame&gt;/myfrontend<br>    # This sets the pull policy for images.<br>    pullPolicy: IfNotPresent<br>    # Overrides the image tag whose default is the chart appVersion.<br>    tag: &quot;latest&quot;<br><br>  # This is for the secrets for pulling an image from a private repository. More information can be found here: https://kubernetes.io/docs/tasks/configure-pod-container/pull-image-private-registry/<br>  imagePullSecrets: []<br><br>  # This is to override the chart name.<br>  nameOverride: &quot;&quot;<br>  fullnameOverride: &quot;&quot;<br><br>  # This section builds out the service account. More information can be found here: https://kubernetes.io/docs/concepts/security/service-accounts/<br>serviceAccount:<br>  # Specifies whether a service account should be created<br>  create: true<br>  # Automatically mount a ServiceAccount&#39;s API credentials?<br>  automount: true<br>  # Annotations to add to the service account<br>  annotations: {}<br>  # The name of the service account to use.<br>  # If not set and create is true, a name is generated using the fullname template<br>  name: &quot;&quot;<br><br>  # This is for setting Kubernetes Annotations to a Pod. More information can be found here: https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations/<br>  podAnnotations: {}<br><br>  # This is for setting Kubernetes Labels to a Pod. More information can be found here: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/<br>  podLabels: {}<br><br>  # Pod security context for the pod.<br>  podSecurityContext: {}<br>    # fsGroup: 2000<br><br>  # Security context for the container.<br>  securityContext: {}<br>    # capabilities:<br>    #   drop:<br>    #   - ALL<br>    # readOnlyRootFilesystem: true<br>    # runAsNonRoot: true<br>    # runAsUser: 1000<br><br># This is for setting up a service. More information can be found here: https://kubernetes.io/docs/concepts/services-networking/service/<br>service:<br>  # This sets the service type. More information can be found here: https://kubernetes.io/docs/concepts/services-networking/service/#publishing-services-service-types<br>  type: ClusterIP<br>  # This sets the ports. More information can be found here: https://kubernetes.io/docs/concepts/services-networking/service/#field-spec-ports<br>  port: 80<br><br># This block is for setting up the ingress. More information can be found here: https://kubernetes.io/docs/concepts/services-networking/ingress/<br>ingress:<br>  enabled: false<br>  className: &quot;&quot;<br>  annotations: {}<br>    # kubernetes.io/ingress.class: nginx<br>    # kubernetes.io/tls-acme: &quot;true&quot;<br>  hosts:<br>    - host: chart-example.local<br>      paths:<br>        - path: /<br>          pathType: ImplementationSpecific<br>  tls: []<br>    #  - secretName: chart-example-tls<br>    #    hosts:<br>    #      - chart-example.local<br><br>resources:<br>  # We usually recommend not to specify default resources and to leave this as a conscious<br>  # choice for the user. This also increases chances charts run on environments with little<br>  # resources, such as Minikube. If you do want to specify resources, uncomment the following<br>  # lines, adjust them as necessary, and remove the curly braces after &#39;resources:&#39;.<br>  requests:<br>    memory: &quot;256Mi&quot;<br>    cpu: &quot;250m&quot;<br>  limits:<br>    memory: &quot;512Mi&quot;<br>    cpu: &quot;500m&quot;<br><br># This is to set up the liveness and readiness probes. More information can be found here: https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes/<br>readinessProbe:<br>  httpGet:<br>    path: /<br>    port: 80<br>  initialDelaySeconds: 2<br>  periodSeconds: 10              <br>  timeoutSeconds: 2              <br>livenessProbe:<br>  httpGet:<br>    path: /<br>    port: 80<br><br># This section is for setting up autoscaling. More information can be found here: https://kubernetes.io/docs/concepts/workloads/autoscaling/<br>autoscaling:<br>  enabled: false<br>  minReplicas: 1<br>  maxReplicas: 100<br>  targetCPUUtilizationPercentage: 80<br>  # targetMemoryUtilizationPercentage: 80<br><br># Additional volumes on the output Deployment definition.<br>volumes: []<br># - name: foo<br>#   secret:<br>#     secretName: mysecret<br>#     optional: false<br><br># Additional volumeMounts on the output Deployment definition.<br>volumeMounts: []<br># - name: foo<br>#   mountPath: &quot;/etc/foo&quot;<br>#   readOnly: true<br><br>nodeSelector: {}<br><br>tolerations: []<br><br>affinity: {}<br><br># Backend configuration<br>backend:<br>  replicas: 1<br>  image:<br>    repository: docker.io/&lt;reponame&gt;/mybackend<br>    tag: latest<br>  dbHost: &#39;Your RDS endpoint address&#39;<br>  rootPassword: xxxxxx<br>  rootUsername: username</pre><p><strong>Note: It is unsafe/less secure to expose the password in the values file/ anywhere outside. Since, this work is for practice purposes, I went ahead with testing it directly. We can use AWS Secrets Manager or similar services to store the secrets and can be retrieved either in Dockerfile/Kubernetes Init containers. [HIGHLY RECOMMENDED]</strong></p><p>After everything is created, run the command:</p><p><strong>‘helm install &lt;releasename&gt; ./myapp — namespace &lt;namespace&gt;’.</strong></p><p><strong>‘kubectl get pods -o wide’</strong></p><p>Now you will see something like ‘READY’:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QOo5WqBOa7yYvHU1l-GTKw.png" /></figure><p>Now, let’s get the IP of the Kubernetes Cluster with the command: <strong>‘kubectl get svc -o wide’</strong>. You will be able to find your IP of your release name. Copy that and go to security group (Please refer to Step 2) and add an entry to the ‘<strong>Ingress rules</strong>’. You can also choose the range of IPs you want to open to your database.</p><p>After Ready status, you now need to port forward to test the application: Run the command:</p><p>‘<strong>kubectl port-forward svc/&lt;releasename&gt; 8080:80’</strong></p><p>When you run this, you might get a timeout error which is intentional (Please scroll up and look at the podlabels in frontend-deployment template and selector label in service.yaml). But if you port-forward it to the pod directly, it will work. Why is that? Let’s see…</p><p><strong>‘kubectl port-forward &lt;frontend-pod-name&gt; 8080:80’</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*60_k8lLzEEXGSRgSa2_zEQ.png" /></figure><p>Now let’s change the service.yaml to match the actual label of frontend-deployment.</p><pre>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: {{ include &quot;myapp.fullname&quot; . }}<br>  labels:<br>    {{- include &quot;myapp.labels&quot; . | nindent 4 }}<br>spec:<br>  type: {{ .Values.service.type }}<br>  ports:<br>    - port: {{ (.Values.service).port | default 80 }}<br>      targetPort: 80<br>      protocol: TCP<br>      name: http<br>  selector:<br>    app: {{ .Release.Name }}-frontend # &lt;- Changing it according to podLabel from frontend deployment</pre><p>Now upgrade the helm with ‘<strong>helm upgrade &lt;releasename&gt; &lt;chartname&gt; — namespace &lt;namespace&gt;</strong>’ or ‘<strong>helm uninstall &lt;releasename&gt; — namespace &lt;namespace&gt;</strong>’ command and install it again. Then we run the <strong>‘kubectl port-forward svc/myapp 8080:80’</strong>. It will workk!!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*fCsGy1S1ruv0fSjg_bocQA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*llEeuc9234k99orfxwS_PA.png" /><figcaption><strong>Isn’t that a sweet dessert?</strong></figcaption></figure><p>[<strong>You need help?</strong>] If you get something like ‘<strong>CrashloopBackoff</strong>’, please check the cluster configuration/values/resource constraints or ‘<strong>ImagePullBackoff</strong>’, then there might be an error with pulling the image from the repository. You can refer to: <a href="https://sysdig.com/blog/debug-kubernetes-crashloopbackoff/">https://sysdig.com/blog/debug-kubernetes-crashloopbackoff/</a> for debugging tips.</p><p>Now let’s introduce a Crashloopbackoff error to see how it looks.</p><pre>readinessProbe:<br>  httpGet:<br>    path: /notapath   # &lt;-Invalid path<br>    port: 80<br>  initialDelaySeconds: 2<br>  periodSeconds: 10              <br>  timeoutSeconds: 2              <br>livenessProbe:<br>  httpGet:<br>    path: /notapath   # &lt;-Invalid path<br>    port: 80</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*obKiNojT_4fkFzvW3asj1A.png" /></figure><p>Running ‘<strong>kubectl get pods’</strong> will give you the above result. Since, we changed path of readiness probe and liveness probe, the pod reached a crashloopbackoff state. The reason for that is the failure of health check causing repeated restarts. You can change it back and upgrade the chart again.</p><h3>Conclusion</h3><p>That brings us to an end in the Kubernetes deployment where you have successfully deployed a React-Flask application. This is a dev practice session and to make it production-ready, we will be integrating Monitoring solutions, deploying to EKS etc. Stay tuned! Hey one more thing! Do stop and delete the RDS instance when you are done practicing to avoid lengthy credit card bills :D</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0ab9579d3d78" width="1" height="1" alt=""><hr><p><a href="https://blog.devops.dev/deploy-a-full-stack-web-application-on-kubernetes-a-full-course-meal-0ab9579d3d78">Deploy a full-stack web application on Kubernetes: A Full Course meal</a> was originally published in <a href="https://blog.devops.dev/">DevOps.dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beyond the Definition of ‘DevOps’]]></title>
            <link>https://medium.com/@prabavmurali09/beyond-the-definition-of-devops-03c5b584617b?source=rss-eb75631f2466------2</link>
            <guid isPermaLink="false">https://medium.com/p/03c5b584617b</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[devsecops]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[information-technology]]></category>
            <dc:creator><![CDATA[Prabav Murali]]></dc:creator>
            <pubDate>Sat, 16 Mar 2024 21:29:26 GMT</pubDate>
            <atom:updated>2024-04-14T04:08:17.650Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*PcdHQUJGEOIiWY9R_kG3Gg.jpeg" /><figcaption><em>Remember to pick what you want like this kid in the picture (This is an AI generated image)</em></figcaption></figure><p><strong>Introduction</strong>:</p><p>Book definition: “DevOps principles act as the bridge between the Development team and the Operations team”. This definition has been following me everywhere since the day I took a career in DevOps, even in my sleep. But what exactly is DevOps? People talk about Continuous Integration, Continuous Deployment, but DevOps majorly revolves around Continuous Improvement. Confusing right? Let’s break it down. DevOps is not only about searching google for “Top DevOps tools in 202x” and cramming everything at once (In educational context). It’s a mindset which goes through continuous learning and learning from past failures.</p><p><strong>Main Content</strong>:</p><p>So let’s get into the actual content. DevOps practices started around the late 2000s (Obviously got this information from Google) as a practice to deliver software products reliably and rapidly. Before DevOps, the role probably would have been called a Systems engineer or the “Server guy”. It then evolved rapidly to be called DevOps practices which helped in solving “<strong>It works in my machine!</strong>” problems by Docker container deployment across environments, Cloud DevOps, then <strong>DevSecOps</strong> (when data became the “new oil” in today’s world). Now, the “Ops” term is a suffix which is added to emerging tech concepts like CloudOps, DataOps, MLOps, AIOps, and what not? I recently also came across the concept of ChatOps.</p><p>When everything is evolving rapidly, it is difficult to cope with changes and as I had mentioned before, you cannot get familiarized with ALL the tools at once. But, it is paramount that you are informed about the changes happening in the tech community and and adopt ONLY that suits your infrastructure needs (<strong>Cherry picking</strong>). For eg., When AI is booming, think about how you can integrate it with the existing DevOps processes.</p><p>It is imperative that DevOps professionals be aware of Software development lifecycles, Automation using a scripting language, and Infrastructure as Code (IaC) tools etc., but also to have the following mindset:</p><p>- Always expect failures and have a Fail fast approach.</p><p>- Ability to read documentation and write documentation in simple English.</p><p>- Ability to learn from your and other’s mistakes.</p><p>- Understand that scripts need not be the cleanest all the time. Sometimes dirty scripts which can solve production issues at the moment are appreciated.</p><p>- Should not have the “One size fits all” mindset and must not create a complex infrastructure just because you have options. Evaluate whats needed!</p><p>- Use CLI for MOST AWS tasks and thank me later!</p><p>- Finally, have security, cost-control, monitoring, DR and backup strategies in mind.</p><p>Now, when we talk about the kick-starter tech stacks that are needed for DevOps, there are numerous of them in the market starting from AWS, GCP, Azure for Cloud providers, TerraForm, Ansible, Pulumi etc. for IaC tools, Docker, Kubernetes, Jenkins, Prometheus etc. Picking the right stack for your infrastructure is important and should not be afraid of trying others.</p><p>Since I’ve been working on AWS from the time I started my cloud journey, I can provide the gist of AWS services for implementing DevOps practices. As you all know AWS offers a wide range of services that cater to the needs of DevOps, Solutions Architecture, and DevSecOps teams, it becomes easy to build, deploy, and manage applications efficiently and securely in no time. In this article, we’ll explore key AWS services and how they can be utilized in DevOps and, DevSecOps practices.</p><p><strong>Example list of AWS Services:</strong></p><p><strong>AWS IAM</strong>: Manage user access to AWS services securely with IAM, ensuring that only authorized users and applications have access.</p><p><strong>AWS CodeCommit</strong>: To manage Git repositories within AWS. You can integrate AWS <strong>CodeGuru</strong> with CodeCommit to find security vulnerabilities and recommend fixes in the code. This can help in the <strong>Shift-left</strong> approach from DevSecOps.</p><p><strong>AWS CloudFormation</strong>: Provides Developers/DevOps Engineers the ability to manage the Infrastructure as a Code. Can also use <strong>TerraForm</strong>, <strong>Ansible, Pulumi </strong>and other IaC (Outside AWS) for cloud-agnostic approaches.</p><p><strong>VPC, Subnets, NACLs, Security Groups, WAF</strong> etc.: Give the customers an advanced networking and firewall configuration freedom to be utilized for “<strong>Security in the Cloud</strong>”.</p><p><strong>AWS KMS</strong>: For control over encryption and decryption of data and objects at rest.</p><p><strong>AWS CodeBuild</strong>: Compiles your code, runs tests, and produces deployable artifacts, all within a managed build environment (Docker). You can also implement <strong>SonarQube</strong> for DevSecOps practices within CodeBuild for your pipelines.</p><p><strong>AWS CodePipeline</strong>: Automate your CI/CD pipeline with AWS CodePipeline, which allows you to build, test, and deploy your applications seamlessly. Can also use <strong>Jenkins</strong>, <strong>Octopus</strong> (Outside AWS) for cloud-agnostic approaches.</p><p><strong>Amazon EC2, Load Balancers, ASG</strong>: Launch virtual servers in the cloud with Amazon EC2, providing elastic and scalable computing capacity to run your applications.</p><p><strong>AWS ECR, ECS, EKS</strong>: For maintaining docker images, running containers, Manage Kubernetes control plane. It has options to deploy as EC2 or Fargate clusters</p><p><strong>Amazon S3</strong>: Store and retrieve any amount of data with high durability and availability using Amazon S3, ideal for static website hosting and data archiving.</p><p><strong>AWS RDS, Aurora, DynamoDB</strong>: AWS provides managed <strong>Relational</strong> database service in the form of RDS, Aurora and <strong>NoSQL</strong> in the form of DynamoDB.</p><p><strong>AWS Lambda</strong>: Run code without provisioning or managing servers with AWS Lambda, enabling you to build serverless applications. Supports Python, Java, Node.js etc.</p><p><strong>AWS CloudWatch, CloudTrail</strong>: To monitor AWS services with CloudWatch’s logging capabilities and also helps to implement Alarms based on thresholds, CRON-based schedulers and much more. CloudTrail provides much advanced features like tracking API calls and other activities done by users/roles within the Cloud.</p><p><strong>AWS Security Hub</strong>: Centrally manage security and compliance across your AWS environment with AWS Security Hub, providing a comprehensive view of your security posture.</p><p>Please note that the services are not limited to the list and there are services for <strong>Machine Learning</strong> use-cases, <strong>Data Analytics</strong> use-cases etc. There are about 100s of services to cater for your needs in the AWS Cloud and every service has its strength and <strong>related costs</strong> involved. So, it is important to meticulously evaluate the needs and it is highly recommended to read the AWS-provided documentation before adopting a new service in your organization.</p><p>I began my career as a Cloud DevOps professional right after my Masters and since then, I have always made sure that asking questions is as important as learning from online resources. When you post questions to the right people/right community, you get to learn from their failures, their way of thinking etc. Hence, it is super-important to be a part of a tech-community to be informed about the ever evolving tech world.</p><p><strong>Conclusion</strong>:</p><p>Adopting DevOps culture within teams helps in various aspects like collaboration which can help in delivering highly optimized solutions at the right time, but planning the architecture right will also help in saving huge amount of time. AWS is one of the cloud providers that offers a comprehensive suite of services that cater to the needs of DevOps, Solutions Architecture, and DevSecOps teams. Please keep in mind that there are costs involved with the services and it is imperative to evaluate the needs of the organization when choosing the Cloud provider/DevOps tools.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=03c5b584617b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>