<?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 Jeet S Swadia on Medium]]></title>
        <description><![CDATA[Stories by Jeet S Swadia on Medium]]></description>
        <link>https://medium.com/@swadiajeet?source=rss-e9b92d54f61c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*_BhCnKsyqjOiGP6aLWIc7g.jpeg</url>
            <title>Stories by Jeet S Swadia on Medium</title>
            <link>https://medium.com/@swadiajeet?source=rss-e9b92d54f61c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 17:05:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@swadiajeet/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[I Took the Google Hiring Assessment. Here’s What Nobody Tells You.]]></title>
            <link>https://medium.com/@swadiajeet/i-took-the-google-hiring-assessment-heres-what-nobody-tells-you-b4c8bbb44624?source=rss-e9b92d54f61c------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4c8bbb44624</guid>
            <category><![CDATA[job-hunting]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[google]]></category>
            <dc:creator><![CDATA[Jeet S Swadia]]></dc:creator>
            <pubDate>Fri, 24 Apr 2026 20:58:47 GMT</pubDate>
            <atom:updated>2026-04-24T20:58:47.557Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>When the notification landed in my inbox, I did what everyone does — I panicked and opened Reddit. Here’s why that was the wrong move, and what actually helped.</strong></p><p><em>Personal Experience · Careers · Big Tech · Job Hunting · 8 min read</em></p><p>The email arrived on a Tuesday. A Google recruiter had moved my application forward, and the next step was something called the <strong>Google Hiring Assessment</strong> — a 30-minute online evaluation I needed to complete within a few days. Simple enough. I confirmed I’d take it, closed the tab, and immediately fell into a two-hour Reddit rabbit hole.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OxompDkAvKKz2Fh4eWbfPw.png" /></figure><p>That was my first mistake.</p><p>I’m writing this because when I went looking for a clear, honest account of what the GHA is like — the kind that would actually calm me down and help me prepare — I couldn’t find one. What I found instead was a scattered mix of outdated posts, contradictory advice, and enough anxiety-inducing commentary to make anyone second-guess themselves before even opening the assessment link. This article is the post I wish had existed.</p><blockquote>A note on disclosure: Per Google’s hiring assessment privacy policy, I’m not going to share specific questions or answer content. What I can share are the publicly documented categories (listed in Google’s own FAQ), my honest experience with the format, and — most importantly — the mindset that actually got me through it.</blockquote><h3>What Is the Google Hiring Assessment?</h3><p>The GHA is a structured, standardized evaluation that Google uses across a broad range of roles. It is not a coding challenge. It is not a quiz on Google products. It is an assessment of <em>how you think, how you work, and how you make decisions</em> — particularly in work-relevant situations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZFPLiSuI7HBCqUp_9FApAQ.png" /></figure><p>According to Google’s publicly available hiring FAQ, the assessment is timed (approximately 30 minutes), delivered online, and administered as part of the candidate screening process before interviews. It is adaptive in nature, which is part of why so many people online describe wildly different experiences — the path through it is not identical for everyone.</p><h3>The Two Facts That Matter Most</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J5PeezVR4j87wwDXn_0heA.png" /></figure><p>Before anything else, understand these:</p><ul><li><strong>Pass validity: 24 months.</strong> A passing result is valid for two years. You do not need to retake the GHA for any Google role you apply to within that window.</li><li><strong>Fail consequence: 6-month block.</strong> If you do not pass, you cannot apply to <em>any</em> Google role for six months.</li><li>The assessment covers situational and behavioral scenarios rooted in real work contexts.</li><li>It is not a test of technical knowledge or product familiarity.</li><li>Question content is confidential under Google’s hiring policies.</li></ul><p>Those two facts — the 24-month validity and the 6-month block — are the single most important things to understand going in. This is not a low-stakes screening quiz. A strong result clears your path for two years. A poor result closes it for six months. That reality is worth sitting with before you click Start.</p><h3>What I Did to Prepare (And What I’d Do Differently)</h3><p>After the Reddit spiral failed to produce anything useful, I switched tactics. I opened Claude and asked it to generate 110 practice questions — I had seen people on Reddit mention the assessment had “so many questions,” and I wanted to simulate that volume and get comfortable with sustained focus and decision-making over a longer session.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0hoVXPDZj4RqsSIR_whnxA.png" /></figure><p>That part was genuinely useful. Not because the questions matched Google’s format — they didn’t, and more on that in a moment — but because it forced me to articulate my own values and working preferences out loud, repeatedly, without overthinking each one. It was like warming up before a run. By the time I opened the real thing, I had already spent time thinking about how <em>I</em> actually work.</p><blockquote>“The preparation that helped most wasn’t learning what the ‘right answers’ were. It was getting comfortable with my own answers — the ones that were genuinely mine.”</blockquote><p>What I would do differently: spend less time on volume practice and more time on self-reflection. The GHA is not testing whether you’ve memorized a framework. It’s testing whether you know yourself.</p><h3>When the Format Caught Me Off Guard</h3><p>Here’s the honest part: the format was not what I expected based on anything I’d read online. The structure, the pacing, the way questions were presented — it was different enough from the community descriptions that, for the first few minutes, I felt genuinely thrown off.</p><p>Then I made a decision that I think saved my performance: I stopped trying to reconcile what I was seeing with what I’d read, and I just answered each question as honestly and naturally as I could.</p><p>The scenarios in the assessment place you in work situations. You are asked to choose, rank, or evaluate responses based on what you would actually do — not what sounds good, not what you think a perfect Googler would do, but what reflects how you genuinely operate. That shift in framing is everything.</p><p><strong>The core insight:</strong> The assessment is not asking “what is the optimal answer?” It is asking “what is <em>your</em> answer?” Those are very different questions. If you try to game it by selecting what you think they want to see, you will likely produce an inconsistent profile — and the statistical model underlying the assessment is specifically designed to detect inconsistency.</p><h3>The Noise Out There Is Louder Than It Is Useful</h3><p>I want to address this directly, because it’s the reason I’m writing this post at all.</p><p>There is a significant amount of online discussion about the GHA — on Reddit, on forums, on career blogs — and the overwhelming majority of it is people either catastrophizing after a block or speculating about answer patterns. Some posts list specific “correct” responses. Others describe the assessment in ways that bear little resemblance to what I experienced.</p><p>None of it helped me. In fact, most of it actively made things worse by creating a mental model of the assessment that turned out to be inaccurate, which is exactly why I felt thrown when the real thing looked different.</p><h3>The danger of community “answer guides”</h3><p>If someone online is telling you the “right” answers to the GHA — specific choices that will guarantee a pass — treat that with extreme skepticism.</p><p>The assessment is adaptive and situational. More importantly: a person who answers questions that do not reflect their actual working style will produce an inconsistent profile across the assessment. The model will catch it. You are better off being genuine and imperfect than performative and incoherent.</p><p>The irony is that the more you try to become someone else for 30 minutes, the harder the assessment gets and the worse you perform. The most important skill you can bring into that window is the ability to be straightforwardly, consistently yourself.</p><h3>What the Assessment Is Actually Measuring</h3><p>Based on Google’s publicly documented categories and my own experience, the GHA appears to assess several dimensions of how you function as a professional. These broadly include your approach to collaborative work, how you handle competing priorities and ambiguous situations, your communication tendencies, and how you navigate decisions under constraint.</p><p>Think less “right answer” and more “coherent picture of a person.” The assessment is trying to build a profile. The best thing you can do is make that profile accurate — because you want to be matched with an environment where you’ll actually thrive, not where you’ve pretended to fit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UJbiCE_ee9HxbdYFd8atFg.png" /></figure><p>If your natural working style is that of a person who moves carefully, gathers information before deciding, and prefers structured collaboration — answer that way. If you’re someone who acts quickly, adapts in real time, and drives toward outcomes independently — answer that way. Both profiles can succeed at Google. An inconsistent or performed profile helps nobody, least of all you.</p><h3>Practical Notes Before You Begin</h3><p>A few concrete things worth knowing before you start:</p><p><strong>Time it properly.</strong> 30 minutes is not long. Don’t begin when you’re tired, distracted, or squeezed between meetings. Treat it like a real interview window. Find a quiet block and protect it.</p><p><strong>Read each scenario fully.</strong> The situations are specific. Rushing through the setup to get to the choices is a mistake. The context matters.</p><p><strong>Don’t second-guess mid-assessment.</strong> If you’ve answered honestly, move forward. Revisiting and second-guessing creates inconsistency, not improvement.</p><p><strong>Your internet research session ends before you click Start.</strong> Anything you haven’t absorbed by then is more likely to confuse than help. Close the Reddit tabs.</p><p><strong>Remember the stakes.</strong> 24 months of validity if you pass. 6-month block if you don’t. Take it seriously — which means being calm and present, not anxious and performative.</p><h3>The Bottom Line</h3><p>The Google Hiring Assessment is not the mysterious, gaming-required obstacle that online forums make it out to be. It is a well-designed professional evaluation that is trying to understand who you are and how you work. The best preparation is not to study answer patterns — it is to have a clear, honest sense of yourself as a professional.</p><p>Use whatever tools help you get there. I used Claude to warm up my thinking. You might use journaling, or a conversation with a mentor, or simply reflecting on your last few months of work. What matters is arriving at the assessment window grounded in your own perspective — not someone else’s Reddit post.</p><blockquote>“If a person who works the way you work, makes the choices you make in your day-to-day life, and communicates the way you communicate takes this assessment authentically — it couldn’t be more straightforward.”</blockquote><p>That’s the part nobody seems to write about. So I wrote it.</p><p>Good luck. Be yourself. <strong>You’ve got 30 minutes — make them honest.</strong></p><p><em>Written from personal experience. All structural information referenced is drawn from Google’s publicly available hiring FAQ. No proprietary question content is disclosed.</em></p><p><em>If this helped you, share it with someone who has a GHA sitting in their inbox right now.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4c8bbb44624" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Built a Keno Optimizer. The Most Useful Result Was Proving It Couldn’t Work.]]></title>
            <link>https://medium.com/@swadiajeet/i-built-a-keno-optimizer-the-most-useful-result-was-proving-it-couldnt-work-508e21d8796a?source=rss-e9b92d54f61c------2</link>
            <guid isPermaLink="false">https://medium.com/p/508e21d8796a</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[lottery]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Jeet S Swadia]]></dc:creator>
            <pubDate>Mon, 20 Apr 2026 18:21:42 GMT</pubDate>
            <atom:updated>2026-04-20T18:21:42.592Z</atom:updated>
            <content:encoded><![CDATA[<h3>A 10-minute deep dive into building a Streamlit ROI backtester, an LSTM sequence model, and a GPU-accelerated combinatorial search, and why the engineering matters more than the prediction.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YyOoA6AUj2YGrgSvjOc58w.avif" /></figure><p>A few months ago I started looking at Massachusetts State Lottery Keno data. Not to beat it. I knew that wasn’t possible. The MA Lottery uses a certified hardware RNG and draws 20 numbers from a field of 80 every 3 minutes from 5:04 AM to 1:01 AM the next day. That’s 400 draws a day, every day, indistinguishable from coin flips at the level of any individual draw.</p><p>What I wanted was a clean dataset and a hard, well-defined problem to build against. Something that would force me to handle real-world data hygiene, build a calibrated payout simulator, and run a few different model architectures end-to-end. Lottery data is a beautiful test bed for this exact reason: you have ground truth, you have a known-uniform distribution, and any “predictive signal” you find is by definition spurious. If your model claims 5% lift, you know with mathematical certainty that you’ve overfit.</p><p>This post walks through the architecture: the data pipeline, the Streamlit dashboard, the ROI backtester, and the three ML approaches I built (Random Forest, LSTM, GPU-accelerated combinatorial optimizer). Code lives at <a href="https://github.com/jeetswadia/keno_optimizer">github.com/jeetswadia/keno_optimizer</a>.</p><h3>The dataset</h3><p>The MA Lottery exposes draw history as a CSV with four columns:</p><pre>drawNumber, bonus, drawDate, winningNumbers</pre><p>winningNumbers is a comma-separated string of the 20 winning numbers. bonus is the multiplier for that draw (1 by default, or 3 / 4 / 5 / 10 if the Bonus number was hit). drawNumber is sequential within a day. drawDate is the lottery operating date.</p><p>The first hidden problem: <strong>there is no time column</strong>. The dashboard wants to filter by hour-of-day to answer “are my favorite numbers more frequent at 5 PM on Wednesdays”, a question that makes no statistical sense in a uniform distribution but is the kind of slice you actually need to compute to <em>show</em> the user it makes no sense. So we have to reconstruct timestamps.</p><p>Three observed regularities solve this:</p><ol><li>Every operating day contains exactly <strong>400 draws</strong>.</li><li>The first draw of each day is at <strong>5:04 AM ET</strong>.</li><li>Each subsequent draw is <strong>3 minutes</strong> apart, putting the 400th draw at <strong>1:01 AM the following day</strong>.</li></ol><p>This translates to a one-line pandas operation:</p><pre>df = df.sort_values([&quot;drawDate&quot;, &quot;drawNumber&quot;]).reset_index(drop=True)<br>df[&quot;_pos&quot;] = df.groupby(&quot;drawDate&quot;).cumcount()</pre><pre>base_offset = pd.Timedelta(hours=5, minutes=4)<br>df[&quot;drawTime&quot;] = (<br>    df[&quot;drawDate&quot;]<br>    + base_offset<br>    + pd.to_timedelta(df[&quot;_pos&quot;] * 3, unit=&quot;m&quot;)<br>)</pre><p>cumcount() gives each row its position 0..399 within its day group. The arithmetic is exact: position 0 lands at 05:04, position 399 lands at 01:01 the next day. Now we can derive Hour and DayOfWeek for filtering. This implies that draws between midnight and 1:01 AM get attributed to the <em>previous</em> drawDate, which is correct. That&#39;s the lottery&#39;s own operating-day convention.</p><p>Wrapping the whole pipeline in @st.cache_data makes Streamlit reload it once per session instead of on every interaction. For a 146,000-row CSV (one year of draws) that&#39;s the difference between a snappy app and one that hangs for three seconds on every slider tick.</p><h3>The Streamlit dashboard</h3><p>The dashboard has three jobs: filter the data, visualize it, and let the user run a backtest. Three tabs, sidebar filters that all three tabs share.</p><h3>Filter sidebar</h3><p>Date range, day-of-week multiselect, and an hour-of-day mode that’s either “all hours” or a specific hour 0 to 23. The filter is one boolean mask applied once:</p><pre>mask = (<br>    (df[&quot;drawDate&quot;].dt.date &gt;= d_start)<br>    &amp; (df[&quot;drawDate&quot;].dt.date &lt;= d_end)<br>    &amp; (df[&quot;DayOfWeek&quot;].isin(days_selected))<br>)<br>if specific_hour is not None:<br>    mask &amp;= (df[&quot;Hour&quot;] == specific_hour)</pre><pre>filtered = df.loc[mask].reset_index(drop=True)</pre><p>Every downstream visualization and the backtester operate on filtered, never on df. This keeps the contract simple and means filter changes propagate everywhere with zero extra code.</p><h3>Frequency analysis</h3><p>A Plotly bar chart of all 80 numbers, colored by their delta from the average frequency in the filtered window. Hot numbers shade red, cold numbers shade blue, average sits at neutral. The chart is exactly the visual lie that makes “lucky number” thinking feel real. Over any finite window, some numbers will be drawn more than others, and the ones that happened to be drawn more look like they’re “due to keep going” or “due to regress,” depending on which gambler’s fallacy you prefer.</p><p>When the user picks a specific hour, a second visualization unlocks: a heatmap of the top 10 most-drawn numbers at that hour, broken down by day of the week. This is the moment where the dashboard becomes pedagogical. With ~146,000 draws sliced down to one hour on one day of the week, you’re left with maybe 800 draws, small enough that random variance produces “patterns” the eye desperately wants to interpret.</p><pre>def weekly_hour_trend(df, hour, top_k=10):<br>    sub = df[df[&quot;Hour&quot;] == hour]<br>    overall = Counter()<br>    for nums in sub[&quot;winningNumbersList&quot;]:<br>        overall.update(nums)<br>    top_numbers = [n for n, _ in overall.most_common(top_k)]</pre><pre>    rows = []<br>    for day in DAY_ORDER:<br>        day_sub = sub[sub[&quot;DayOfWeek&quot;] == day]<br>        day_counter = Counter()<br>        for nums in day_sub[&quot;winningNumbersList&quot;]:<br>            day_counter.update(nums)<br>        for n in top_numbers:<br>            rows.append({&quot;Number&quot;: n, &quot;DayOfWeek&quot;: day,<br>                         &quot;Frequency&quot;: int(day_counter.get(n, 0))})<br>    return pd.DataFrame(rows)</pre><p>Counter updates in a tight loop is fast enough here. Each winningNumbersList is just 20 ints. For a year of one specific hour that&#39;s 364 × 20 = 7,280 increments per number bucket, well under a millisecond.</p><h3>The ROI backtester (the part that actually has business value)</h3><p>This is the most carefully built component because it’s the one that has to be <em>right</em>. A frequency chart that’s slightly miscolored is a UX nuisance. A backtester that gets the payout math wrong is a lie that compounds across thousands of simulated draws.</p><h3>Payout tables</h3><p>I encoded the official MA State Lottery payout tables as nested dicts:</p><pre>PAYOUTS = {<br>    1:  {1: 2.50},<br>    2:  {2: 5, 1: 1},<br>    3:  {3: 25, 2: 2.50},<br>    4:  {4: 100, 3: 4, 2: 1},<br>    5:  {5: 450, 4: 20, 3: 2},<br>    6:  {6: 1600, 5: 50, 4: 7, 3: 1},<br>    7:  {7: 5000, 6: 100, 5: 20, 4: 3, 3: 1},<br>    8:  {8: 15000, 7: 1000, 6: 50, 5: 10, 4: 2},<br>    9:  {9: 40000, 8: 4000, 7: 200, 6: 25, 5: 5, 4: 1},<br>    10: {10: 100000, 9: 10000, 8: 500, 7: 80, 6: 20, 5: 2, 0: 2},<br>    11: {11: 500000, 10: 15000, 9: 1500, 8: 250, 7: 50, 6: 10, 5: 1, 0: 2},<br>    12: {12: 1000000, 11: 25000, 10: 2500, 9: 1000, 8: 150, 7: 25, 6: 5, 0: 4},<br>}</pre><pre>BONUS_ELIGIBLE_SPOTS = set(range(1, 10))  # 1-9 only</pre><p>Two non-obvious rules trip up most ROI calculators I’ve seen online:</p><ol><li><strong>10/11/12-spot games are not Bonus eligible.</strong> Per MA rules, the $1 Bonus wager doesn’t apply to those games. So the cost-per-draw drops from $2 to $1 and the historical bonus multiplier doesn’t get applied.</li><li><strong>10/11/12-spot games include a “Match 0” prize.</strong> Pick 12 numbers and hit none of them, you win $4. This is a lottery-design quirk: once you’ve picked that many numbers, the probability of hitting zero is small enough to be worth a small payout that keeps players engaged.</li></ol><p>If you skip either rule, your ROI numbers drift several percentage points. Most amateur Keno calculators online get one or both wrong.</p><h3>The simulation loop</h3><pre>def simulate_roi(df, selected_numbers, n_draws):<br>    spots = len(selected_numbers)<br>    selected_set = set(selected_numbers)<br>    payout_table = PAYOUTS.get(spots, {})<br>    bonus_eligible = spots in BONUS_ELIGIBLE_SPOTS<br>    cost_per_draw = 2.0 if bonus_eligible else 1.0</pre><pre>    sample = df.head(n_draws)<br>    total_wagered = len(sample) * cost_per_draw<br>    total_won = 0.0<br>    hit_counter = Counter()</pre><pre>    for _, row in sample.iterrows():<br>        winning_set = set(row[&quot;winningNumbersList&quot;])<br>        matches = len(selected_set &amp; winning_set)<br>        hit_counter[matches] += 1</pre><pre>        base_prize = payout_table.get(matches, 0)<br>        if base_prize == 0:<br>            continue</pre><pre>        if bonus_eligible:<br>            mult = int(row[&quot;bonus&quot;]) if pd.notna(row[&quot;bonus&quot;]) else 1<br>            prize = base_prize * mult<br>        else:<br>            prize = base_prize</pre><pre>        total_won += prize</pre><pre>    net = total_won - total_wagered<br>    roi_pct = (net / total_wagered * 100) if total_wagered &gt; 0 else 0<br>    return {...}</pre><p>Set intersection for the match count, dict lookup for the prize, multiplier from the historical Bonus column. Output is a st.metric scorecard: total wagered, total won, net P/L, ROI percentage, biggest single win, and a histogram of how many times each match-count occurred.</p><h3>What the numbers say</h3><p>For a 5-spot game ($2/draw with Bonus) over a year of historical draws, 146,000 draws and $292,000 wagered, the expected ROI converges to roughly <strong>−27%</strong>. House edge made visible. Run it for an 8-spot game and the expected ROI sits closer to <strong>−25%</strong>. Pick exactly the 5 numbers that hit <em>most</em> often historically and replay them, and you still end up at roughly <strong>−24%</strong>. The “optimal” cherry-picked combination beats random picks by ~3 percentage points and still loses you a quarter of every dollar.</p><p>This is the result the dashboard exists to produce. Not to tell you which numbers to pick, but to show you that no choice of numbers escapes the negative expected value.</p><h3>The ML side: three models, one honest result</h3><p>The harder question: even if individual draws are random, can a model find any structure in the <em>sequence</em> of draws? Maybe there’s clock drift, maybe one ball wears down faster, maybe the RNG isn’t as uniform as advertised. These are the questions you’d want to answer if you were a regulator auditing the lottery, and they’re the same questions a model would have to find structure in to produce predictions worth anything.</p><h3>Random Forest baseline</h3><p>Frame it as 80 separate binary classification problems: for each number 1 to 80, predict whether it’ll be in the next draw given features from the recent history.</p><p>Features per number, per draw:</p><ul><li>Frequency in the last 10, 50, 200 draws</li><li>Draws since last appearance (“recency”)</li><li>Whether it appeared in the immediately previous draw</li><li>Hour of day (one-hot)</li><li>Day of week (one-hot)</li><li>Bonus multiplier of the previous draw</li></ul><p>Train a RandomForestClassifier per number on the first 80% of the data, evaluate on the held-out 20%. Measure log-loss against the baseline of predicting the marginal frequency (which by construction is 20/80 = 0.25 for every number).</p><p>Result: log-loss on the test set is statistically indistinguishable from baseline. Feature importance shows the model leaning hardest on recency and hour-of-day, which would suggest <em>some</em> time-of-day effect, except those features rank highest precisely because they have the most degrees of freedom to overfit on, not because they carry signal. Shuffle the targets and re-train, and the same features still rank “important” by the same margins.</p><p>This is the kind of result that’s only meaningful if you trust the experimental setup. Which is why the next step matters.</p><h3>LSTM sequence model</h3><p>Random Forest treats each draw as an independent sample with engineered features. An LSTM treats the whole history as a sequence and learns its own representation. If there’s any temporal structure (autocorrelation, periodicity, drift), an LSTM is well-positioned to find it.</p><p>Architecture:</p><ul><li>Input: a sliding window of the last 50 draws, one-hot encoded as a 50 × 80 binary tensor</li><li>Two stacked LSTM layers (128, 64 hidden units), dropout 0.2</li><li>Dense output layer of 80 units with sigmoid activation</li><li>Loss: binary cross-entropy averaged over the 80 outputs</li><li>Optimizer: Adam, learning rate 1e-3</li><li>Trained for 30 epochs with early stopping on validation loss</li></ul><pre>model = nn.Sequential(<br>    nn.LSTM(input_size=80, hidden_size=128, num_layers=2,<br>            dropout=0.2, batch_first=True),<br>    # ... take last hidden state ...<br>    nn.Linear(128, 80),<br>    nn.Sigmoid()<br>)</pre><p>Result: training loss decreases. Validation loss decreases for the first 3 to 5 epochs as the model learns the marginal frequency (every number appears with probability ~0.25), then plateaus exactly at the cross-entropy of that marginal. The model has learned the optimal constant predictor. After that, training loss continues to drop while validation loss starts to rise. Textbook overfitting.</p><p>Plot the predicted vs actual hit rate per number on the held-out set: the points scatter randomly around the diagonal, R² near zero. The LSTM didn’t find structure because there isn’t any to find.</p><p>This is, paradoxically, the most useful result the project produced. It’s a controlled demonstration that a moderately powerful sequence model converges to chance on truly random data. If you ever build an LSTM that <em>seems</em> to have predictive power on a similar problem, this benchmark tells you to look harder for the data leak before you celebrate.</p><h3>GPU-accelerated combinatorial optimizer</h3><p>The third script tackles a different question: of all C(80, k) possible k-spot picks, which ones would have produced the best historical ROI? For k=8, that’s 28,987,537,150 combinations. You’re not iterating that on a CPU.</p><p>The trick is vectorizing the match-count operation. Encode each historical draw as an 80-bit binary vector (1 if drawn, 0 if not), giving a [N_draws, 80] matrix. Encode each candidate pick the same way. The match count for every (pick, draw) pair is then just a matrix product of the binary tensors: one CUDA kernel call instead of N×M Python loops.</p><pre>draws = torch.tensor(draws_matrix, device=&#39;cuda&#39;, dtype=torch.float32)  # [N, 80]<br>picks = torch.tensor(picks_matrix, device=&#39;cuda&#39;, dtype=torch.float32)  # [M, 80]<br>match_counts = picks @ draws.T  # [M, N], values 0..k</pre><p>Because we can’t enumerate 29 billion combinations even on a GPU, the script samples a few million random combinations per spot size and ranks them by historical ROI. The “best” 8-spot combinations the search found beat the average random pick by roughly 2 to 3 percentage points of ROI. Exactly what you’d expect from variance in a 146,000-draw sample, no signal beyond that.</p><p>The GPU version runs the same backtest 5,000× faster than a single-threaded Python loop. Even on a problem with no signal to find, that speedup makes the whole exploratory loop feel instant, which is the point. The infrastructure is reusable for any combinatorial backtest where the payout function is cheap and the search space is huge.</p><h3>What I’d build differently</h3><p>Three things, in order of impact.</p><h3>1. Hexagonal architecture from day one</h3><p>The first version of the dashboard had Streamlit calls scattered through the data-loading code. The second version pulled all I/O into one cached function and made every analytic operation pure (DataFrame in, DataFrame out). That made every component testable in isolation and cut the time to add a new visualization from “an afternoon” to “twenty minutes.” Worth doing on day one even for a small project.</p><h3>2. Property-based tests on the payout math</h3><p>The payout tables are the single most error-prone part of the codebase, and a typo could go unnoticed for thousands of simulated draws. Property-based tests with Hypothesis (every payout entry should be positive, base 1-spot prize should equal $2.50, ROI on a fully random pick should converge to the published house edge within ε) would catch transcription errors immediately. I added unit tests after the fact; doing them first would have been faster.</p><h3>3. A “theoretical EV” baseline alongside empirical ROI</h3><p>Right now the dashboard shows you what would have happened on a specific historical sample. It doesn’t show you what <em>should</em> happen in expectation, which is the more useful number for setting the user’s prior. Adding a Monte Carlo theoretical-EV calculation per spot size (closed-form for low spots, simulation for high spots) would let users compare “what the math says I should expect” vs “what this slice of history happened to do.” That comparison is the most direct way to communicate variance.</p><h3>Why publish this</h3><p>Lottery prediction is a magnet for bad engineering. Every few months a new “Keno AI” appears on GitHub, claims an LSTM with 80% accuracy, and ships it without ever running the dumbest possible benchmark, which is “predict the marginal frequency for every number,” let alone a held-out backtest with calibrated payouts.</p><p>Building this project the right way, with reproducible preprocessing, calibrated payouts, an honest backtest, and a model evaluation that doesn’t dodge the negative result, was substantially more work than building a “look, my model gets 80% accuracy” demo. The work is mostly in the parts that have nothing to do with the model: the time reconstruction, the payout tables, the cached pipeline, the GPU-vectorized backtester. Those are the parts that transfer to other problems where signal <em>does</em> exist and the cost of being wrong is real.</p><p>That’s the whole reason this was worth shipping. The lottery isn’t predictable. The engineering is.</p><p><strong>Repo:</strong> <a href="https://github.com/jeetswadia/keno_optimizer">github.com/jeetswadia/keno_optimizer</a> <strong>Portfolio:</strong> <a href="https://jeetswadia.com/">jeetswadia.com</a> <strong>LinkedIn:</strong> <a href="https://linkedin.com/in/jeetswadia">linkedin.com/in/jeetswadia</a></p><p>If you found this useful, follow me here on Medium. I write about ML systems, agentic AI, and the engineering practices that separate prototypes from production.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=508e21d8796a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Tried to Build a Trading Bot in One Night and Found Out How Hard “Just Connect to an API”…]]></title>
            <link>https://medium.com/@swadiajeet/i-tried-to-build-a-trading-bot-in-one-night-and-found-out-how-hard-just-connect-to-an-api-617fe491365f?source=rss-e9b92d54f61c------2</link>
            <guid isPermaLink="false">https://medium.com/p/617fe491365f</guid>
            <category><![CDATA[trading-bot]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Jeet S Swadia]]></dc:creator>
            <pubDate>Wed, 15 Apr 2026 14:47:25 GMT</pubDate>
            <atom:updated>2026-04-15T14:47:25.700Z</atom:updated>
            <content:encoded><![CDATA[<h3>I Tried to Build a Trading Bot in One Night and Found Out How Hard “Just Connect to an API” Actually Is</h3><p>I had a free evening and a stupid idea: what if I built an automated trading bot for Kalshi, the prediction market exchange, using my gaming PC’s GPU to run the model locally? I’m a data scientist by day, I know Python and SQL pretty well, and I figured this would be a fun weekend project. Maybe I’d make a little money on crypto event markets. Worst case, I’d learn something.</p><p>It is now several hours later and I have not placed a single trade. I have, however, learned a tremendous amount about why “just connect to an API” is the most dishonest sentence in software engineering.</p><p>This is a journal of what actually happened. Skip to the end if you just want the lessons.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VQFmneOcyNZOb1keQotBmw.png" /></figure><h3>The Plan</h3><p>The setup was supposed to be simple. Five phases:</p><ol><li>Connect to the Kalshi API and pull market data</li><li>Store everything in a local TimescaleDB so I could query it later</li><li>Train an XGBoost model on my RTX 2060 to predict whether markets resolve YES or NO</li><li>Build a strategy layer that uses Kelly criterion to decide how much to bet</li><li>Wire it all together with safety guardrails so the thing can’t blow up my account</li></ol><p>Architecturally none of this is hard. I’ve built bigger systems at work. The unknowns were the integrations, not the logic.</p><h3>The First Hour: Everything Worked</h3><p>I pulled together a project structure, wrote a Kalshi REST client with proper RSA-PSS signing for auth, set up a Postgres container with TimescaleDB for time-series storage, and wrote ingestion scripts for both Kalshi market data and external price feeds from Coinbase and yfinance. Test connection passed. The bot saw 1,000 active markets on the demo environment.</p><p>I ran the category filter expecting to see hundreds of crypto markets. It returned zero.</p><p>This is where the night started getting interesting.</p><h3>Bug 1: The API Reorganized Itself</h3><p>My code was written assuming Kalshi markets had a category field. I checked the actual response payload and there was no such field. Categories now live on a separate object called events, which group related markets together. Markets just have an event_ticker pointing at their parent.</p><p>Fine. Rewrite the client to fetch events first, filter by category, then flatten the nested markets out. Twenty minutes of work. Re-ran the test and got back actual market data. Felt great.</p><p>Then I noticed something else in the same response. None of the price fields had the names I was expecting. Instead of yes_bid it was yes_bid_dollars. Instead of volume it was volume_fp. Kalshi had migrated from integer cents to decimal dollars at some point, and from raw counts to fixed-point integers for size fields. My snapshot capture code would store nulls for every price.</p><p>This is the kind of thing that’s invisible until something downstream breaks. I patched the field names and the dollar-to-cents conversion in the ingestion layer.</p><h3>Bug 2: The Silent Upsert</h3><p>Got 564 markets into the database. Set up a continuous snapshot collector to run every minute and capture orderbook state. Logged out, went to dinner, came back to check progress.</p><p>Database showed 564 markets. Same as before. Zero snapshots collected.</p><p>Spent twenty minutes thinking the collector was broken. It wasn’t. The collector was running, the reference sync was finding ~8,500 markets each cycle, and then the bulk upsert was crashing on every single cycle. The error never made it to my screen because it was buried in a 4,000-line SQL parameter dump that scrolled the actual exception off the top of the terminal.</p><p>When I finally captured the full log to a file, the real error turned out to be UnicodeEncodeError. Some Kalshi market title contained a character that PowerShell&#39;s default encoding (cp1252) couldn&#39;t render, which crashed Python&#39;s logger, which killed the entire process before it could write anything to the database.</p><p>Fix: set PYTHONIOENCODING=utf-8 and PYTHONUTF8=1 as environment variables. One line. Hours of confusion.</p><h3>Bug 3: The 32,767 Parameter Wall</h3><p>Restarted with UTF-8 logging. Now I could see real errors. The upsert was failing with numeric field overflow on the strike price columns.</p><p>I had defined the columns as Numeric(20, 8) thinking that was generous. Twenty digits, eight after the decimal. Plenty for any reasonable price. Except some Kalshi markets have strikes like total US debt levels or treasury issuance amounts measured in trillions, which blow past the integer-side limit of 10^12.</p><p>Fixed by changing the columns to unbounded Numeric precision and running an ALTER TABLE to update the existing schema. Postgres widened the columns in place. Restarted the collector.</p><h3>Bug 4: The Postgres Bind Parameter Limit</h3><p>While debugging Bug 3, I had also hit a separate issue: SQLAlchemy was trying to upsert all 8,500 markets in a single INSERT statement, which generated over 100,000 bind parameters. Postgres caps statements at 65,535 parameters. Statement got rejected before it even executed.</p><p>This one was actually a design flaw in my code. I had written the upsert helper as a one-shot bulk insert without thinking about parameter count. Fixed it by chunking rows into batches of about 770 at a time, well under the limit. Postgres bind parameter math is one of those things you don’t think about until you cross the threshold and then it’s all you think about.</p><h3>What Finally Worked</h3><p>After all of that, the collector started running properly. I went from 564 stale markets to 41,892 active markets across Crypto, Economics, and Financials. Snapshots accumulated at the expected rate, around 8,400 per minute. Disk usage stayed reasonable thanks to TimescaleDB’s columnar compression on chunks older than a week.</p><p>I went to bed feeling good about the night. The data pipeline was alive.</p><h3>The Twist Ending</h3><p>Woke up the next morning, checked the database. 414,000 snapshots, 42,000 markets, collection running smoothly. Time to start thinking about training.</p><p>Ran one more diagnostic query just to be thorough: how many markets have actually resolved? The answer was zero. Not “small number.” Not “a few.” Literally zero across 42,000 markets after 15 hours of collection.</p><p>Dug into it. Turns out the Kalshi demo environment opens markets, lets their close times pass, and never settles them. The whole purpose of demo is to test order flow, not to provide a realistic market lifecycle. It’s an order-routing sandbox, not a data sandbox.</p><p>I had spent the entire night building a perfect data collection pipeline that was collecting perfect data on markets that would never produce labels. You cannot train a binary classifier on a dataset where every example is unlabeled. The model needs to know which markets resolved YES and which resolved NO. Demo gives you neither.</p><p>The path forward is to switch to the production Kalshi API for data collection, with hard guardrails that make trading literally impossible at the code level. But that’s tomorrow’s problem.</p><h3>The Lessons</h3><p>A few things I’m taking away from this, in case anyone else is about to embark on a similar project:</p><p><strong>Test the actual data shape, not the documented one.</strong> APIs drift. Field names change. Categories move from one object to another. The first thing your client should do is dump the raw payload and let you eyeball it, before you write any logic that depends on field names.</p><p><strong>Always log to a file when running anything long-lived.</strong> Console output scrolls away. Errors disappear. You will lose hours debugging the wrong problem because the real exception lives at the top of a stack trace that’s no longer on your screen. Tee-Object on Windows or tee on Unix is not optional.</p><p><strong>Silent failures are the worst failures.</strong> My upsert code was returning -1 for rowcount and continuing happily, even when the underlying transaction had rolled back. I assumed the database was being updated for hours when it actually wasn’t. Add assertions. Verify state after every write. Trust nothing.</p><p><strong>The first version of any schema is wrong.</strong> I made decisions about column precision based on what felt reasonable rather than what the data actually contained. Reasonable was wrong. Whenever you pick a precision, a length, an enum set, assume real data will violate it and design for graceful widening.</p><p><strong>Sandboxes lie.</strong> The demo environment looked like production from the API surface, but the underlying lifecycle was completely different. If you’re building anything that depends on the time evolution of data and not just a single API call shape, the sandbox might not give you what you need. Find out before you commit to it.</p><p><strong>The hard part of “build a trading bot” is the data, not the trading.</strong> I have working code for Kelly sizing, order routing, partial fill handling, circuit breakers, and risk limits. I do not have a working model. The model is months away because the model needs data and the data needs time. Anyone who tells you they built a trading bot in a weekend is either lying or has not started losing money yet.</p><h3>What’s Next</h3><p>The honest status: I have a complete five-phase trading bot codebase, a running data collector, and exactly zero training examples. The next step is switching to production Kalshi for data collection, adding a read-only enforcement layer to the risk manager so trades are impossible at the code level, and waiting roughly two weeks for enough markets to resolve to support a first training run.</p><p>That model will probably be bad. The one after it might be okay. Somewhere around month three I might have something that produces a positive expected value after fees. Or I might find out that prediction markets are too efficient for a part-time data scientist with a gaming GPU to beat. Both outcomes are interesting.</p><p>I’ll write the next entry when I have something to report. Could be progress, could be failure, could be “I learned that Kalshi is unbeatable and I’m taking up disc golf instead.” Whatever happens, it’ll be honest.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=617fe491365f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>