<?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 David Arias, CFA on Medium]]></title>
        <description><![CDATA[Stories by David Arias, CFA on Medium]]></description>
        <link>https://medium.com/@davidarias2?source=rss-b60be0a222b0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Oc4Z5_2-rJVeeU8UNENbsQ.jpeg</url>
            <title>Stories by David Arias, CFA on Medium</title>
            <link>https://medium.com/@davidarias2?source=rss-b60be0a222b0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 22:30:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@davidarias2/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[A 12-agent AI investment committee for $0.09. Here’s what it decided.]]></title>
            <link>https://medium.com/@davidarias2/a-12-agent-ai-investment-committee-for-0-09-heres-what-it-decided-89c82a0a148f?source=rss-b60be0a222b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/89c82a0a148f</guid>
            <dc:creator><![CDATA[David Arias, CFA]]></dc:creator>
            <pubDate>Thu, 24 Sep 2026 22:47:00 GMT</pubDate>
            <atom:updated>2026-09-24T22:47:00.131Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>10 AI agents build the case, 2 decide, and neither judge ever reads the data. Inside GitHub’s most starred trading project (108,000 stars), tested over 68 runs with every log published.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*U4Y-zhXGYMMI5uR_.jpg" /></figure><p>On 19 September 2026, at 22:07, twelve AI agents met as an investment committee and <strong>rated Microsoft Underweight</strong>. Two minutes later the same committee met again, with the same filings, prices, models and settings, and <strong>rated it Overweight</strong>. Each meeting lasted about eight minutes and cost <strong>about $0.09</strong>.</p><p>This committee is TradingAgents, an open-source framework running here on DeepSeek’s models. To see how it can disagree with itself, it helps to know where the idea came from and how the meeting is organised.</p><h3>Three years, from one model to a whole firm</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SWm03QlrZOuB9ZRE.png" /></figure><p>Finance started with models. <a href="https://arxiv.org/abs/2303.17564">BloombergGPT</a>, published in March 2023, was a 50 billion parameter model trained on a corpus heavy with financial data. <a href="https://arxiv.org/abs/2306.06031">FinGPT</a> followed in June with open-source financial models anyone could fine-tune. You could ask either one about a filing or a headline. <strong>Neither could do anything with the answer.</strong></p><p>Agents changed that, though at first they worked alone. <a href="https://arxiv.org/abs/2311.13743">FinMem</a>, in November 2023, was a single trading agent with a layered memory and a profile you could configure. <a href="https://arxiv.org/abs/2402.18485">FinAgent</a>, in February 2024, read price charts, news and tool results together before it traded. Nobody inside either system checked the agent’s reasoning.</p><p>A fix came from general AI research. In May 2023, Yilun Du and colleagues at MIT published <a href="https://arxiv.org/abs/2305.14325">multiagent debate</a>: several copies of a model propose answers and criticise each other for a few rounds, and together they reason better and hallucinate less than one copy alone.</p><p>Finance took that idea and gave the agents job titles. <a href="https://arxiv.org/abs/2405.14767">FinRobot</a>, in May 2024, put specialised financial agents on one open-source platform. <a href="https://arxiv.org/abs/2407.06567">FinCon</a>, in July, organised its agents as a manager with analysts, a setup its authors describe as “inspired by effective real-world investment firm organizational structures,” plus a risk step that criticises past decisions. <a href="https://github.com/virattt/ai-hedge-fund">AI Hedge Fund</a>, a GitHub repository started that November, gives each agent the style of a famous investor and has more than 63,000 stars.</p><p>Committees have one more appeal for finance. Every report, argument and ruling is written down, so a person can audit exactly how a decision was reached. In December 2024, one project took the firm idea further than anyone else.</p><h3>TradingAgents</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*y5S2azrYNOz5M4bR.png" /></figure><p>By GitHub stars, <a href="https://github.com/TauricResearch/TradingAgents">TradingAgents</a> is the biggest project on that timeline: <strong>more than 108,000 stars and 20,800 forks</strong>, 22 contributors and eleven releases, published by Tauric Research under the Apache 2.0 licence.</p><p>It began as the code for <a href="https://arxiv.org/abs/2412.20138">a paper</a> by Yijia Xiao, Edward Sun, Di Luo and Wei Wang. Their abstract notes that earlier work had “largely focused on single-agent systems handling specific tasks,” and proposes a whole trading firm instead: analysts, researchers who argue, a trader, a risk team and a manager who signs off. On Apple, over the first quarter of 2024, the paper reported a <strong>26.62% cumulative return and a Sharpe ratio of 8.21</strong>, while simply holding Apple lost 5.23%.</p><p>Those results came from three stocks over three months, one backtest each, and later tests were less kind. <a href="https://arxiv.org/abs/2505.07078">FINSABER</a>, a KDD 2026 paper, tested LLM trading strategies over twenty years and more than 100 symbols and found the earlier advantages “ <strong>deteriorate significantly</strong>.” Its strategies were too cautious in bull markets and too aggressive in bear markets. <a href="https://arxiv.org/abs/2510.11695">Agent Market Arena</a>, launched in October 2025, ran four agent designs live on stocks and crypto, each on five models from OpenAI, Anthropic and Google. How a system was designed changed its behaviour far more than which model it ran on. In the authors’ words, “ <strong>model backbones contribute less to outcome variation</strong>.”</p><p>The code kept moving after the paper. Releases in 2026 widened model support to most major providers, from OpenAI, Anthropic and Google to DeepSeek and Qwen, then added structured outputs for the managers and the trader, a grounded sentiment analyst, and FRED and Polymarket data. Version 0.5.0, released on 18 September 2026, brought point-in-time data on every dated path, SEC filings as filed and grid backtests, and 0.5.1 followed six days later. Its README now calls the project “a research scaffold for studying multi-agent analysis,” and forks adapt it to Chinese A-shares and to brokers like Alpaca.</p><p><strong>Setup, a full run and a paper order at a broker are shown step by step in this video:</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FBvucb9BpJ1U%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DBvucb9BpJ1U&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FBvucb9BpJ1U%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c7caab2414afb8311f65679c478d6cb/href">https://medium.com/media/8c7caab2414afb8311f65679c478d6cb/href</a></iframe><h3>How the committee works</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*CsfNABRwlxOB2Mif.gif" /></figure><p>A run takes one stock and one date. Five stages follow in a fixed order, built with LangGraph, a library for wiring LLM calls into a graph.</p><p>First, four analysts work one after another, each with its own data tools: a market analyst for prices and indicators, a sentiment analyst for headlines and social posts, a news analyst for headlines and macro data, and a fundamentals analyst for statements and filings. Each writes a report, and only these four ever touch data. Version 0.5.0 also made that data safer: the company is identified from the ticker before anyone starts, the market analyst checks exact prices against a verified snapshot, and on past dates no source goes beyond what was known that day.</p><p>Second comes a debate with fixed sides. A bull researcher argues for buying and a bear argues against, whatever the reports say, for one round by default. Sides are assigned so that every argument meets the strongest opposing case.</p><p>Third, a research manager reads the debate and writes an investment plan with one of five ratings: Buy, Overweight, Hold, Underweight or Sell. Overweight means holding more than a normal position, Underweight less.</p><p>Fourth, a trader turns that plan into an order idea with an entry price, a stop and a size.</p><p>Fifth, three risk voices, one aggressive, one neutral and one conservative, argue about the trader’s proposal. A portfolio manager then makes the final call: a rating, a price target and a time horizon.</p><p>Once a decision’s result is known, the framework writes a short lesson into a memory log. Later runs load those lessons, limited to what was known on their own date, and in version 0.5.0 only the portfolio manager reads them.</p><p>At the end you get a rating for one stock on one date, with sizes described relative to “a standard allocation.” Turning those ratings into a portfolio is up to you.</p><p>Two design choices matter most. <strong>Only two agents decide, and nobody votes</strong>: the research manager and the portfolio manager run on DeepSeek’s larger reasoning model, Pro, and the other ten run on the faster Flash model. And <strong>neither judge reads the data</strong>.</p><p>In these runs, the four analysts read about 109,000 tokens of raw material between them. Each judge read fewer than 8,000. Of the two, the research manager sees only the bull and bear transcript, and the portfolio manager sees the plans and the risk debate. Neither sees a single analyst report. That’s intended, since the debate is supposed to boil the evidence down for the judges. It also means <strong>a ruling can depend on how an argument was worded</strong>.</p><h3>Here’s what it decided</h3><p>Across eight full runs with all twelve agents, the median cost was $0.09 at DeepSeek’s list prices on 24 September 2026, and a run took about eight minutes. More than half of everything the models wrote was hidden reasoning, produced before the visible answer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SsGohVnfdNddAVzF.png" /></figure><p>Now Microsoft. Both runs started from the same filings and the same closing price of $493.78, and both fundamentals analysts spotted the same $5.9 billion of gains on securities Microsoft had sold. They framed it differently. One called a $15.6 billion swing in other income “not purely operational.” Its counterpart in the second run called normalized income growth of 26.4% “the cleaner read, still exceptional.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3nUeNveB5wp3Vvmx.png" /></figure><p>Everything downstream followed that framing. In the first run, the bear pointed to deferred revenue growing 13% while revenue grew 17.8%. In the second, the bull read that same deferred revenue as a sign of demand. One research manager concluded that “the bear won the risk/reward argument,” and the other that “the bull’s structural case is the stronger one, but not decisive.” One trader sold and the other bought.</p><p>Position sizes narrow the gap. Underweight meant cutting to half or three quarters of a normal position, “not an exit.” Overweight meant buying a small first slice and staying at or below a normal position until the move confirmed. So <strong>the two labels point in opposite directions, while the money involved barely differs</strong>.</p><p>TradingAgents’ own README explains why this happens: model sampling is non-deterministic, and reasoning models “vary the most” and “largely ignore temperature,” the setting normally used to make output repeatable. Two runs are a single example, so they can’t show how often ratings flip. Until someone publishes reruns of the same stock on the same date, <strong>no single rating should size a position</strong>.</p><h3>Watch it run</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*uTqqnJodlxArQj8f.gif" /></figure><p>Every run in this article was recorded in <a href="https://github.com/davidalmeida90/glassbench">Glassbench</a>, an open-source workbench built around TradingAgents. It shows the twelve agents working live, stores every run in a searchable database, compares LLMs on the same setup, and sends paper orders only, never real money. All 68 runs behind this article come with the repository, including reports, tool results and reasoning, so every number here can be checked without spending anything.</p><p>One meeting costs $0.09. Trusting its verdict takes many meetings: the same stock on the same date, run again and again until you know how far the answers spread. At today’s prices, a hundred of them cost about $9.</p><p><em>Figures come from the Glassbench runs database (68 runs, read 24 September 2026), TradingAgents 0.5.0 source and the TradingAgents repository page on 25 September 2026. Costs use DeepSeek’s off-peak list prices on 24 September. Written by a TradingAgents contributor (merged fix #1370) who builds Glassbench, with no affiliation to Tauric Research. Site: </em><a href="https://davidariasfinance.com/glassbench/"><em>davidariasfinance.com/glassbench</em></a><em>. Nothing here is investment advice.</em></p><p><em>Originally published at </em><a href="http://davidariasfinance.com/scripts/_medium/ai-committee-v1/"><em>https://davidariasfinance.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89c82a0a148f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI finance skills are limited by design. Build your own!]]></title>
            <link>https://medium.com/@davidarias2/ai-finance-skills-are-limited-by-design-build-your-own-895afbbad78a?source=rss-b60be0a222b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/895afbbad78a</guid>
            <dc:creator><![CDATA[David Arias, CFA]]></dc:creator>
            <pubDate>Mon, 21 Sep 2026 00:27:55 GMT</pubDate>
            <atom:updated>2026-09-21T00:27:55.075Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Anthropic ships seventeen finance plugins. Daloopa ships twenty-three skills with 487 stars behind them. Reading the code shows where each one stops, and both packages hardcode the same number.</strong></p><p>When Anthropic shipped agent templates for financial services, the headlines wrote themselves. One widely shared piece announced templates <a href="https://medium.com/ai-analytics-diaries/claude-just-dropped-finance-agent-templates-that-can-replace-junior-analysts-in-2026-77f45e8350e3">“that can replace junior analysts in 2026”</a>. Finance LinkedIn ran with it for a week.</p><p>Almost nobody said what a skill actually is.</p><p>It’s a markdown file. Somebody writes down how to do a job, in English, and the model reads it. No retraining happened. Nothing proprietary got encoded. Ten templates shipped means somebody wrote ten documents.</p><p>That gap, between what people assumed shipped and what actually shipped, is most of the story. Anyone who reads the files finds instructions any second-year analyst could argue with, and a few of them wouldn’t survive a first-round interview.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RP4iI44MH7tKRN0D.png" /></figure><p><em>Counted from the published repositories and the dshfind marketplace, September 2026.</em></p><p><a href="https://github.com/Mesitis/financial-services-plugins">Anthropic’s collection</a> runs to seven verticals, ten agent templates, and two partner packages from LSEG and S&amp;P Global. <a href="https://github.com/daloopa/daloopa-plugin-claude">Daloopa’s plugin</a> holds twenty-three skills over an MCP server that returns fundamentals linked back to the filing line they came from, and their <a href="https://github.com/daloopa/investing">companion repo</a> is the most starred thing in this corner of GitHub.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YK3fznPYgB-O5gRb.png" /></figure><p><em>daloopa/investing, the most starred finance agent repository on GitHub.</em></p><p>487 stars, 114 forks. For scale, the whole <a href="https://dshfind.com/en/plugins/t/finance">finance category</a> on the DeepSeek Harness marketplace holds 21 plugins and its most popular one has 45 stars.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SkwjmaE-Y4QPY4OB.png" /></figure><p><em>Thirty-eight skills across the two packages, named as the repositories name them.</em></p><p>Before pulling any of this apart, it’s worth saying the obvious. It’s good work. Written by people who have clearly done the job, covering more ground than any individual builds alone, and free.</p><h3>What a well-built skill looks like</h3><p>Daloopa’s DCF does something most valuation tutorials skip. Instead of projecting revenue as a growth rate that decays toward GDP, it first tries a bottoms-up build off operational drivers, with a taxonomy covering nine sectors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vOQS6hzsnIasZ1hu.png" /></figure><p><em>Daloopa builds revenue bottoms-up from sector KPIs before falling back to a growth rate.</em></p><p>That highlighted line separates a junior model from a real one, and whoever wrote it has built both.</p><p>Anthropic’s DCF is rigorous somewhere else entirely, aimed at the spreadsheet rather than the forecast.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7WNmKxas86qOIciI.png" /></figure><p><em>Anthropic’s DCF skill, on spreadsheet discipline and stage-by-stage confirmation.</em></p><p>Two rules there that human analysts break every week. Derived cells have to be live formulas, so the model flexes when somebody changes an assumption. And the build pauses for confirmation at each stage instead of running start to finish, because a wrong margin caught after the sensitivity tables are built means redoing everything downstream.</p><p>It keeps going. Sensitivity grids need an odd number of rows so a true centre cell exists, and that centre cell has to reproduce the model’s own base case, which is a real self-check rather than decoration. Further down, a list of common errors includes “using equity beta instead of asset or unlevered beta incorrectly.” Somebody who has reviewed a lot of bad models wrote that.</p><p>So none of what follows is about sloppiness. Both packages are careful, the limits turn up anyway, and that’s what makes them worth reading.</p><h3>Both of them hardcode the same number</h3><p>Daloopa’s DCF, four sections after the KPI taxonomy:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VuIYeOKrizf8WN4Y.png" /></figure><p><em>Daloopa’s cost of equity. Premium and beta both arrive as constants.</em></p><p>Equity risk premium, 5.5%, called a standard assumption. Beta comes from market data and falls back to 1.0.</p><p>Anthropic’s DCF, different team, different data philosophy:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Q94rpbSz3O7aOMPK.png" /></figure><p><em>Anthropic’s cost of equity, written by a different team against different data.</em></p><p>Equity risk premium, 5.0 to 6.0%, called market standard.</p><p>Two teams who didn’t coordinate, reaching for the same shortcut in the same place. That coincidence is what makes this structural instead of an oversight somebody will patch.</p><p>Notice what surrounds it. Risk-free rate gets pulled live off the ten-year Treasury in both skills, correctly. Beta gets pulled from market data. Every neighbouring input is sourced, and the premium sitting between them is a number somebody typed.</p><p>Freezing the premium is the kind of thing a valuation course corrects in week three. Damodaran recomputes and republishes an implied premium every month, free, and has done for two decades. Any analyst who wrote 5.5% into a model and left it there through a rate cycle would be sent back to redo it. Yet that’s what’s shipping inside templates people described as replacing them.</p><p>Here’s what the constant costs. Same cash flows, same growth, same terminal rate, only the premium moves.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SZ5-5YfygYr38NXy.png" /></figure><p><em>Same cash flows and same terminal rate, with only the premium moving.</em></p><p>At 4.0% the company’s worth 126. At 6.5% it’s worth 88. Two thirds of the answer decided by one line of markdown, written once, applied to every company in every rate environment in every market.</p><p>Implied premiums have swung roughly between 4% and 7% over the last twenty years, widening whenever something breaks and compressing back down through the calm stretches in between, which is why anyone who values companies for a living recalculates it rather than remembering it. Freezing the midpoint works fine as a default. As a method it doesn’t survive a second question.</p><h3>Nobody sensitises the assumed input</h3><p>Both packages take sensitivity seriously. Daloopa’s DCF builds a sensitivity section. Anthropic’s builds three grids: WACC against terminal growth, a multiple grid, and beta against risk-free rate.</p><p>Look at that third one. Cost of equity equals risk-free rate plus beta times the equity risk premium, so it has three inputs. Two of them get varied, and the one held fixed, the premium sitting in the middle of the formula, is the only input in the whole calculation that nobody sourced from anywhere.</p><p>What lands on the desk is a target price wrapped in a grid of alternatives, which reads as a thorough treatment of uncertainty. And whichever assumption moved the number most isn’t in the grid.</p><h3>Where the data actually comes from</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-BoiAfYz7-T-LfE7.png" /></figure><p><em>Absent the vendor tools, the instruction is to reconnect. No free path exists.</em></p><p>Every skill in the Daloopa package goes through five vendor tools. When they’re missing, the instruction is to tell the user to reconnect. No free path exists in that package, and none was meant to.</p><p>Anthropic’s side needs a distinction, because the two halves behave differently. dcf-model is data agnostic: it reads SEC filings, uses web search for prices and beta, and works with whatever MCP servers happen to be connected. Anyone can run it today, no subscription.</p><p>Verticals are the other story. Claude for Financial Services routes through eleven connectors, Daloopa and FactSet and S&amp;P Global and Moody’s and LSEG and PitchBook and Morningstar among them, and Anthropic’s own documentation says access “may require a separate subscription or API key from the respective provider.”</p><p>So the gate is real. It sits at the data layer, not inside every skill, and saying otherwise would be easy to disprove.</p><h3>Why “by design” is the right phrase</h3><p>Three limits fall out of what a shared package has to be, and shipping more versions won’t fix any of them.</p><p>A vendor’s skill routes to that vendor. Daloopa’s skills exist so Daloopa data gets used, and report attribution defaults to their name. Wanting a free fallback inside them means wanting a company to undercut its own product, which isn’t a criticism so much as a description of how it works.</p><p>Then there’s method. A skill written for every subscriber has to strip out the judgment that separates one research process from another. Your premium source, how you build beta, what you do with leases and buybacks and stock comp, all of it collapses into somebody’s midpoint. Equity research gets differentiated by exactly the thing a general package must remove.</p><p>Last, defaults go invisible the moment they ship. A number picked as a sensible starting point ends up in every output, unsurfaced, undated, unrevisited. Nothing in the skill format nudges anyone to write “premium was 5.5%, sourced on this date, from this calculation.” Convenience quietly hardens into method.</p><p>None of that makes these packages bad. It’s what a general purpose package has to be.</p><h3>Building one is smaller than it sounds</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6t44BcDQK9JzaKG7.png" /></figure><p><em>Frontmatter and instructions in English. That is the entire skill format.</em></p><p>That’s the whole format. Name, description, an argument hint, then instructions in English. Every excerpt in this article came straight off GitHub as ordinary markdown, readable in a browser.</p><p>Which means engineering was never the barrier. Knowing what a bottom-up beta is, and why it beats a five-year regression for a company that refinanced last year, that’s the barrier.</p><p>Every DCF input has a free source.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IE0DjsrH1cKf0fxv.png" /></figure><p><em>Each input, and where it comes from without a subscription.</em></p><p>EDGAR has the filings, same place the vendors get them, and its companyfacts endpoint hands back structured XBRL for any filer. FRED has the risk-free rate. Implied premium comes out of index level, aggregate cash flows and the ten-year yield, and can carry the date it was computed. Beta gets rebuilt from unlevered sector comparables and relevered at the target&#39;s own capital structure. Cost of debt comes off a synthetic rating from interest coverage, rather than dividing last year&#39;s interest expense by average debt.</p><p>Different plumbing, same model, and an answer somebody can audit line by line.</p><h3>Fork it, don’t start from a blank page</h3><p>Nothing above argues for starting over. Beginning from one of these packages is faster and lands better, because years of process are already written down inside them.</p><p>Licensing allows more than most people assume.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*N1reiiBarFEV95JF.png" /></figure><p><em>All three packages ship Apache 2.0, which permits commercial forks.</em></p><p>All three packages here ship under Apache 2.0. Forking, modifying, republishing, selling, all permitted. Conditions are light: keep the licence text, leave attribution notices alone, say which files you changed. Trademarks are excluded, so a fork can’t imply endorsement or take the original name.</p><p>One boundary matters. Licence covers the skill, meaning the instructions and any scripts. Data behind it runs on the vendor’s own terms, a separate agreement. Forking Daloopa’s DCF gets you their method and none of their fundamentals.</p><p>So read the DCF skill end to end, which takes about twenty minutes since it’s plain English. Keep the craft: sector KPI taxonomy, the terminal value flag at 80%, formulas over hardcodes, the stage-by-stage confirmation, the odd-numbered grid whose centre cell has to reproduce the base case. Reinventing that would take months.</p><p>Then rip out the plumbing. Every input somebody else already decided for you, starting with the premium.</p><p>And add the part neither package has, where the skill prints the source and date of every assumption it used. Nothing prevents it. Once one skill does it, going back feels careless.</p><h3>What creating your own skill looks like</h3><p>Worth making concrete, so here’s one built that way, developed by me after multiples trial and errors:</p><p><a href="https://github.com/davidalmeida90/equity-research-agents">equity-research-agents</a> splits a DCF framework across two agents that are not allowed to read each other. Architect owns the generator, the schema and the 10-K facts, and is banned from expressing any view, including in its own notes. Analyst owns the scenarios and the write-up, and is forbidden from reading anything the architect produced, so the model’s implied price never becomes a target to reverse-engineer toward.</p><p>Premium in that framework is a sourced input, not a constant. Base case has to equal Damodaran’s current published value exactly, bull sits 25 to 75bps below it as a franchise-quality discount, bear 50 to 125bps above for cycle and regulatory risk. Same number, turned from an assumption into a scenario lever with a citation attached.</p><p>Rest of it is the same pattern applied elsewhere. Gross margin never held flat, five research buckets mandatory. Base case built first, bull and bear derived by perturbation. Driver attribution in basis points with a source per variable. Three retunes maximum, and retuning to silence a warning named as the thing not to do.</p><p>Repository holds the agent definitions and the written method. Generator stays private, which is the point: the method is the part worth publishing.</p><p>Skills are cheap to write. Your method isn’t, and that’s the part nobody can hand you.</p><p><em>Skill excerpts come from </em><a href="https://github.com/daloopa/daloopa-plugin-claude"><em>daloopa/daloopa-plugin-claude</em></a><em> and </em><a href="https://github.com/Mesitis/financial-services-plugins"><em>Mesitis/financial-services-plugins</em></a><em>, both public, read September 2026. Sensitivity chart is illustrative and built on the assumptions printed on it. Nothing here is investment advice.</em></p><p><em>Originally published at </em><a href="https://davidariasfinance.com/scripts/_medium/ai-skills-v2"><em>https://davidariasfinance.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=895afbbad78a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Machine Learning and Deep Learning in Finance: A Complete Guide to 10 Models]]></title>
            <link>https://medium.com/@davidarias2/machine-learning-and-deep-learning-in-finance-a-complete-guide-to-10-models-d1af41c8f3b6?source=rss-b60be0a222b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1af41c8f3b6</guid>
            <dc:creator><![CDATA[David Arias, CFA]]></dc:creator>
            <pubDate>Wed, 09 Sep 2026 22:29:27 GMT</pubDate>
            <atom:updated>2026-09-09T22:29:27.126Z</atom:updated>
            <content:encoded><![CDATA[<p>Trees, neural networks and real market data, with the code for every one. Three of the ten lost to a baseline that costs nothing, and that result stays in.</p><p>Most articles about machine learning in finance show a model, report a number, and stop. Stopping there is the problem, because a number on its own never answers the question a desk actually asks, which is whether something simpler would have done the same job for nothing.</p><p>Ten models run below on real market data. Five from the classical side, decision trees through Lasso, and five neural networks, feed forward through autoencoders. Each one is pointed at a task that suits its structure rather than at whatever produces the prettiest curve. Every split is by date. Every data source is free.</p><p>Section 5 then does the part that usually gets skipped. It scores the two sequence models and the convolutional net against baselines that cost nothing, on the identical rows, and all three lose. That result stays in.</p><p>Code first, since that is what most people want. Both repositories run top to bottom on free data, and every chart in this article is reproduced by the scripts that made it. <a href="https://github.com/davidalmeida90/machine-learning-for-finance">Classical models are here</a> and <a href="https://github.com/davidalmeida90/deep-learning-for-finance">the neural networks and the baselines are here</a>.</p><p><a href="https://github.com/davidalmeida90/deep-learning-for-finance">https://github.com/davidalmeida90/deep-learning-for-finance</a></p><h3>Watch my video on deep learning in live trading, step by step</h3><p>Video below takes the same ideas the whole way: 94 firm characteristics into a neural network, predictions ranked into a long short book, then wired to the Interactive Brokers API so the model places its own orders rather than printing a backtest. Subtitles in English, Portuguese and Spanish.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fj-uwUwr3aXw%3Fstart%3D2%26feature%3Doembed%26start%3D2&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dj-uwUwr3aXw&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fj-uwUwr3aXw%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/3168d76d793f1559c349229bc925d549/href">https://medium.com/media/3168d76d793f1559c349229bc925d549/href</a></iframe><h3>1. Glossary, so nothing later needs unpacking</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*m3NMXkuUKDryPaXb.png" /></figure><h3>1.1 Supervised, unsupervised, and why it matters here</h3><p>A supervised model gets features and an answer, and learns the map between them. Eight of the ten below are supervised. Unsupervised models get features and no answer, and are asked to describe structure instead of predicting it. PCA and the autoencoder are the two, and they turn out to be the most reliable pair in the article, which is not a coincidence. Describing structure that genuinely exists is a far easier problem than forecasting a return.</p><h3>1.2 Splitting by date, and why random splitting is a lie</h3><p>Shuffling rows and holding out 20% is standard in machine learning and invalid in finance. Prices are autocorrelated, so a shuffled test set contains days that sit between two training days, and the model interpolates rather than forecasts. Every result here splits at a date: everything before it trains, everything after it is scored. Section 4.1 is the single exception, and it says so, because fitting a surface quoted at one instant carries no time ordering to respect.</p><h3>1.3 Survivorship, the bias that flatters everything</h3><p>Downloading today’s S&amp;P 500 list and running it back to 2007 tests a strategy on companies already known to have survived. Membership here is rebuilt point in time from index history, so a company that was in the index in 2011 and gone by 2015 is present until it left and absent after. That yields 640 tickers with usable data and a median of 342 members on any given day.</p><p>Rebuilding membership is four lines of pandas: start every ticker as absent, walk the index revisions in date order, and switch on the names present at each revision. Every feature is then computed through that mask, so a company contributes rows only on the days it was actually in the index. Removing the mask and using today’s list instead lifts the headline numbers, which is exactly why so many published backtests look better than they are.</p><pre>mask = pd.DataFrame(False, index=days, columns=universe)<br>for date, members in membership.items():          # one row per index revision<br>    mask.loc[date:, :] = False<br>    mask.loc[date:, [m for m in members if m in mask.columns]] = True<br>print(f&quot;{px.shape[1]} of {len(universe)} tickers with data&quot;)<br>print(f&quot;median members on a day: {int(mask.sum(axis=1).median())}&quot;)<br># 640 of 959 tickers with data<br># median members on a day: 342</pre><p>Every feature below is computed <em>through</em> that mask, so a company contributes rows only on the days it was actually in the index. Removing the mask and using today’s list instead lifts the headline numbers, which is exactly why so many published backtests look better than they are.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tpq5Mac5vy4SrWVr.png" /></figure><p><em>Grey is how many companies were index members that day. Green is how many of those have price data. Gap is the part a survivorship free universe refuses to pretend away.</em></p><h3>1.4 How to read the numbers</h3><p>Classification models are scored with AUC, where 0.50 is a coin flip. Forecasts are scored with correlation against what actually happened, and with RMSE in the units of the target. Trading results are reported as return per day of a long short book with a t statistic, before costs. No figure below has transaction costs in it, and none of it is a backtest with money in it.</p><h3>2. Trees, and a published strategy rebuilt</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*g9HGLBT1YGrYbqYv.png" /></figure><p><em>What each section was actually fed, and what it was asked for.</em></p><p>Sections 2.1 to 2.3 rebuild the tree based half of Krauss, Do and Huck (2017), <em>Deep neural networks, gradient boosted trees, random forests: Statistical arbitrage on the S&amp;P 500</em>, on free data. Same construction: train on 750 days, trade the next 250, step forward and refit. Features are cumulative returns over 1 to 20 days and then 40, 60 up to 240, standardised across the cross section of each day. Target is whether a stock beats the median stock tomorrow. Trade only the extremes, long the ten highest probabilities and short the ten lowest.</p><p>Features are cumulative returns over 1 to 20 days, then 40, 60 and so on to 240, each standardised across the cross section of its own day. Standardising that way is what makes the target relative: on every single day half the names are labelled one and half are labelled zero, so a model cannot win by learning that markets drift upward. Windows then roll, refitting from scratch each time, and only the ten highest and ten lowest probabilities of each day are traded.</p><p>Standardising across the cross section of each day is what makes the target relative. A model cannot win by learning that markets drift upward, because on every single day half the names are labelled one and half are labelled zero.</p><h3>2.1 Decision tree</h3><p>One tree, grown alone, splitting on whichever threshold removes the most uncertainty until each leaf holds a rule you can read in English. Accuracy sits below every ensemble in this article, and credit committees sign it anyway, because a regulator asking why an application was declined wants a reason code rather than a SHAP plot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Sk3QjIMzzn8jcCzX.png" /></figure><p><em>Depth three, eight leaves. Short term reversal is the first thing it finds. Most leaves hold 0.49 to 0.52, which is why AUC lands near 0.51, and the one useful leaf holds 0.584 on 0.6% of the rows.</em></p><p>Out of sample it returns <strong>0.055% a day</strong> with a t statistic of 2.02. Same sign as the paper, a fraction of the size.</p><h3>2.2 Random forest</h3><p>Hundreds of trees, each grown on its own bootstrap sample and allowed to see only a random subset of columns at every split. Answer is the vote. That double randomisation decorrelates the trees so averaging cancels variance instead of compounding it.</p><p>Out of sample: <strong>0.160% a day, t = 4.80</strong>. Paper reports 0.43% a day at t = 14.93 on its own period, so this reproduces at roughly <strong>37%</strong> of the published effect.</p><h3>2.3 Gradient boosting</h3><p>Trees built one after another, each fitting the error the ensemble has left rather than the target itself, with the second derivative of the loss sizing how far each leaf may move.</p><p>Out of sample: <strong>0.123% a day, t = 3.36</strong>, about <strong>33%</strong> of the 0.37% the paper reports for the same family.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_Xi_nNdQxmCnTTL_.png" /></figure><p><em>Five windows, 1,250 trading days, every window positive for all three models. Consistency matters more than the average, because a strategy carried by one lucky year looks identical to a real one once you take the mean.</em></p><p>Two facts hold at once here, and holding them together is the whole skill. AUC is <strong>0.51 against a coin flip’s 0.50</strong>, which is nearly nothing. And the book still earns a real spread, because it only ever touches the two ends of the ranking, where the thin edge concentrates. A model can be almost useless as a classifier and still be tradeable as a sort.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*p3yUlSHoH8L377ef.png" /></figure><p><em>Window by window, before costs. Fifteen cells, all positive.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6odVrtZSu2FwOs5P.png" /></figure><p><em>Published result against this replication, on free data and a shorter period.</em></p><h3>2.4 Why AUC near 0.51 still pays</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*C4u_V7ZYCXtJ1Opj.png" /></figure><p><em>In sample against out of sample. Gap between the two curves is the memorisation, and what survives it is the thin edge the book actually trades.</em></p><p>Ranking accuracy of 0.51 sounds like nothing, and it is nothing across the middle of the distribution. A long short book never touches the middle. It takes the ten highest and the ten lowest probabilities of each day, where the edge concentrates, and leaves the other 320 names alone. Same model, judged as a classifier, is close to useless; judged as a sort, it is tradeable.</p><h3>2.5 What happens when the same code runs to 2025</h3><p>Same code, wider period. Effect decays hard. Roughly a sixth of a percent a day before costs on the years the paper covers, and roughly a thirtieth of that by 2025. That decay is the most useful single number in this article, because it is what a strategy looks like after a decade of being published, read and competed away.</p><blockquote><em>A peer reviewed, widely cited strategy delivers roughly a sixth of a percent a day before costs on the period it was written about, and roughly a thirtieth of that by 2025. Any backtest reporting far more, on free daily data and price features alone, is worth reading twice.</em></blockquote><h3>3. Unsupervised and sparse</h3><h3>3.1 PCA on the Treasury curve</h3><p>PCA is not a predictor. It rotates correlated variables into uncorrelated ones ordered by how much variance each carries. Run it on the daily <em>changes</em> of ten Treasury maturities, never the levels, and the first three components arrive with shapes that have names.</p><p>Three lines of scikit-learn do it, and one detail carries the result: the fit runs on daily <em>changes</em> of the ten maturities, never on the levels. Levels are non stationary and the first component would simply track the general level of rates. Changes give the structure that actually moves.</p><pre>tenors = [&quot;DGS3MO&quot;,&quot;DGS6MO&quot;,&quot;DGS1&quot;,&quot;DGS2&quot;,&quot;DGS3&quot;,&quot;DGS5&quot;,&quot;DGS7&quot;,&quot;DGS10&quot;,&quot;DGS20&quot;,&quot;DGS30&quot;]<br>curve = fred(tenors).dropna()<br>p = PCA(n_components=5).fit(curve.diff().dropna())   # CHANGES, not levels<br>print(p.explained_variance_ratio_)<br># [0.7827 0.1351 0.0386 0.0190 0.0079]<br>level, slope, curvature = p.components_[:3]<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XeqRX73bsaD3pxlD.png" /></figure><p><em>Nobody told the model about level, slope or curvature. It recovered all three from the covariance of ten maturities, and they hold their shape across regimes, which is why a three factor hedge does not need refitting every month.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/0*tQ9ffZTsQNuRLefc.png" /></figure><p><em>First component alone carries 78%. Three carry 95.64%, and the remaining seven maturities are noise around them.</em></p><p><strong>95.64% of daily variation in three components.</strong> Cover three risks instead of ten that move together, and the components hold their shape across regimes.</p><h3>3.2 Lasso</h3><p>Linear regression carrying a penalty on the size of its own coefficients. L1 puts corners on the constraint region, so coefficients land on exactly zero and variables drop out during the fit rather than after it. With fifty candidate signals and twenty years of data, ordinary least squares fits noise and reports it as skill.</p><p>Cross validation folds are temporal here, never shuffled, which matters more than the penalty itself. A shuffled fold lets the model tune its penalty on data from the future of its own training set, and the selected feature list stops meaning anything.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1013/0*1Iuq3ilwfm-iXhfk.png" /></figure><p><em>Eight survivors out of fifty. Selection is the output here, not the R squared.</em></p><p>Out of sample R² of <strong>0.0908</strong> on 21 day returns, against <strong>−0.0080</strong> for predicting the mean. Small, and pointed in the right direction.</p><h3>4. Neural networks</h3><p>Trees stop somewhere. A network only earns its cost when the data has a shape a table cannot hold: a smile across strikes, a sequence with memory, a picture, a cross section with hidden factors. Five architectures, each on the job it was invented for.</p><h3>4.1 Feed forward, on the volatility surface</h3><p>Plainest architecture there is. Every input reaches every unit of the next layer, each unit sums what arrives, bends it through a non linear function and passes it on. No memory between calls. Feed it log moneyness and maturity, get one number back, and that number is a point on an implied volatility surface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/0*SqeY7hmRKsuZGNfr.png" /></figure><p><em>Two inputs, two hidden layers of 96 units, one output. Every quote is an independent observation, which is honest here because a surface at a single instant carries no time ordering.</em></p><p>Fitted on <strong>998 live SPY quotes</strong>, out of the money only, because a call and a put on one strike carry different quoted vols and feeding both teaches the net to average two different things. Held out error settles at <strong>0.251 volatility points</strong>, inside the bid ask spread on most of the chain.</p><p>Quotes come from the first sixteen expiries as they stand right now, out of the money only, filtered on volume and bid so stale strikes drop out. Network is three hidden layers of 96 units with a tanh between each, which is more capacity than the problem needs and trains in seconds on a thousand points.</p><pre>for exp in spy.options[:16]:<br>    ch = spy.option_chain(exp)<br>    for df, side in ((ch.calls, &quot;c&quot;), (ch.puts, &quot;p&quot;)):<br>        d = df[(df.impliedVolatility &gt; 0.03) &amp; (df.volume &gt; 5) &amp; (df.bid &gt; 0.05)]<br>        d = d[d.strike &gt;= spot] if side == &quot;c&quot; else d[d.strike &lt; spot]   # OTM only<br>        rows += [(np.log(k / spot), t, iv) for k, iv in zip(d.strike, d.impliedVolatility)]<br>ffn = nn.Sequential(nn.Linear(2, 96), nn.Tanh(), nn.Linear(96, 96), nn.Tanh(),<br>                    nn.Linear(96, 96), nn.Tanh(), nn.Linear(96, 1))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/0*LA5rt_LZJDQVrWc_.png" /></figure><p><em>Four maturities from the fitted surface drawn over the quotes that trained it. Skew is steep and one sided, and that gap narrows as maturity lengthens.</em></p><p>Honest caveat, and section 5 does not reach this one: interpolating a surface is not forecasting. A spline or an SVI fit would do the same job and respect no arbitrage conditions, which this network does not.</p><h3>4.2 Recurrent, on volatility that remembers</h3><p>One addition changes everything. A hidden state travels from step to step, so the network reads a sequence in order and what it saw yesterday still colours today. An LSTM wraps that state in gates deciding what to keep and what to drop, which is how forty days survive instead of fading after five.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FXEc3GJ7cWvZar7W.png" /></figure><p><em>Same series twice. Sign of the daily return, on top, has almost no structure to hold on to. Size of that same return, underneath, arrives in clusters lasting weeks. Clustering is what a recurrent cell is built to carry.</em></p><p>Windows are built by hand rather than with a library: forty days of absolute returns in, realised volatility over the following ten days out, and the split is taken at 75% of the timeline rather than at random. Feature is the <em>size</em> of each move and never its sign, because the sign is the part that does not persist.</p><pre>fwd_vol = r[::-1].rolling(FWD).std()[::-1].shift(-1) * np.sqrt(252)<br>feat    = np.abs(r.values) * np.sqrt(252)          # size of the move, not its sign<br>cut = int(len(Xs) * 0.75)                          # split in TIME, never shuffled<br>class LSTMVol(nn.Module):<br>    def __init__(s, h=48):<br>        super().__init__(); s.l = nn.LSTM(1, h, batch_first=True); s.o = nn.Linear(h, 1)<br>    def forward(s, x): return s.o(s.l(x)[0][:, -1])   # last hidden state carries the window</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/0*O6gXj6AdB-XDktox.png" /></figure><p><em>Forecast against what happened, out of sample. Level and turning points come through, and the April 2025 spike above 70% annualised is caught rather than missed, though a step late, which is what a lagging feature always does.</em></p><p>Trained to 7 September 2021 and pushed forward on <strong>4,978 windows</strong>, correlation with realised volatility over the next ten days comes to <strong>0.457</strong>, RMSE 7.74 volatility points.</p><h3>4.3 Convolutional, reading a chart as a picture</h3><p>Convolution slides a small filter across an input and asks the same question at every position. Following Jiang, Kelly and Xiu (2023), <em>(Re-)Imag(in)ing Price Trends</em>, twenty trading days are rendered as a bar chart image, three pixels per day, and prices are rescaled inside each window so level disappears and only shape survives.</p><p>Each day gets three columns of pixels: a tick on the left for the open, the high to low bar in the middle, a tick on the right for the close, and a volume strip along the bottom. Prices are rescaled inside each window, so a 400 dollar stock and a 40 dollar stock produce the same picture when they move the same way.</p><pre># three pixels a day: open tick, high to low bar, close tick<br>img[esc(o[d]),           x    ] = 1.0<br>img[esc(l[d]):esc(h[d]), x + 1] = 1.0<br>img[esc(c[d]),           x + 2] = 1.0</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/0*INKVp10rIolmCWbQ.png" /></figure><p><em>What the network actually reads. 153,000 of these across 45 names, labelled with the volatility that followed.</em></p><p>Ask it which way the name goes and a coin does as well: four runs of identical code returned quintile spreads of 0.19, 0.18, 0.01 and 0.16 percentage points. Spread that moves that much between runs is not a result. Ask how much it moves and the picture answers, with the quietest quintile realising <strong>22.9%</strong> volatility against <strong>30.6%</strong> for the wildest.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/0*rPROXtiJDuTKjrIi.png" /></figure><p><em>Out of sample, sorted only by what the network read off the picture. Every step rises, which is the shape a real signal makes. Section 5.3 then puts it beside a baseline.</em></p><h3>4.4 Transformer, and where attention actually pays</h3><p>Attention replaces the chain. Every day in the window looks at every other day at once, and a learned score sets the weight each one carries. Query, key and value do the work. Same mechanism sits under every large language model.</p><p>Block is deliberately minimal: project each day to 32 dimensions, add a learned position code, one four head attention layer, a residual and a layer norm, then read the last position. Nothing else, so whatever the attention map shows is the attention and not a stack of other machinery.</p><pre>class Attn(nn.Module):<br>    def __init__(s, d=32):<br>        super().__init__()<br>        s.p   = nn.Linear(1, d)<br>        s.pos = nn.Parameter(torch.randn(1, LOOK, d) * 0.02)   # learned position codes<br>        s.a   = nn.MultiheadAttention(d, 4, batch_first=True)<br>        s.n   = nn.LayerNorm(d); s.o = nn.Linear(d, 1)<br>    def forward(s, x, want=False):<br>        h = s.p(x) + s.pos<br>        z, w = s.a(h, h, h, need_weights=want, average_attn_weights=True)<br>        return s.o(s.n(h + z)[:, -1]), w                       # residual, then last position</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*F3z3fxFfb2bYtHqe.png" /></figure><p><em>Averaged over 256 out of sample windows. Weight collapses onto the final eight or so days and the first thirty contribute almost nothing.</em></p><p>On the same volatility target: correlation <strong>0.446</strong>, RMSE 7.81. Read alone that looks like a narrow loss to the LSTM. Section 5 retrains both five times and shows the gap sits inside the noise.</p><p>Forty daily numbers is a toy sequence for attention. Text is where transformers genuinely pay in finance: FinBERT and its descendants read filings, earnings calls and news into a sentiment score, and the attention map shows which sentence moved it. Nothing of that kind was trained here.</p><h3>4.5 Autoencoder, and what survives a squeeze</h3><p>An autoencoder learns by rebuilding its own input. Daily returns of 45 names go in, get squeezed through three units, and come back out. Nothing supervises it, so those three have to carry whatever is common across the cross section.</p><p>Encoder takes 45 returns to 3 numbers, decoder takes them back to 45, and the loss is simply how badly the rebuild misses. Nothing supervises it. Reconstruction error per day is then a second output for free, and it is the one that dates the stress.</p><pre>def forward(self, x):<br>    z = self.enc(x)                     # 45 names squeezed into 3<br>    return self.dec(z), z<br>rec, z = ae(returns)<br>erro = ((returns - rec) ** 2).mean(1)   # a day that stopped behaving</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/0*t9lpo_iP2v0P9K4_.png" /></figure><p><em>Nobody mentioned sectors. Unit one splits tech from energy, unit two runs cyclical against defensive, unit three holds the defensives on their own.</em></p><p><strong>35.0% of the variance of 45 names through three units</strong>, out of sample over 3,440 days. Two uses fall out of that. What the units hold is a factor set for hedging and for residuals in statistical arbitrage. What the rebuild misses is a day the cross section stopped behaving, and out of sample the worst one lands on <strong>9 April 2025</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/993/0*qM-c8J6ryAuNkE1k.png" /></figure><p><em>Days the rebuild fails, out of sample. Spikes are days the cross section stopped moving together, which is the same thing a risk model calls a regime break.</em></p><h3>5. Baselines that beat them</h3><p>Every number above was scored on its own, which answers whether a model learned something and leaves open whether anything simpler would have done as well. Below, each baseline runs on the identical windows, rows and date split.</p><h3>5.1 Volatility: four fitted coefficients beat both networks</h3><p>Three baselines for the ten day forward volatility target of sections 4.2 and 4.4. Persistence takes the realised volatility of the last ten days and predicts it continues. EWMA is the RiskMetrics filter at decay 0.94. HAR-RV, from Corsi (2009), regresses forward volatility on daily, weekly and monthly realised volatility. Four coefficients, fitted on the training block, frozen.</p><p>Whole model is four coefficients: an intercept plus realised volatility over the last day, the last week and the last month, fitted once by least squares on the training block and then frozen. That is the entire competitor, and it is the one that wins.</p><pre>r2 = r ** 2                                            # squared daily log returns<br>rv1  = np.sqrt(r2) * np.sqrt(252)                      # today<br>rv5  = np.sqrt(r2.rolling(5).mean()) * np.sqrt(252)    # last week<br>rv22 = np.sqrt(r2.rolling(22).mean()) * np.sqrt(252)   # last month<br>A = np.c_[np.ones(len(rv1)), rv1, rv5, rv22]<br>beta, *_ = np.linalg.lstsq(A[:cut], fwd_vol[:cut], rcond=None)   # training block only<br>har = A[cut:] @ beta                                              # out of sample</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/0*aBSd2glcpq5x7gNE.png" /></figure><p><em>Every method on the same 1,245 out of sample windows. Whiskers are the range across five seeds. HAR-RV sits above the best seed of either network, and plain persistence sits above both means.</em></p><p>Persistence and EWMA both reach <strong>0.49</strong>. HAR-RV reaches <strong>0.53</strong>. Both networks were then retrained five times from different seeds: LSTM averaged <strong>0.46</strong>, transformer <strong>0.43</strong>.</p><p>Reading is uncomfortable and clear. Ten day volatility on SPY is forecastable, and on forty daily absolute returns a linear model with the right three features extracts more of it than a recurrent cell or an attention head, at a fraction of the cost. Sections 4.2 and 4.4 stand as demonstrations of how each architecture reads a sequence. As forecasts they lose to the boring thing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*r4aLe8AP9xADsSH-.png" /></figure><p><em>Every method on the same target, the same windows and the same split.</em></p><h3>5.2 LSTM against transformer, read against the seeds</h3><p>Seed by seed, LSTM minus transformer: 0.000, 0.013, 0.015, 0.104, 0.006. Three of five gaps sit inside 0.015, one is zero, and the mean is carried almost entirely by a single transformer seed that collapsed to 0.384. Fair verdict on a sequence this short is that neither separates, and the transformer is the less stable of the two. Any article declaring a winner on one run of each is declaring a winner on noise.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Fs5cyUavvMg8c4U-.png" /></figure><p><em>Five seeds each. One collapsed transformer run carries the whole average gap.</em></p><h3>5.3 The number the picture was denied</h3><p>Section 4.3 rescales prices inside each window so only shape survives. Right design for a direction question, and for a magnitude question it throws away the most useful number available, which is how much the name moved over those same twenty days. Scoring that single number on the identical 38,250 out of sample rows gives correlation <strong>0.513</strong> against <strong>0.225</strong> for the network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/0*vCCkAWTXn60sTQGR.png" /></figure><p><em>Same rows, two sorts. Trailing realised volatility spreads the quintiles from 18% to 36%. Shape alone spreads them from 23% to 31%.</em></p><p>Convolution did recover a real signal from shape. Number it never saw carries more than twice as much.</p><h3>6. Everything on one line</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XWPSNZ9JM2Bs0xNP.png" /></figure><p><em>Out of sample throughout. Red rows lost to a baseline that costs nothing.</em></p><p>Matching the architecture to the shape of the data is half the lesson. A static map got a feed forward net and landed inside the spread. Correlated maturities got PCA and gave up level, slope and curvature. A cross section got an autoencoder and gave up its sectors.</p><p>Other half costs more to learn. Volatility is forecastable, and here a four coefficient linear model forecasts it better than either sequence network, while the single number the CNN was denied forecasts it better than the CNN. Deep learning earns its cost when the input holds structure a linear model cannot: a cross section, an order book, a filing. On forty daily numbers it did not.</p><h3>7. Limitations</h3><p>No transaction costs anywhere. No commission, spread, slippage, borrow or impact. Quintile ladders are sorts rather than strategies, and nothing here is a backtest with money in it.</p><p>Forty five names is a sample and not a market, all of them alive today, which is survivorship bias by construction in sections 4.3 and 4.5. Volatility windows overlap heavily, so two consecutive labels share nine of their ten days and 4,978 windows are nowhere near 4,978 independent observations. Headline figures come from single runs with a fixed seed, except where section 5 reports five. Adjusted prices carry today’s split and dividend factors back through history, which is standard practice and still not strictly point in time.</p><p>None of that makes the exercise pointless. It makes it a set of worked examples, each showing which architecture suits which shape of data, with the failures kept in view beside the successes.</p><h3>Code</h3><p>Article carries no code blocks on purpose, because the point of each section is the result and the reasoning rather than the syntax. Every snippet behind it is public, split into five gists in reading order, and both full repositories run top to bottom on free data.</p><p>1. Universe, the point in time mask and the sliding window: <a href="https://gist.github.com/davidalmeida90/f8667e2704c21b2ec88bbc48d56fb489">https://gist.github.com/davidalmeida90/f8667e2704c21b2ec88bbc48d56fb489</a></p><p>2. PCA on the Treasury curve, and Lasso with temporal folds: <a href="https://gist.github.com/davidalmeida90/c0f1ac5c48ea2ece940353f06abb0eed">https://gist.github.com/davidalmeida90/c0f1ac5c48ea2ece940353f06abb0eed</a></p><p>3. Volatility surface fit, and the LSTM: <a href="https://gist.github.com/davidalmeida90/899b9e37763def575f871450648021c5">https://gist.github.com/davidalmeida90/899b9e37763def575f871450648021c5</a></p><p>4. Rendering a window as an image, and the attention block: <a href="https://gist.github.com/davidalmeida90/f716aab411c4cae3a52264c6a5d24eb4">https://gist.github.com/davidalmeida90/f716aab411c4cae3a52264c6a5d24eb4</a></p><p>5. Autoencoder, and HAR-RV in full: <a href="https://gist.github.com/davidalmeida90/22dbcea1aa64bbfeaedce5789b0d3714">https://gist.github.com/davidalmeida90/22dbcea1aa64bbfeaedce5789b0d3714</a></p><h3>Where to go next</h3><p>Repositories are linked at the top, and both run on free data with no API keys. Longer write ups, with every step, every chart and the limitations in full, live at <a href="https://davidariasfinance.com/scripts/machine-learning-for-finance/">machine learning for finance</a> and <a href="https://davidariasfinance.com/scripts/deep-learning-for-finance/">deep learning for finance</a>.</p><p><em>Originally published at </em><a href="https://davidariasfinance.com/scripts/_medium/ml-dl-v10/"><em>https://davidariasfinance.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1af41c8f3b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Is Brazil “carrying” the EM currency game?]]></title>
            <link>https://medium.com/@davidarias2/is-brazil-carrying-the-em-currency-game-9e5c677170dc?source=rss-b60be0a222b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e5c677170dc</guid>
            <dc:creator><![CDATA[David Arias, CFA]]></dc:creator>
            <pubDate>Mon, 03 Nov 2025 19:18:02 GMT</pubDate>
            <atom:updated>2025-11-03T19:57:48.390Z</atom:updated>
            <content:encoded><![CDATA[<h3>Carry returns and Implied Volatility</h3><p>EM currencies have higher interest rates, but are also high-risk currencies due to high volatility, instability and lowe liquidity. But they can also offer high returns in case there’s no or little currency depreciation. The carry trading can be an effective strategy to absorb the high interest rate differentials between high-yield and low-yield countries. In the past 12 months, it offered extra returns due to EM currencies’ appreciation in comparison with the dollar.</p><p>Brazil’s BRL returned nearly 17% carry returns, and 1-month option volatility nearly halved (-42%) in the last year, being one of the leading carry returns among currencies in the past year. This factor can be explained by Brazilian high interest rates, central bank discipline, inflation control, weakening dollar, US rate cuts, and the decline in the USD/BRL IV. Recently, US Republican senators voted to end Brazil tariffs, which helped to reduce geopolitical risk.</p><p>In the following graph, we can also see that the Colombian peso delivered 18% carry returns. Although its monthly IV declined less in comparison with BRL, the same can be said for the Turkish lira (20% carry returns and -32% in IV).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-h4gfmOoveSGD5-utYGYLw.png" /></figure><p><em>NOTE: outliers such as russian ruble, which had carry returns over 40% and Indian Rupee, with a high change in the IV were not considered in the plot, altough the russian suble was the big winner last year in terms of returns.</em></p><h3>Options are cheaper, but less for BRL exposition protection</h3><p>The BRL, similarly to other EM currencies, has always suffered from high volatility due to political and economic instability. As it is possible to see, the real faced high losses in November 2024 due to low confidence in the Brazilian government to maintain its fiscal budget. There was also a short-term depreciation in April due to Liberation Day, but after that, there has been an appreciation trend.</p><p>The IV hit new lows, reflecting that USD/BRL options are cheaper, indicating a positive sentiment for the currency pair, less market fear, and a constructive outlook for the brazilian economy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IqFjEqwbQKTqIyzsirSJ_g.png" /></figure><p>At the same time, the risk reversal increased (Delta 25 IV OTM calls — Delta 25 IV OTM puts), meaning that USD/BRL OTM calls IV reduced much less than USD/BRL OTM puts. In conclusion, hedging positions in BRL can remain pricey even by opting for the most affordable calls.</p><p>In this case, if the investor is interested in hedging their BRL currency exposure and has a high tolerance for gamma risk, it might be more cost-effective (delta per dollar) to buy ATM calls, knowing that hedge positions will break faster.</p><p>On the other hand, there’s a larger discount if the investor is interested in betting against the dollar by buying OTM puts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TZk-EJMfbkzWfow8gZhHXA.png" /></figure><h3>A good risk-adjusted return?</h3><p>In comparison with some peers, Brazil’s BRL reached a high one-month carry-to-volatility ratio, indicating that BRL carry trading can attract investors seeking yield without excessive risk. The increase in IV for the Indian rupee made Brazil take the lead, although it is still behind the Russian ruble.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4AkAEuqEG4ZKl3ik2YjXcw.png" /></figure><h3>Conclusion</h3><p>Although considered a risky strategy that can face potential huge losses, carry trading using the Brazilian currency has shown a very positive risk-adjusted return in the past 12 months. This can imply a series of possible strategies for asset managers:</p><p><strong>Portfolio optimization with leveraged positions:</strong> EM government bonds are in general low-correlated with developed-country equities and bonds. To avoid specific risk, the carry trading strategy can also be used in a pool of EM currencies.</p><p><strong>Hedging dollar positions:</strong> Although the S&amp;P got stellar returns this year, the dollar depreciation reduced potential gains. If the dollar keeps its depreciation trend, a carry-trading strategy can be a way to cover part of the currency losses. Moreover, OTM USD/BRL put options have historically lower premiums.</p><p><strong>Macro strategies:</strong> Although there are a lot of uncertainties regarding fiscal policies, there has been discipline in the Brazilian central bank to control inflation, which can drive bonds prices upwards.</p><p><strong>Hedging BRL positions:</strong> The decline in USD/BRL IV makes it more attractive for portfolios with BRL exposure to make temporary hedging. Near-ATM options, although more expensive, might be cost-effective due to the high IV smile.</p><p><strong>Short risk-reversal:</strong> Generally used in stock options (and not sure if commonly used for currencies). A strategy that consists of selling a USD/BRL call and buying a USD/BRL put. This is a way to take a bearish position in the US dollar, and at the same time express a view that the IV skew will increase. This can be viable only if there’s enough liquidity and a very high risk appetite.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e5c677170dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Volatility skew in bull markets for year-end earnings, time to hedge?]]></title>
            <link>https://medium.com/@davidarias2/volatility-skew-in-bull-markets-for-year-end-earnings-time-to-hedge-5f25dd61c3ff?source=rss-b60be0a222b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f25dd61c3ff</guid>
            <dc:creator><![CDATA[David Arias, CFA]]></dc:creator>
            <pubDate>Tue, 30 Sep 2025 15:14:05 GMT</pubDate>
            <atom:updated>2025-09-30T15:14:05.119Z</atom:updated>
            <content:encoded><![CDATA[<h3>Reveillon gift</h3><p>Recently, an article by Bernard Goyder in Bloomberg caught my attention. He pointed out something interesting: investors who had been hedging against a downturn are now more worried about missing the year-end rally, a pretty common phenomenon in stock markets.</p><p>Over the past few months, lots of investors have been protecting their positions with put options, in case of a sell-off. Since many were speculating about a possible bubble, put options ended up with higher implied volatility, which pushed the skew higher. But in the last few days, demand has shifted: fewer are looking for downside protection, while more are chasing out-of-the-money calls.</p><h3>Trying to smile?</h3><p>It might be an interesting metaphor: just as we all try to smile on New Year’s Eve, hoping for new dreams and to reach our goals, markets can also “smile” when optimism takes over.</p><p>The call skew can be measured by taking the implied vol of an OTM call (for example, one with a delta of 0.25) and dividing it by the implied vol of an ATM call (delta 0.5). Since this ratio is less than one, the SPX curve has more of a “smirk” shape — meaning OTM calls are less skewed than ATM options. When the skew of OTM calls or ITM puts increase, it is “smiling”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5VsgGsm4jEYXfbyr.png" /><figcaption>Source: Investopedia</figcaption></figure><p>As shown in the Nomura chart, the IV of OTM calls has been rising since the start of the month. On September 22, the <strong>3-month call skew</strong> hit new highs since January, showing that investors are buying higher-strike calls, betting the index could close the year above 7,000.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wMwYdlHvcDp5EZcagUcIYg.png" /><figcaption>Source: Bloomberg, elaborated by Nomura</figcaption></figure><p>Another point is that the <strong>3-month put skew</strong> (−0.25 delta / −0.5 delta) has slightly decreased, but it remains relatively elevated compared to the beginning of the period. This means that although OTM put options have gotten cheaper in september, they’re still trading at relatively high levels.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EJrrh5bx6PxIAHggf_nc2Q.png" /><figcaption>Source: Bloomberg, elaborated by David Arias, CFA</figcaption></figure><p>In September, the increase in call skew was more significant than the decrease in put skew, which suggests the move was driven more by bullish positioning than by reduced demand for hedges.</p><p>On top of that, ATM implied volatility has been trending lower over the past few months, making options overall cheaper to buy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PZzh0zASUbE1FkuD-ItTjA.png" /><figcaption>Source: Bloomberg, elaborated by David Arias, CFA</figcaption></figure><h3>The risk reversal strategy</h3><p>Investors might try to capitalize on the IV difference between OTM puts and OTM calls by selling an OTM put and buying an OTM call. The lower the delta, the higher the skew effect tends to be.</p><p>A plot was built comparing the IV of a 0.15 delta put with a 0.15 delta call — together with the same strategy with 0.1 delta. As the chart shows, many who tried this strategy since Liberation Day would have been hurt (if only IV is considered). However, those who entered in September could have seen positive returns thanks to the reversal in skewness. The effect becomes even stronger at lower deltas, as the plot highlights.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*STswOAbOWEnW4OEGYKWGbQ.png" /><figcaption>Source: Bloomberg, elaborated by David Arias, CFA</figcaption></figure><h3>Time to hedge?</h3><p>Buying puts over the past few months has eaten into returns, while the opposite has been true for those who sold them, they’ve benefited from the bull market. Still, there are solid arguments for why investors might consider hedging now. Nomura’s McElligott, for example, argues that some should keep hedging due to signs of euphoria. Others point out that hedging is relatively cheap, as implied volatility has declined. Studies also show that in low-IV environments, large daily losses can trigger stronger capital flows into safer assets.</p><p>It might be an interesting time to experiment with low-delta strategies, such as a short risk-reversal (selling a call and buying a put). But with caution : without holding the underlying, investors risk larger losses if the market keeps rallying and euphoria persists.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f25dd61c3ff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Covered Call Strategy with PETR4: Options Trading Approach Using R]]></title>
            <link>https://medium.com/@davidarias2/covered-call-strategy-with-petr4-options-trading-approach-using-r-70c3b5457148?source=rss-b60be0a222b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/70c3b5457148</guid>
            <dc:creator><![CDATA[David Arias, CFA]]></dc:creator>
            <pubDate>Mon, 09 Jun 2025 13:45:52 GMT</pubDate>
            <atom:updated>2025-06-09T13:45:52.743Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>1. Introduction and Payoff</strong></h3><p>Writting a covered call is a widely used options strategy among individual and institutional investors. It involves an investor who already owns a stock selling a call option on that same stock, thus granting another party the right to purchase the shares at a specified strike price.</p><p>I’ve recorded a YouTube video to explain everything in more detail:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FxAnwKTlVm44%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DxAnwKTlVm44&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FxAnwKTlVm44%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f59ae90bfef381ef22df1dff1b78d8e/href">https://medium.com/media/7f59ae90bfef381ef22df1dff1b78d8e/href</a></iframe><p>For example, imagine an investor who bought PETR4 for R$30 and sold a call with an exercise price of R$32 for R$1. The investor still has unlimited losses but gained a premium; however, now he has limited gains (maximum profit = R$3) when the stock rises above R$32.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*e4LaaexdIhJFBY18OwTRsg.png" /></figure><p><strong>2. Motivations to adopt the covered call strategy</strong></p><p>There are some motivations regarding adoption the covered call strategy:</p><blockquote><strong>1. Yield enhancement</strong></blockquote><p>The primary reason investors write covered calls is to generate cash when they expect limited upside potential in the underlying asset. The call writer retains the premium no matter how the market moves. Many covered call writers consider this premium an extra stream of income.</p><blockquote><strong>2. Reducing position</strong></blockquote><p>A portfolio that has become overweighted in a sector can sell calls to reduce Delta. For example, instead of selling 1,000 stocks to reduce a position, it is possible to sell call contracts to reduce exposure. This might limit potential capital gains from instantaneously liquidating the position (but might add due to the premium) and avoid a higher cash drag.</p><blockquote><strong>3. Target pricing</strong></blockquote><p>Considered an hybrid strategy: involves writing calls with an exercise price near the target price for the stock. In this case, the investor is less worried if the option price is exercised, as the strike price is already precified by its fundamentals.</p><h3><strong>3. Delta, Gamma and Theta</strong></h3><p>Delta is a measure of how much an option’s price is expected to change when the underlying stock price changes. Call options have positive delta, varying from 0 to 1. However, since those calls are being sold, the covered call strategy will reduce the portfolio delta. So, since calls are being sold, the underlying will be sold for a lower value in case the option is exercised.</p><p>Covered call strategies can be done with ATM, ITM or OTM calls depending on the objective:</p><p><strong>ITM calls</strong> have a delta higher than 0.5 (strike price lower than the underlying price) and offer the highest premium, but a higher chance of the call being exercised.<br><strong>ATM calls</strong> have a delta close to 0.5, and a considerable chance of being exercised (underlying price close to strike price).<br><strong>OTM calls</strong> have a delta lower than 0.5 (underlying price lower than strike price), offer the lowest premium, but a lower probability of the option being exercised.<br>Thus, there should be a balance of premium and probability of the option being exercised. In this article, OTM calls will be sold, assuming there’s more need to keep the stock for strategic reasons.</p><p>As the underlying price approaches the strike of a short call option, Gamma increases, causing Delta to change more rapidly. If the call becomes ITM, Delta approaches -1, increasing the directional exposure of the short position. So, in case it is not strategic to reduce a position, the call should be bought back when the underlying reaches a near strike price.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*fxvqF1Kgru3nRbBa.png" /></figure><p><strong>Theta</strong> measures how much the extrinsic value of an option decreases as time passes. It is worth noting that it doesn’t follow a linear structure — as it enters the last month before expiration, the time decay is higher.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/0*x7rryUUyD8UvAsXK.gif" /></figure><p>The longer the time to expiration, the higher the premium, as it increases the probability of being exercised. However, it is worth noting that it might be more beneficial to sell a 1-month call, as option prices decay faster. This is important in case it becomes necessary to buy the call back to close the position.</p><h3><strong>4. Implied volatility (IV)</strong></h3><p>The higher the implied volatility, the higher the option price; and since calls are being sold, it is strategic to do covered calls when the market is more volatile.</p><p>However, IV for calls comes from different reasons than IV for puts, especially for OTM options, as volatility in calls may come from speculative spikes, while puts come from demand for hedging. This difference opens the door to other option strategies such as risk reversal.</p><p>The IV can be calculated using the Black-Scholes (BS) model, with the following formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/0*k623khLPJOTiT7M8.jpg" /><figcaption>Source: WallStreetMojo</figcaption></figure><p>The BS model prices the call based on the risk-adjusted probability of it expiring ITM N(d1), and not expiring ITM N(d2), and discounts it to present value.</p><p>The call price (C(S,t)) is the market price; IV is the value of volatility (σ) that makes the Black-Scholes price of the option match the current market price. The mathematical methods to reach the σ value, given the market price, are beyond the scope of this reading.</p><p>Thus, covered call strategies will be more profitable when the IV of calls is higher than average, or when it is expected that future volatility will be lower than what the market is pricing in.</p><h3>5. Covered call implementation — PETR4</h3><p>Based on the conclusions, the trading strategy will be implemented with 0.3 delta calls (OTM), with a one month time horizon (lower theta), when implied volatility is higher than average.</p><p>Petrobras (PETR4) is one of the largest Brazilian public companies, with high options liquidity, lower option spreads, and easier position rolling. It also has a history of high dividends, which offers an extra yield even when the stock goes down or remains stable. Thus, it can be a strategic stock for dividend yield rather than capital appreciation. There is also considerable government influence and exposure to Brazil risk, which increases call premiums due to higher implied volatility (IV).</p><p><strong><em>Note:</em></strong><em> I am not using the ADR of Petrobras; instead, I am using the security from the Brazilian stock exchange, as it is possible to get the option price history from B3 for free and perform the analysis.</em></p><p>As mentioned in the previous article, the Brazilian stock exchange is very outdated, so it does not have an integrated API, and it is difficult to extract the CSV directly from the database. Fortunately, a Brazilian economist named Wilson Freitas developed an R library called <strong>rb3</strong>.</p><p>In this library, Wilson Freitas created a method to dynamically extract the data and calculate the IV of each option based on the Black-Scholes model. Here is the link to his website with the script:</p><p><a href="https://www.wilsonfreitas.net/posts/2022-08-29-dinamica-da-volatilidade-implicita/dinamica-da-volatilidade-implicita">Dinâmica da Volatilidade Implícita</a></p><p>Firstly, install the library “oplib” manually from GitHub:</p><pre>if (!require(devtools)) install.packages(&quot;devtools&quot;)<br>devtools::install_github(&quot;wilsonfreitas/oplib&quot;)</pre><p>Then extract the data:</p><pre># The following script was developed by Wilson Freitas<br><br>library(rb3)<br>library(oplib)<br>library(bizdays)<br>library(tidyverse)<br><br><br><br>refdate &lt;- getdate(&quot;last bizday&quot;, Sys.Date(), &quot;Brazil/B3&quot;)<br><br><br>ch &lt;- cotahist_get(refdate, &quot;yearly&quot;)<br><br><br>yc &lt;- yc_mget(first_date = as.Date(&quot;2025-01-01&quot;), last_date = refdate)<br><br><br>symbol &lt;- &quot;PETR4&quot;<br><br><br>op &lt;- cotahist_options_by_symbol_superset(symbol, ch, yc)<br><br><br>op_vol &lt;- op |&gt;<br>  mutate(<br>    biz_days = bizdays(refdate, following(maturity_date, &quot;Brazil/B3&quot;), &quot;Brazil/B3&quot;),<br>    time_to_maturity = biz_days / 252,<br>    rate = log(1 + r_252),<br>    bsm_impvol = bsmimpvol(<br>      close, type, close.underlying, strike, time_to_maturity, rate, 0<br>    ),<br>    delta = bsmdelta(<br>      type, close.underlying, strike, time_to_maturity, rate, 0, bsm_impvol<br>    )<br>  ) |&gt;<br>  select(<br>    refdate, symbol, volume, maturity_date,<br>    type, close.underlying, strike, time_to_maturity, rate,<br>    biz_days, close, high, low, bsm_impvol, delta<br>  )</pre><p>As a result, all the options with every strike price and time to expiration from 01/01/2025 were extracted. Now we have all the data to analyze its history:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WqcW-Yc94177713kYZxK3w.png" /></figure><p>Note that some deep ITM options came with an empty blank, it might have been a problem with the closing price data from B3, but It does not impact the 0.3 delta or ATM calls.</p><p>The data was filtered to get just 1 month to expiration calls, which are the ones next to 21 “bisdays”(brazilian calendar considers business days):</p><pre>op1 &lt;- op_vol |&gt;<br>  split(op_vol$refdate) |&gt;<br>  map_dfr(function(df) {<br><br>    if (nrow(df) == 0) return(tibble())<br><br>    target &lt;- df$maturity_date[which.min(abs(df$biz_days - 21))]<br><br>    df |&gt; filter(maturity_date == target)<br>  })</pre><p>Brazilian options expires every third monday of the month, so most of them expires at day 21:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/1*1EEfQwg4Vk8Ce5sX1cOkJQ.png" /></figure><p>Lastly, only options with a delta next to 0.3 will be chosen, the next script was elaborated by Wilson Freitas:</p><pre># The following script was developed by Wilson Freitas<br>op1_otm &lt;- split(op1, op1$refdate) |&gt;<br>  map_dfr(function(df) {<br>    df_type &lt;- filter(df, type == &quot;Put&quot;)<br>    df1 &lt;- df_type[which.min(abs(abs(df_type$delta) - 0.3)), ]<br>    <br>    df_type &lt;- filter(df, type == &quot;Call&quot;)<br>    df2 &lt;- df_type[which.min(abs(abs(df_type$delta) - 0.3)), ]<br>    <br>    bind_rows(df1, df2)<br>  })</pre><p>Then, the 2025 implied volatility time series of PETR4 was plotted.</p><pre>op1_otm |&gt;<br>  ggplot(aes(x = refdate, y = bsm_impvol, colour = type)) +<br>  geom_line() +<br>  geom_point() +<br>  labs(<br>    x = &quot;Data&quot;, y = &quot;Implicit volatility&quot;,<br>    title = &quot;2025 Implicit volatility time series (~1 Month) - PETR4&quot;,<br>    subtitle = &quot; ~0.3 Delta options Implicit volatility (OTM)&quot;,<br>    caption = &quot;Developed by David Arias, CFA with data extraction script from Wilson Freitas / Source: B3&quot;,<br>    colour = &quot;Option type&quot;<br>  ) +<br>  theme_minimal()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sJLA_62b6iqSgEvUydSdCQ.png" /></figure><p>It is possible to see that PETR4 calls have been showing higher implied volatility over the last two months compared to January–March, so it might be a reasonable period to sell options. On some days, there is a high disparity between puts and calls IV — these can be opportunities for a risk reversal. Thus, for the day 06–03–2025, covered calls and lower delta risk reversals (selling OTM puts and buying OTM calls) might present attractive premiums.</p><h3>5. Trading implementation</h3><p>In practice, if an investor with a R$200,000 position in PETR4 wants to enter a covered call strategy on 03–06–2025, it would require selling PETRF325W4 contracts:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A-wo6qiRSIwcVD6Uz3CklA.png" /></figure><p><strong>Petr4 closing stock price = 30.18 ; Call premium = 0.34 ; Delta = 0.28</strong>5 ; <strong>strike price = 31.68</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1021/1*bamOc_y3kdVoO-sZjWZmTA.png" /></figure><p>The investor has approximately 6600 PETR4 stocks (200000/30.18).</p><p>The investor will sell 6600 PETR4 calls (66 contracts), getting a premium of <strong>2244 </strong>(6600* 0.34). Yield enhancement of <strong>1.12% (2244/200000)</strong>.</p><p><strong>Delta before the strategy = 6600</strong> (each stock sums 1 delta)</p><p>Each call sold counts as a negative 0.285 delta, thus the delta of written calls will be <strong>-1881</strong>(0.285*6600)</p><p><strong>Delta after the strategy = 4719</strong> = 6600 – 1881</p><p>Thus, for each R$1 the stock price moves up, the portfolio will move up by R$4719 instead of R$6600, as the position in PETR4 was reduced.</p><p>There are American and European options for PETR4, but in this example, PETRF325W4 is an American option. Thus, in case the stock price goes higher than 31.68 during the one-month time period, the option might be exercised. It might not be a problem for an investor to sell it if the price is speculated to be the target.</p><p>However, it can be a problem for investors who still want to hold the stock for strategic reasons, such as portfolio optimization or dividend income. Moreover, investors who bought PETR4 at a low price (e.g., R$25) might face high capital gains in case the call is exercised — the investor would be taxed on R$6.68 per share (31.68–25), plus the premium of 0.34 per share.</p><p>The solution would be to buy back the call when the underlying price reaches a certain threshold, and the large Theta decay is very beneficial on these occasions, especially if the IV on that day is lower. The investor would benefit from the time decay of one-month options if close to expiration.</p><p>However, it would require a certain level of active management to monitor the stock price. For that, trading software might be necessary to automate the process. Another solution would be to adjust the delta (from 0.15 to 0.25) to reduce the probability of exercise.</p><h3>6. Limitations and conclusion</h3><p>There are limitations regarding modeling the option strategy:</p><p><strong>Volatility model:</strong> Black-Scholes is considered one of the most well-known models to calculate IV; however, it is used to price European options, such as SPY. Since some of PETR4’s calls are American options, it might not be the most appropriate model compared to the binomial method.</p><p><strong>Theta:</strong> Even though it was considered during the analysis using one-month options, the Theta time decay is lower for OTM options, as the extrinsic value is lower compared to ATM options.</p><p><strong>Suitability:</strong> The strategy might not be appropriate for investors who don’t have a clear understanding of the payoff structure of a covered call, and it may require more active management if the investor intends to avoid selling the stock prematurely.</p><p><strong>In summary,</strong> covered calls might be seen as simpler strategies that include the underlying asset for protection and do not carry the risk of margin calls. Since the investor is selling an OTM call, there is no loss if the call is exercised — unlike other strategies that involve selling options without holding the underlying asset. The only potential losses would occur if the investor sells the stock for less than the purchase price, which can result in capital losses. Covered calls can be an effective way to generate extra yield when the investor is not concerned about the stock being called away early.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70c3b5457148" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Visualizando a Curva de Juros Brasileira: Análise Temporal com Python e R]]></title>
            <link>https://medium.com/@davidarias2/visualizando-a-curva-de-juros-brasileira-an%C3%A1lise-temporal-com-python-e-r-6ad64e3eee3e?source=rss-b60be0a222b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ad64e3eee3e</guid>
            <dc:creator><![CDATA[David Arias, CFA]]></dc:creator>
            <pubDate>Sun, 25 May 2025 02:34:19 GMT</pubDate>
            <atom:updated>2025-05-25T02:34:19.772Z</atom:updated>
            <content:encoded><![CDATA[<p>A <strong>curva de juros</strong> representa o comportamento esperado das taxas de juros no tempo. No Brasil, ela é construída com base nas taxas de juros negociadas em diferentes prazos.</p><p>Neste artigo, será analisada a <strong>curva de juros DI brasileira</strong> e seu comportamento entre <strong>maio de 2024 e maio de 2025</strong>, com base em dados públicos da B3 e modelagem realizada nas linguagens <strong>Python</strong> e <strong>R</strong>.</p><p>Também fiz um vídeo explicando a lógica da curva de juros:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F3Jdek7MI-ms%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D3Jdek7MI-ms&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F3Jdek7MI-ms%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/c54c8c26f722d64dc5e3ac41217e4dd4/href">https://medium.com/media/c54c8c26f722d64dc5e3ac41217e4dd4/href</a></iframe><h3>1. Estrutura da curva</h3><p>A curva de juros é um dos principais instrumentos para entender as expectativas do mercado em relação à <strong>inflação</strong>, <strong>crescimento econômico</strong> e <strong>política monetária</strong>. A curva pode ser estruturada a partir de três dimensões: <strong>nível</strong>, <strong>inclinação</strong> e <strong>curvatura</strong>.</p><p><strong>Nível</strong>: Refere-se à <strong>altura média da curva</strong>. Quando as taxas de juros em todos os prazos sobem, temos um movimento de <strong>“bear”</strong> (alta das taxas). Quando caem, falamos em <strong>“bull”</strong> (queda das taxas). O nível é fortemente influenciado pelas expectativas em relação à taxa Selic.</p><p><strong>Inclinação:</strong> Diferença entre <strong>juros de longo prazo e curto prazo</strong>. Podem seguir as seguintes formas:</p><ul><li><strong>Inclinada (steep):</strong> juros de longo prazo são maiores que os de curto prazo, isso indica um potencial crescimento econômico esperado com inflação sob controle.</li><li><strong>Invertida:</strong> juros de curto prazo são maiores que os de longo prazo. Isso pode sinalizar preocupação com recessão ou cortes futuros na Selic.</li><li><strong>Achatada (flat):</strong> juros curtos e longos estão próximos.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TmaH-tB7tLKfXGgj.png" /></figure><p>Como por exemplo, a curva de juros no dia 16 de maio se encontrava invertida:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1015/1*NtVxJGmwJEYkySisq0C8wg.png" /></figure><h3>2. Obtenção dos dados no R</h3><p>Uma das maiores dificuldades ao construir a curva de juros para um período extenso está na <strong>obtenção estruturada dos dados</strong>. A B3, principal fonte oficial para a curva DI, <strong>não oferece uma API pública integrada</strong> que permita o acesso automatizado aos dados históricos da curva. Pelo site da B3, é possível apenas <strong>baixar arquivos CSV individualmente por data</strong>, o que torna o processo extremamente trabalhoso para quem deseja analisar centenas de dias consecutivos.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W2TEgaexlmsVB_j_QQyCQg.png" /></figure><p>Para contornar essa limitação de acesso aos dados, o economista <strong>Wilson Freitas</strong> desenvolveu a biblioteca <strong>rb3</strong>, um pacote para a linguagem <strong>R</strong> voltado especificamente à extração e manipulação de dados do mercado financeiro brasileiro. O próprio autor critica a estrutura atual dos dados no Brasil, afirmando que <em>“os arquivos disponibilizados no mercado financeiro brasileiro são da idade da pedra”</em>.</p><p>A biblioteca rb3 permite acesso automatizado a diversas séries financeiras públicas, incluindo a <strong>curva de juros da B3</strong>, viabilizando análises históricas mais completas e eficientes. Para este estudo, será utilizado o comando yc_get(), que retorna a <strong>curva de juros prefixada interpolada</strong> para uma determinada data — uma estrutura que já considera os contratos futuros de DI1 e aplica os métodos de interpolação utilizados pela própria B3.</p><p>Para mais informações sobre a metodologia utilizada, segue o website do Wilson Freitas:</p><p><a href="https://www.wilsonfreitas.net/">https://www.wilsonfreitas.net/</a></p><pre>library(rb3)<br>library(dplyr)<br>library(purrr)<br>library(readr)<br><br><br>datas &lt;- seq.Date(from = as.Date(&quot;2024-05-19&quot;), to = as.Date(&quot;2025-05-19&quot;), by = &quot;day&quot;)<br><br># Função segura -&gt; pois se alguma chamada falhar, não interromer.<br>safe_yc_get &lt;- safely(yc_get)<br><br># 1 curva por dia<br>curvas_seguras &lt;- map(datas, safe_yc_get)<br><br># Filtrar apenas as curvas que funcionaram, removendo nulls, caso haja erro <br>curvas_sucesso &lt;- map(curvas_seguras, &quot;result&quot;) %&gt;% <br>  compact() %&gt;% <br>  bind_rows()<br><br><br>write.csv(curvas_sucesso, &quot;curva_DI_B3_2024_2025.csv&quot;, row.names = FALSE)</pre><p>Como a extração envolve um grande número de datas, qualquer falha pontual — como ausência de dados ou erro de conexão — poderia interromper toda a execução. Para contornar esse problema, foi utilizada a função safely()</p><p>Com isso, já é possível começar a análise da curva, pois já temos os dados com as seguintes colunas:</p><p>refdate<strong>Data de referência</strong> da curva.</p><p>cur_daysNúmero de <strong>dias corridos</strong> entre a refdate e a forward_date.</p><p>biz_daysNúmero de <strong>dias úteis</strong> entre a refdate e a forward_date.</p><p>forward_dateData de vencimento futura para a qual a taxa é calculada.</p><p>r_252<strong>Taxa de juros anualizada</strong> com base em 252 dias úteis (padrão Brasil).</p><p>r_360<strong>Taxa de juros anualizada</strong> com base em 360 dias corridos (padrão internacional).</p><h3>3. Dataframe no python</h3><p>Após a extração dos dados em formato CSV, a análise segue em <strong>Python</strong>, onde os dados são organizados em um <strong>DataFrame</strong>. A primeira etapa consiste em <strong>converter a coluna </strong><strong>biz_days em categorias de maturidade</strong>, o que facilita a visualização e interpretação da curva. Por exemplo, valores como 20 ou 21 dias úteis são agrupados sob a categoria <strong>&quot;1M&quot;</strong> (um mês).</p><pre>import pandas as pd<br>import matplotlib.pyplot as plt<br>import openpyxl<br>import os<br>import matplotlib.animation as animation<br><br>os.chdir(&quot;C:/Users/david/Documents&quot;)<br><br>df = pd.read_csv(&quot;curva_DI_B3_2024_2025.csv&quot;)<br>df[&#39;refdate&#39;] = pd.to_datetime(df[&#39;refdate&#39;])<br><br>maturity_ranges = {<br>    &#39;1M&#39;: (18, 24),<br>    &#39;3M&#39;: (58, 64),<br>    &#39;6M&#39;: (120,135),<br>    &#39;1Y&#39;: (252, 271),<br>    &#39;2Y&#39;: (494,520),<br>    &#39;3Y&#39;: (756, 770),<br>    &#39;5Y&#39;: (1230, 1282),<br>    &#39;10Y&#39;: (2475, 2555),<br>    &#39;20Y&#39;: (4095, 5090)<br>}<br><br>def map_maturity(biz_day):<br>    for label, (min_d, max_d) in maturity_ranges.items():<br>        if min_d &lt;= biz_day &lt;= max_d:<br>            return label<br>    return None</pre><p>Como a coluna biz_days representa o número de dias úteis entre a data de referência e o vencimento, seu valor exato <strong>varia ligeiramente de um dia para outro</strong>. Por exemplo, no dia 5 de maio um vencimento de três meses pode corresponder a 63 dias úteis, enquanto no dia 6 de maio pode corresponder a 62. Se a categorização for feita com base em um valor fixo, como 63 para &quot;3M&quot;, essas pequenas variações resultarão em <strong>colunas vazias</strong> no DataFrame quando a equivalência exata não for encontrada. Por isso, é importante definir <strong>intervalos apropriados para cada faixa de vencimento,</strong></p><pre><br>df[&#39;maturity&#39;] = df[&#39;biz_days&#39;].apply(map_maturity)<br><br>maturity_order = [&#39;1M&#39;, &#39;3M&#39;, &#39;6M&#39;, &#39;1Y&#39;, &#39;2Y&#39;, &#39;3Y&#39;, &#39;5Y&#39;, &#39;10Y&#39;, &#39;20Y&#39;]<br>curve_df = curve_df[[col for col in maturity_order if col in curve_df.columns]]<br><br>curve_df.to_excel(&quot;curva_DI_binned_cleantable.xlsx&quot;, sheet_name=&quot;DI_Curve&quot;)<br><br>curve_df</pre><p>Após ordernar as colunas , foram construídos o dataframe e a planilha do excel</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*QygnHe6d3c4jUpKoR8GPCQ.png" /></figure><h3><strong>4. Plot dinâmico</strong></h3><p>Após a análise dos dados, foi possível observar que a curva de juros passou por <strong>diversas dinâmicas ao longo do período de um ano</strong>. Para organizar e interpretar melhor esses movimentos, foram definidas algumas <strong>“timestamps” </strong>representando diferentes fases da curva de juros,</p><p><strong>Entre junho e Dezembro de 2024:</strong> “Slight steepening to bear flattener” — refletinado as expectativas do mercado de uma <strong>política monetária mais restritiva no curto prazo</strong>, diante de pressões inflacionárias e incertezas fiscais.</p><p><strong>Entre dezembro e a segunda semana de janeiro:</strong> “Bear steepener and high increase in yields”. Nesse período, o Comitê de Política Monetária (Copom) do Banco Central <strong>elevou a taxa Selic em 1 ponto percentual,</strong> além do real sofrer uma desvalorização significativa, ultrapassando R$ 6,20 por dólar; além de problemas fiscais, depois anúncio de medidas fiscais consideradas insuficientes para conter o crescimento da dívida pública. Com isso, as expectativas de inflação e aumento de juros no longo prazo aumentaram.<br><br><strong>Entre Janeiro e Maio de 2025: </strong>“Bear flattener to curve inversion” -Em março de 2025, o Copom elevou a taxa Selic para 14,25% ao ano. Depois, houve um aumento na demanda de títulos de médio e longo prazo, diminuindo suas yields, devido à especulação da queda de juros nos próximos anos.</p><pre>curve_df_pct = curve_df.copy() * 100<br><br>december_start = pd.Timestamp(&quot;2024-12-01&quot;)<br>january_second_week = pd.Timestamp(&quot;2025-01-08&quot;)<br><br>before_dec = curve_df_pct[curve_df_pct.index &lt; december_start].resample(&quot;7D&quot;).first()<br>during_dec = curve_df_pct[(curve_df_pct.index &gt;= december_start) &amp; (curve_df_pct.index &lt; january_second_week)]<br>after_jan = curve_df_pct[curve_df_pct.index &gt;= january_second_week].resample(&quot;7D&quot;).first()<br><br>combined = pd.concat([before_dec, during_dec, after_jan]).dropna(how=&#39;all&#39;)</pre><p>Após isso, o formato do gráfico foi moldado:</p><pre>x_labels = list(combined.columns)<br>x_pos = range(len(x_labels))<br><br>fig, ax = plt.subplots(figsize=(10, 6))<br>line, = ax.plot([], [], marker=&#39;o&#39;, linewidth=2)<br><br>subtitle = ax.set_title(&quot;&quot;, fontsize=17, pad=10, color=&#39;red&#39;)<br><br>fig.suptitle(&quot;Brazil DI Yield Curve (2024-05-19 to 2025-05-16)&quot;, fontsize=18, weight=&#39;bold&#39;, y=0.98)<br><br>ax.set_xlim(-0.5, len(x_labels) - 0.5)<br>ax.set_ylim(combined.min().min() * 0.95, combined.max().max() * 1.05)<br>ax.set_xticks(x_pos)<br>ax.set_xticklabels(x_labels, fontsize=12)<br>ax.set_xlabel(&quot;Maturity&quot;, fontsize=16, labelpad=3)<br>ax.set_ylabel(&quot;Annualized Rate (%)&quot;, fontsize=13)<br>ax.tick_params(axis=&#39;y&#39;, labelsize=11)<br>ax.grid(True, linestyle=&#39;--&#39;, alpha=0.5)<br><br>fig.text(0.5, 0.01, &quot;Source: B3, elaborated by David Arias, CFA&quot;, ha=&#39;center&#39;, fontsize=9, style=&#39;italic&#39;)<br><br><br>slope_text = fig.text(0.85, 0.8, &quot;&quot;, fontsize=16, ha=&#39;right&#39;, color=&#39;black&#39;)<br>prev_slope = 0</pre><p>Em seguida, foi construída uma <strong>visualização dinâmica</strong> da evolução da curva ao longo do tempo. Além disso, foi adicionada uma a variável <strong>“slope”</strong>, que seria a diferença das yields de 10 anos e 1 mês.</p><pre>def get_phase_title(current_date):<br>    if current_date &lt; december_start:<br>        return &quot;Slight steepening to bear flattener&quot;<br>    elif december_start &lt;= current_date &lt; january_second_week:<br>        return &quot;Bear steepener and high increase in yields&quot;<br>    else:<br>        return &quot;Bear flattener and curve inversion&quot;<br><br><br>def init():<br>    line.set_data([], [])<br>    slope_text.set_text(&quot;&quot;)<br>    return line, subtitle, slope_text<br><br>def update(frame):<br>    global prev_slope<br>    current_date = combined.index[frame]<br>    y = combined.iloc[frame].values<br>    line.set_data(x_pos, y)<br><br>    slope = y[x_labels.index(&quot;10Y&quot;)] - y[x_labels.index(&quot;1M&quot;)]<br><br>    if slope &gt; prev_slope:<br>        slope_color = &quot;blue&quot;<br>    elif slope &lt; prev_slope:<br>        slope_color = &quot;red&quot;<br>    else:<br>        slope_color = &quot;black&quot;<br><br><br>    prev_slope = slope<br>    slope_text.set_text(f&quot;Slope(10Y-1M) = {slope:.2f}&quot; )<br>    slope_text.set_color(slope_color)<br>    current_date = combined.index[frame]<br>    y = combined.iloc[frame].values<br>    line.set_data(x_pos, y)<br>    subtitle.set_text(f&quot;{get_phase_title(current_date)} – {current_date.strftime(&#39;%Y-%m-%d&#39;)}&quot;)<br>    return line, subtitle, slope_text<br><br>ani = animation.FuncAnimation(<br>    fig, update, frames=len(combined), init_func=init,<br>    interval=400, blit=False<br>)<br><br>ani.save(&quot;di_curve_dynamic_phases_with_slope.gif&quot;, writer=&quot;pillow&quot;, fps=2)<br>plt.close()</pre><p>Como resultado, temos a seguinte curva:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*vO3Vlvx4sdMT1ZLtNwCxMg.gif" /></figure><h3>5. Conclusão</h3><p>Moldar e interpretar a curva de juros no Brasil é uma tarefa desafiadora, tanto para formuladores de política quanto para analistas e investidores. A dinâmica da curva é constantemente afetada por uma combinação de <strong>variáveis fiscais, monetárias e políticas</strong>, muitas vezes imprevisíveis e, em diversos momentos, contraditórias.</p><p>O componente fiscal exerce enorme influência sobre os juros de longo prazo. Qualquer ruído sobre a sustentabilidade da dívida pública, mudanças no arcabouço fiscal ou dúvidas sobre o compromisso com metas fiscais rapidamente se traduzem em <strong>pressão na ponta longa da curva</strong>, elevando os prêmios de risco exigidos. Por outro lado, a política monetária conduzida pelo Banco Central — em resposta à inflação , impacta diretamente a <strong>parte curta da curva</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ad64e3eee3e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Portfolio Optimization in Python: Historical vs. Forward-Looking Mean-Variance Models]]></title>
            <link>https://medium.com/@davidarias2/portfolio-optimization-in-python-historical-vs-forward-looking-mean-variance-models-0b10665ddd08?source=rss-b60be0a222b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/0b10665ddd08</guid>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[cfa]]></category>
            <category><![CDATA[portfolio-management]]></category>
            <category><![CDATA[investment]]></category>
            <dc:creator><![CDATA[David Arias, CFA]]></dc:creator>
            <pubDate>Tue, 13 May 2025 00:59:19 GMT</pubDate>
            <atom:updated>2025-05-14T12:14:15.571Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. MVO model</h3><p><strong>Mean–Variance Optimization (MVO)</strong>, introduced by <strong>Harry Markowitz (1952, 1959)</strong>, remains one of the most widely used methods for setting asset allocation policy. The model relies on three key inputs: <strong>expected returns</strong>, <strong>risks (standard deviations)</strong>, and <strong>correlations between assets</strong>. Based on these inputs, MVO identifies <strong>efficient portfolios</strong> — combinations of assets that <strong>maximize expected return for a given level of risk</strong>, or equivalently, <strong>minimize risk for a given expected return.</strong> It can also be used<strong> to find the </strong>best risk-adjusted return, by <strong>maximizing the sharpe ratio, </strong>as a way to give to maximise utility given by the function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/210/1*cCvywyvCzzJ__M1IBdga5A.png" /></figure><p>In summary, the optimizer identifies all efficient portfolios that together form the efficient frontier. Conceptually, it does this by iterating through all possible values of the <strong>risk aversion coefficient (λ)</strong>, and for each value, it determines the asset combination that maximizes expected utility.</p><p>The full set of these optimal portfolios forms what is known as the <strong>efficient frontier</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/434/0*S6dTAzdfWBMNEgaW.jpg" /></figure><p>Assuming we are working in a “strategic” setting, we will use annual capital market assumptions, getting data over a 10-year horizon, and our <strong>objective function will be to maximize sharpe ratio</strong>. We will firstly start with the most traditional MVO application, using the average past log returns as the expected return.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*UZVGTm2bqN4eyDxAI8dEbw.png" /></figure><p>The focus of this article is on the s<strong>tructure and logic of Mean-Variance</strong> Optimization (MVO), with a practical application using Python. It aims to explain the model’s key inputs, mechanics, strengths, and limitations, <strong>rather than to forecast precise return or volatility assumptions</strong>. While forward-looking inputs are incorporated, they are included primarily for illustrative purposes.</p><p>I’ve recorded a YouTube video to explain everything in more detail:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F6j6k_iv6hY0%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D6j6k_iv6hY0&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F6j6k_iv6hY0%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/92e43b05de6a54d3bfde54d354a8ebb1/href">https://medium.com/media/92e43b05de6a54d3bfde54d354a8ebb1/href</a></iframe><h3>2. Investment Universe</h3><p>The first step is selecting<strong> asset classes</strong>, which can be one of the most challenging aspects of portfolio construction, as it depends on specific investment <strong>objectives, constraints, and goals</strong>. Multiple ETFs often represent the same asset class, making the choice highly subjective and requiring careful attention to their <strong>composition and methodology; </strong>Moreover<strong>, </strong>securities <strong>cannot overlap in different asset classes</strong>. The selection in this case was guided by alignment with the asset classes outlined in CFA Institute materials. The final selection includes the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*zRvHOzRsrsvMwgnZKAOIlg.png" /></figure><p>The investment universe is global, with different asset classes and geographies, which will be more effective to get a better allocation.</p><h3>3. Data Collection</h3><p>The following libraries will be used:</p><pre>import yfinance as yf<br>import numpy as np<br>import pandas as pd<br>import matplotlib.pyplot as plt<br>import plotly.express as px<br>import plotly.graph_objects as go<br>from fredapi import Fred<br>from datetime import datetime, timedelta<br>from pypfopt import expected_returns, risk_models<br>from pypfopt.efficient_frontier import EfficientFrontier</pre><p>The next step involves collecting 10 years of historical data for the selected ETFs, retrieved directly using the yfinance API</p><pre># Through yfinance, we get the asset class tickers and labels<br>tickers = [&#39;VTI&#39;, &#39;GOVT&#39;, &#39;LQD&#39;, &#39;VEA&#39;, &#39;PICB&#39;, &#39;VWO&#39;, &#39;EMB&#39;, &#39;CEMB&#39;,&#39;GLD&#39;]<br>asset_class_labels = {<br>    &#39;VTI&#39;: &#39;US Equities&#39;,<br>    &#39;GOVT&#39;: &#39;US Treasuries&#39;,<br>    &#39;LQD&#39;: &#39;US Corporate Bonds&#39;,<br>    &#39;VEA&#39;: &#39;Non-US Developed Equities&#39;,<br>    &#39;PICB&#39;: &#39;Non-US Corporate Bonds&#39;,<br>    &#39;VWO&#39;: &#39;EM Equities&#39;,<br>    &#39;EMB&#39;: &#39;EM Gov. Bonds&#39;,<br>    &#39;CEMB&#39;: &#39;EM Corporate Bonds&#39;,<br>    &#39;GLD&#39;: &#39;GOLD&#39;<br>}<br><br># Here we select our time horizon (10 years)<br>end_date = datetime.today()<br>start_date = end_date - timedelta(days=10*365)<br>print(start_date)<br><br>#Then we create our data frame - Note that I selected auto_adjust=True, thus prices will be adjusted<br>adj_close_df = pd.DataFrame()<br>for ticker in tickers:<br>    data = yf.download(ticker, start=start_date, end=end_date,auto_adjust=True)<br>    adj_close_df[ticker] = data[&#39;Close&#39;]<br><br></pre><h3>4. Calculations using historical returns</h3><p>After retrieving the data, the next steps are to calculate log returns, covariance, and volatility, followed by plotting the <strong>accumulated log returns</strong> over the past 10 years:</p><pre># log returns for expected return estimation, and also drop possible nan<br>log_returns = np.log(adj_close_df / adj_close_df.shift(1)).dropna()<br>mu = log_returns.mean() * 252<br>S = log_returns.cov() * 252<br>vols = log_returns.std() * np.sqrt(252)<br><br># expected log returns and volatilities per asset class<br>print(&quot;\nExpected Annualized Log Returns and Volatility by Asset Class:&quot;)<br>for ticker in tickers:<br>    print(f&quot;{asset_class_labels[ticker]} ({ticker}): Return = {mu[ticker]:.2%}, Volatility = {vols[ticker]:.2%}&quot;)</pre><pre># Building the returns plot <br>cumulative_returns = (1 + log_returns).cumprod()<br><br># Need to normalize to 1.0 at starting point<br>cumulative_returns = cumulative_returns / cumulative_returns.iloc[0]<br><br># Cumulative returns to build the plot<br>plt.figure(figsize=(12, 7))<br>for ticker in cumulative_returns.columns:<br>    plt.plot(cumulative_returns.index, cumulative_returns[ticker], label=asset_class_labels[ticker])<br>plt.title(&quot;Cumulative Returns by Asset Class (Last 10 Years)&quot;)<br>plt.xlabel(&quot;Date&quot;)<br>plt.ylabel(&quot;Cumulative Return&quot;)<br>plt.legend(loc=&quot;upper left&quot;)<br>plt.grid(True)<br>plt.tight_layout()<br>plt.show()</pre><p>The resulting returns and volatilities reveal limitations of using expected returns based on historical trends: the past decade was characterized by exceptionally <strong>strong performance from U.S. equities </strong>— particularly large-cap stocks — while bonds and emerging market equities underperformed and exhibited high volatility. Even before running the optimization, it is evident that the allocation is likely to be heavily weighted toward U.S. stocks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*tEbHHh_aqdwN5lXSxGlFpQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NJXk4hXSlVTMDgHlcaeglw.png" /></figure><p>A correlation matrix was plotted to see the diversification benefits between asset classes; it is possible to conclude that <strong>government bonds and gold have the lowest to negative correlation</strong> with other asset classes, which is an important factor in asset allocation.</p><p>The optimization was then performed using the PyPortfolioOpt library, which offers a simple and intuitive implementation of the mean-variance framework. Although there are other options for building customized optimization models, this approach <strong>provides a simple and effective starting point.</strong> The optimization process requires return and covariance estimates as inputs.</p><pre># Plot correlation matrix<br>correlation_matrix = log_returns.corr()<br>correlation_heatmap = px.imshow(<br>    correlation_matrix,<br>    text_auto=True,<br>    color_continuous_scale=&#39;RdBu_r&#39;,<br>    labels=dict(x=&quot;Assets&quot;, y=&quot;Assets&quot;, color=&quot;Correlation&quot;),<br>    x=correlation_matrix.columns,<br>    y=correlation_matrix.columns,<br>    title=&quot;Correlation Matrix of Log Returns&quot;,<br>    width=1000,<br>    height=800<br>)<br>correlation_heatmap.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*ybDVIUTnK1jmxd9dV6ZujQ.png" /></figure><pre>ef = EfficientFrontier(mu, S)<br>weights = ef.max_sharpe(risk_free_rate=risk_free_rate)<br>clean_weights = ef.clean_weights()<br>ret, vol, sharpe = ef.portfolio_performance(risk_free_rate=risk_free_rate)<br>risk_premium = ret - risk_free_rate<br>print(&quot;\nClean Weights:&quot;)<br>for ticker, weight in clean_weights.items():<br>    print(f&quot;{ticker}: {weight:.4f}&quot;)<br><br>print(f&quot;\nExpected Portfolio Return: {ret:.2%}&quot;)<br>print(f&quot;Portfolio Risk Premium: {risk_premium:.2%}&quot;)<br>print(f&quot;Portfolio Volatility: {vol:.2%}&quot;)<br>print(f&quot;Portfolio Sharpe Ratio: {sharpe:.2f}&quot;)<br><br><br>#weights come as a dictionary, so to plot it, we have to convert it into a list<br><br>weights_list = [clean_weights[ticker] for ticker in tickers]<br><br>plt.figure(figsize=(10, 6))<br>plt.bar(tickers, weights_list)<br><br>plt.xlabel(&#39;Asset class&#39;)<br>plt.ylabel(&#39;Optimal Weights&#39;)<br>plt.title(&#39;Optimal Portfolio Weights&#39;)<br><br>plt.show()<br></pre><p>As I am basing into the CFA material model, The risk-free rate is assumed to be 2.5%.</p><pre>risk_free_rate = 0.025</pre><p><em>It is also reasonable to consider the 10-year government bond yield as the risk-free rate. However, doing so would significantly reduce the Sharpe ratio, given the elevated 10-year yield levels. For those interested in incorporating this into the model, the following code can be used:</em></p><pre>fred = Fred(api_key=&#39;YOUR API&#39;)<br>risk_free_rate_2 = fred.get_series_latest_release(&quot;GS10&quot;).iloc[-1] / 100<br>print(f&quot;Risk-Free Rate (10Y Treasury): {risk_free_rate_2:.4%}&quot;)</pre><p>As a result, the asset allocation is heavily concentrated in U.S. stocks and gold. Over the past decade, <strong>gold delivered strong returns </strong>— particularly during the pandemic, in 2024, and amid the recent bear market triggered by tariff policies — <strong>while maintaining low correlation with other assets</strong>. In contrast, e<strong>merging market securities underperformed</strong>, impacted by several factors including slow growth and challenges in China. These observations highlight a key limitation of basing expected returns solely on historical performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/258/1*3ECGHUG6AZ3EW1wx63vtLg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*RPCuTuVhBSmXF5NFppLBgg.png" /></figure><h3>5. Calculations based on Capital market expectations</h3><p><strong>Forward-looking returns offer a more effective foundation for optimal portfolio allocation.</strong> While historical returns can serve as one parameter for these projections, they also help identify the key variables influencing market behavior.</p><p>Since the focus of this article is on applying MVO in asset allocation, CME(capital market expectations) for each asset class will not be defined. Instead, r<strong>eturn and standard deviation estimates will be derived from multiple external sources.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*JzoXqnTFfBDIhWPsfzzEYw.png" /><figcaption>¹Data was found only for EM bonds, without separating into corporate and sovereign, so I an adjustment was made based on historical returns to differenciate it (historically, EM corporate bonds presented higher return and lower volatility). ² Not so many reports on gold prediction, so It was based more on historical estimates, and that it is currentlty overpriced. * Some of the estimates was not based on the same ETFs, the data was cured from simillar ones.</figcaption></figure><p>Returns and volatility estimates differ significantly between historical and forward-looking approaches<strong>. In this case, return and volatility are treated as output variables</strong>.</p><p>Although some analysts prefer to construct a forward-looking correlation matrix, it is assumed here that correlations between asset classes remain relatively stable, allowing the use of the same 10-year historical correlation matrix</p><pre># It is needed to import the returns and volatilites as pd.series to run optimization<br>mu_forward = pd.Series({<br>    &#39;VTI&#39;: 0.06,   &#39;GOVT&#39;: 0.046,  &#39;LQD&#39;: 0.055,   &#39;VEA&#39;: 0.066,   &#39;PICB&#39;: 0.028,   &#39;VWO&#39;: 0.075,    &#39;EMB&#39;: 0.050,   &#39;CEMB&#39;: 0.055,  &#39;GLD&#39;: 0.050    <br>})<br>vol_forward_series = pd.Series({<br>    &#39;VTI&#39;: 0.162,   &#39;GOVT&#39;: 0.131,  &#39;LQD&#39;: 0.112,   &#39;VEA&#39;: 0.148,   &#39;PICB&#39;: 0.052,  &#39;VWO&#39;: 0.25,   &#39;EMB&#39;: 0.110,   &#39;CEMB&#39;: 0.105,  &#39;GLD&#39;: 0.150    <br>})</pre><p>To obtain the new covariance matrix, the historical correlation matrix is multiplied by the forward-looking volatilities, as indicated by the following formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/283/1*S0zkBbtvPO16fswm6WtZDA.png" /></figure><pre># We have the correlation matrix, but not the covariance for this data, so we firstly we need to create the shape of the covariance matrix<br>outer_vols = np.outer(vol_forward_series, vol_forward_series)<br># Then we multiply the values to get the covariance matrix<br>S_forward = correlation_matrix.values * outer_vols<br># Convert it into a data frame to run optimization<br>S_forward = pd.DataFrame(S_forward, index=correlation_matrix.index, columns=correlation_matrix.columns)</pre><pre>ef_forward = EfficientFrontier(mu_forward, S_forward)<br>weights_forward = ef_forward.max_sharpe(risk_free_rate=risk_free_rate)<br>clean_weights_forward = ef_forward.clean_weights()<br>ret_forward, vol_forward, sharpe_forward = ef_forward.portfolio_performance(risk_free_rate=risk_free_rate)<br>risk_premium_forward = ret_forward - risk_free_rate<br><br>print(&quot;\nClean Weights (Forward-Looking):&quot;)<br>for ticker, weight in clean_weights_forward.items():<br>    print(f&quot;{ticker}: {weight:.4f}&quot;)<br><br>print(f&quot;\nExpected Portfolio Return: {ret_forward:.2%}&quot;)<br>print(f&quot;Portfolio Risk Premium: {risk_premium_forward:.2%}&quot;)<br>print(f&quot;Portfolio Volatility: {vol_forward:.2%}&quot;)<br>print(f&quot;Portfolio Sharpe Ratio: {sharpe_forward:.2f}&quot;)</pre><p>At this stage, the allocation became more diversified. Analysts are forecasting lower volatility for emerging market (EM) assets, partly due to several factors: <strong>EM economies are expected to grow at a solid pace</strong>, according to an AllianzGI report; many countries offer high-yield bonds; and EM assets provide diversification benefits due to low correlation with other asset classes and exposure to different economic cycles.</p><p>Additionally, <strong>most analysts do not expect U.S. equities to replicate the high returns seen over the past decade</strong>. Some even hold a bearish outlook, citing recent events that may limit U.S. growth potential. Across four different analyst scenarios, the model allocated 0% to U.S. equities, reflecting a consensus view that developed markets outside the U.S. may offer better return prospects. While many portfolios still maintain a significant U.S. equity allocation, <strong>valuation concerns and perceived undervaluation in regions such as Europe have shifted preferences in future-oriented strategies.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3di7rF3WeZbf2F0DhNOI8w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/262/1*LPs4fqoTB8Afkq5zLETMRQ.png" /></figure><h3>6. Considerations</h3><p>This is not a final allocation, but rather a demonstration of how the MVO model functions. Several assumptions must be addressed before considering portfolio rebalancing or implementation.</p><ol><li>Although the model results in a high allocation to bonds, this outcome could shift significantly when tax considerations are in. Interest income is typically taxed at higher rates than dividends or capital gains, making such an allocation less suitable for taxable investors. I<strong>n such cases, the model would likely shift more heavily toward equities</strong>.</li><li>A portion of the portfolio should ideally be allocated to alternative assets such as private equity, hedge funds, real estate, and infrastructure. However, t<strong>hese asset classes require distinct modeling approaches and often involve unsmoothed return data</strong>.</li><li>No constraints were applied during the asset class selection process, which is not entirely realistic. For example, home bias often influences portfolio construction, <strong>and in many cases, emerging market securities may be excluded altogether</strong>. This would result in a markedly different allocation.</li><li>Several asset classes were missing, which possible contributed to have a less optimal allocation.</li></ol><h3>7. MVO limitations</h3><p>MVO can be a practical and efficient method for achieving diversification and return objectives. However, the model has several limitations that must be considered:</p><ol><li><strong>Asset allocations are highly sensitive to small changes in the inputs</strong>. For example: if the expected return and volatility of EM bonds change, the entire allocation would be different.</li><li><strong>The asset allocations tend to be highly concentrated into specific asset classes</strong>, although a minimal threshold would solve the problem, it wouldn’t achieve the optimal sharpe ratio.</li><li><strong>Many investors and analysts are concerned about more than the mean and variance of returns</strong>, and the model simulated didn’t take into consideration maximum drawdown, VAR, skewness, etc. — factors that are important to many.</li><li>Doesn’t take into consideration taxes, fees, trading costs.</li><li>Might be not suitable for liability/asset-driven or specific goals strategy.</li></ol><h3>8. Other Models</h3><ol><li><strong>Reverse optimization:</strong> works in the opposite direction of traditional MVO. It begins with a set of asset allocation weights assumed to be optimal. Using these weights, along with the covariance matrix and a specified risk aversion coefficient, the model solves for the expected returns. These derived values are often referred to as <em>implied</em> or <em>imputed</em> returns. This approach effectively reflects the characteristics of a fully diversified market portfolio, consistent with the Capital Asset Pricing Model (CAPM).</li><li><strong>Black–Litterman model </strong>builds on the reverse optimization framework by starting with excess returns (returns above the risk-free rate) and then adjusting them to incorporate investor-specific views. This technique allows expected returns to reflect subjective insights while maintaining mathematical stability and producing reasonable output in the optimization process.</li><li><strong>Resampled Mean–Variance Optimization: </strong>This method integrates Markowitz’s mean–variance optimization with Monte Carlo simulation to account for estimation uncertainty. As a result, it often produces more diversified and robust portfolios. It is particularly useful when working with forward-looking estimates and limited data history.</li></ol><h3>9.Sources</h3><p>CFA Level III material: Principles of Asset Allocation</p><p><a href="https://medium.com/@filipstcu/a-comprehensive-guide-to-portfolio-optimization-with-pyportfolioopt-1e4de40dd0bb">A Comprehensive Guide to Portfolio Optimization with PyPortfolioOpt</a></p><p><a href="https://individuals.voya.com/insights/market-outlook/capital-market-assumptions-2025">https://individuals.voya.com/insights/market-outlook/capital-market-assumptions-2025</a></p><p><a href="https://www.youtube.com/watch?v=9GA2WlYFeBU&amp;t=1002s">https://www.youtube.com/watch?v=9GA2WlYFeBU&amp;t=1002s</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0b10665ddd08" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>