4/11/2026

The First Pillar Stands: Building an AI-Powered Equity Valuation Engine from Scratch

 

From blank Python file to institutional-grade model — and the bigger ambition behind it.

Four weeks ago, I set out to answer a simple question: can a rigorous, institutional-quality equity valuation be built entirely from scratch, using AI as a co-pilot, without compromising on methodology?

The answer, it turns out, is yes. Here is what I built, why it matters, and where it goes next.

The problem I was trying to solve

This project started with an ambition, not a gap. I wanted to build something sophisticated and scientifically sound — a model where every methodological choice reflected my own knowledge and judgment, not a template someone else had designed. Something that was genuinely mine: in its architecture, its assumptions, and its intellectual foundations.

The objective was also strategic. I wanted a tool rigorous enough to anchor a broader investment platform, something I could leverage across future projects rather than rebuild from scratch each time. A first pillar, in the most literal sense.

The context that made it necessary is well known. Professional equity valuation is expensive and largely inaccessible. The models used by investment banks and asset managers are built over months, maintained by teams of analysts, and guarded behind paywalls. Retail investors and smaller funds are left making decisions with far less rigor, often relying on a P/E ratio and a gut feeling. If the platform I am building is to have any credibility, it needs a valuation engine that can hold up against professional standards. That is what I set out to build.

What I built

Over four weeks, working session by session with Claude, I built a fully automated equity valuation engine in Python. Here is what it does, in plain language.

It reads ten years of official data. The model connects directly to SEC EDGAR — the US government's official financial filing database, and parses 40 quarterly reports and 10 annual reports for the company being analyzed. No manual data entry. No spreadsheet copy-paste. Audited numbers, machine-read.

It forecasts revenues using Geometric Brownian Motion, calibrated separately for each business segment on ten years of actual quarterly data. To prevent the model from over-reacting to recent quarters, Bayesian shrinkage blends short-term momentum with long-run sector drift. A Markov regime-switching layer adds economic realism: the model alternates between expansion and recession states, with recession volatility set 30% higher than in normal periods. Terminal revenue growth of 0.50% per year is derived from the GBM drift itself, not assumed arbitrarily.

It models costs through an Ornstein-Uhlenbeck mean-reverting process, anchored to the historical average cost ratio using an exponentially weighted moving average. This is an important design choice: it prevents the model from projecting runaway margin compression or perpetual expansion, keeping cost trajectories grounded in economic reality while still allowing for uncertainty. EUR/USD currency sensitivity is applied directly to the relevant segment's cost ratio throughout the simulation.

It applies distress guard-rails at multiple levels. CapEx is governed by a three-layer dynamic framework: a phase-gate structure tied to free cash flow thresholds, overlaid with a D&A-parity health floor that activates when net debt falls below 2.5 times EBITDA. The cost of equity carries an explicit distress premium , calculated as the spread between the cost of debt and the risk-free rate, scaled by a 60% loss-given-default assumption, reflecting elevated near-term financial risk. The conditional terminal value rule is a further guard-rail: if the company is forecast to earn below its cost of capital at the end of the horizon, the Gordon Growth model is suppressed and replaced entirely with a market multiple approach.

It runs 10,001 simulated futures simultaneously. This is the Monte Carlo engine. Rather than producing a single "correct" number, the model runs 10,001 different scenarios using Sobol quasi-Monte Carlo sequences, a low-discrepancy sampling technique that converges faster than standard random methods. Eight correlated risk drivers, revenue per segment, cost ratios, currency, and economic regime, are jointly simulated through a Cholesky decomposition, ensuring the correlations between them are realistic, not assumed to be independent. Every single path applies the conditional terminal value rule independently. With an odd number of paths, the median outcome is always a single, exact path, not an average.

It checks itself. Four automated sanity checks run after every execution: return on capital vs cost of capital, terminal value anchor, gap between the simulation median and the discounted cash flow estimate, and regime drift. If something looks wrong, it flags it.

It grades its own methodology. Across ten analytical dimensions: data quality, revenue modeling, cost structure, cost of capital, cash flow construction, terminal value, simulation design, stress testing, earnings quality, and internal consistency; the model scores its own rigor. The current score: 9.1 out of 10, grade A.

What makes this sound valuation, not just a number

Anyone can build a spreadsheet that spits out a price target. What makes this different is the methodology underneath.

The cost of capital updates live each run — fetching the current equity risk premium directly from Professor Damodaran's database, re-levering beta annually as the company's debt changes, and letting the risk-free rate evolve along a mean-reverting path rather than staying frozen at today's level.

The terminal value, the single most impactful assumption in any DCF, applies a conditional rule: if the company is expected to earn below its cost of capital at year seven, the Gordon Growth model is suppressed and replaced with a market multiple anchor. This is the correct thing to do financially, and most models simply don't do it.

The earnings quality checks are independent of the valuation itself. The Beneish M-Score, an academic model with an 85%+ accuracy rate at detecting earnings manipulation, runs on the same official filing data and produces a manipulation probability score for every year in the sample.

The model was built to be right and to allow your critical thinking, not just to produce a number.

What Claude brought to this

I want to be direct about this: I could not have built this in four weeks without Claude.

Not because the ideas were Claude’s, the financial methodology, the architecture decisions, the analytical judgments were all mine. But because building approximately 12,000 lines of Python, across a dozen interconnected modules, while simultaneously reasoning about financial theory, statistical methodology, and implementation correctness, is simply beyond what one person can hold in their head at once.

Claude served as a tireless co-pilot: catching logical errors before they propagated, translating financial intuition into working code, identifying edge cases I hadn't considered, and — critically — pushing back when my assumptions were financially unsound.

The result is a model I can genuinely defend. Every number has a traceable source. Every assumption has a documented rationale. That combination — human financial judgment, AI execution rigor — is where the real value lies.

The output on a real company

The model has been running live on a major publicly listed industrial company. The key outputs from the April 2026 live run:

  • DCF implied price: conservative single-path intrinsic value estimate
  • Monte Carlo median: the central outcome across 10,001 simulated futures — x% above the current market price
  • Downside scenario: a severe recession path implies −y% from current levels
  • Earnings quality: Beneish M-Score of −3.28 — manipulation unlikely, probability 3.6%
  • Model rating: A across 9 of 10 dimensions

The point is not the specific numbers. The point is that they emerge from a methodology that would hold up in a professional investment committee.

Where this goes next

This is the part that genuinely excites me.

Step one: multi-company. The engine is already company-agnostic, it reads from SEC EDGAR using any ticker. The next build extends it to run across an entire watchlist simultaneously: e.g screen 50 pre-selected companies, flag the ones where the Monte Carlo median diverges most significantly from the current market price, and surface the most mispriced opportunities automatically.

Step two: AI agents on top. This is the bigger ambition. Rather than a human analyst manually tweaking assumptions and re-running the model, I want a layer of autonomous agents that can monitor live earnings releases and update model inputs in real time, identify which assumptions are most sensitive and run targeted scenario analyses, compare a company's valuation across different economic regimes, and generate natural-language investment memos from model outputs.

The vision: give any investor — institutional or retail — the ability to ask "what is this company worth, and why?" about any publicly listed company in the world, and get a rigorous, methodology-grounded answer in minutes.

Why this matters

Equity research today is a privilege. It is expensive to produce and expensive to access. The analysis that moves capital is concentrated in a small number of institutions.

AI changes that equation. Not by replacing financial judgment, but by making it scalable. The same methodology that takes an analyst team weeks to build can, with the right architecture, run overnight on every company in an index.

I am not suggesting algorithms should replace human investment decisions. I am suggesting that the quality of information available to make those decisions should not depend on the size of your research budget.

That is what this project is about.

Follow along

I will be publishing the methodology in more detail, the valuation framework, the stress testing approach, the earnings quality models, on my Substack, blog and here on LinkedIn via a post.

If you are interested in quantitative equity research, AI-assisted financial modeling, or the intersection of the two, follow along. And if you are building something in the same space — or thinking about it, I would genuinely love to connect.

A presentation providing additional detail on the project, methodology, architecture, and outputs, is attached to this post.

Substack: https://substack.com/@pedrosantospinto

Blog: https://premioderisco.blogspot.pt

Personal page: https://pedrosantospinto.netlify.app

4/06/2026

The Currency Graveyard

Importance of History

Sometimes all we need is a good, meaningful look back to understand some basic economic concepts — no elaborate theorizing required.

If we want to identify the pillars that a currency must rest on to earn the status of world reserve currency, with all the privileges that entails, we need only study those that have played that role throughout the last few centuries. History, as usual, does the heavy lifting.

Subscribe now

So what are those pillars? There appear to be three constant building blocks that the supporting country or economy must possess:

1. The ability to run a sustained trade deficit. The economy behind the reserve currency must consistently buy more than it sells. Anchored by a strong domestic market, it generates enough surplus capital to purchase goods and services from the rest of the world — and crucially, to pay for them in its own currency. This is how that currency becomes widely available beyond its borders, gains perceived value, and ends up being used in transactions between third parties who have nothing to do with the issuing country.

2. Military and economic hegemony. Hard and soft power work together to spread the currency’s reach, demand, and usage across other economies. Without this, trust is hard to project at scale.

3. Strong and independent institutions. These are the guardians of the currency’s value, capable of shielding it from short-term political temptations by controlling monetary flows and, with them, inflation. Their independence from the executive and legislative branches is what prevents those in power from debasing the currency for electoral convenience.

Apply this simple framework to the current holder of reserve currency status, the dollar, and one might reasonably conclude that the United States is working rather hard to disqualify itself. Two of the three pillars are under relentless and, at times, breathtaking attack, all under a strategy grandly branded as Make America Great Again.

Share Risk Premium

People often say that ignorance can sometimes be a blessing. Unfortunately, in most cases, it is a curse — and one whose consequences fall not just on the ignorant, but on the lives of countless others who never asked to be part of the experiment.

Based on: “The decline and fall of the Roman currency empire”, The Economist, March 26, 2026.

https://ift.tt/0E1xs57



from Risk Premium https://ift.tt/CMlz8Pu
via IFTTT

3/02/2026

The Doomsday Clock just moved — and we're closer than ever

The Doomsday Clock just moved — and we're closer than ever At the end of January 2026, the Doomsday Clock was set to 85 seconds to midnight — the closest it has ever been since its creation. The Doomsday Clock is a symbolic timepiece maintained by the Bulletin of the Atomic Scientists since 1947. It represents how close humanity is to self-annihilation, with midnight symbolizing global catastrophe. The key risks driving us to 1 minute and 25 seconds from the end of the world, according to the Bulletin, are: 1-Nuclear weapons threats 2-Disruptive technologies, including AI 3-Biological security concerns 4-Climate change On a lighter note — and this is genuinely worth a smile — for something published by a board of scientists and Nobel laureates, the methodology behind the clock is remarkably loose. There is no defined formula, no scoring rubric, no aggregation model. It is, at its core, a group of very smart people agreeing on a number that feels right. The scientific method apparently took the day off when this one was designed. Jokes aside, you can think of it as a sentiment index on existential risk — a rough but informed read on how the world's brightest minds perceive the state of things. And right now, they are not feeling optimistic. Worth noting: all of this was set before the war that just started. So here's a question worth sitting with for a moment: how much time would you give us as a species before Doomsday? https://thebulletin.org/2026/01/press-release-it-is-85-seconds-to-midnight/

- Pedro

Read on Substack

Strategy vs Tactics a couple of key concepts often misunderstood

Strategy vs Tactics a couple of key concepts often misunderstood based on → On War: With Illustrations and Commentary by Andrew Kelly by Carl Von Clausewitz 1- “The conduct of War is, therefore, the formation and conduct of the fighting. If this fighting was a single act, there would be no necessity for any further subdivision, but the fight is composed of a greater or less number of single acts, complete in themselves, which we call combats, as we have shown in the first chapter of the first book, and which form new units. From this arises the totally different activities, that of the FORMATION and CONDUCT of these single combats in themselves, and the COMBINATION of them with one another, with a view to the ultimate object of the War. The first is called TACTICS, the other STRATEGY.” (“On War: With Illustrations and Commentary by Andrew Kelly (English Edition)” de “Carl Von Clausewitz, Andrew Kelly”). 2- “According to our classification, therefore, tactics IS THE THEORY OF THE USE OF MILITARY FORCES IN COMBAT. Strategy IS THE THEORY OF THE USE OF COMBATS FOR THE OBJECT OF THE WAR.” (“On War: With Illustrations and Commentary by Andrew Kelly (English Edition)” de “Carl Von Clausewitz, Andrew Kelly”). 3- “By the strategic plan is settled WHEN, WHERE, and WITH WHAT FORCES a battle is to be delivered—and to carry that into execution the march is the only means.” (“On War: With Illustrations and Commentary by Andrew Kelly (English Edition)” de “Carl Von Clausewitz, Andrew Kelly”).

- Pedro

Read on Substack

3/01/2026

Five KPIs to Understand the World

Five KPIs to Understand the World A great, simple article included in The World Ahead 2026 by The Economist, where for each country in the world it provides a snapshot with the following information: 1-GDP growth 2-GDP per person (also with PPP, US=100) 3-Inflation 4-Budget balance (as a % of GDP) 5-Population 6-For some countries, additional context is provided It is amazing how such simple KPIs can help you make an initial assessment of the world today. Although it was something I was already aware of, it was startling to see the population numbers and the relative levels of wealth in Asia-Pacific and MEA. With Europe, it was also a good reminder that GDP per person can be significantly diluted when taking into consideration the Purchasing Power Parity normalisation factors. An article and tool I will keep handy, as it provides significant value and allows us to put so much into perspective. A article/tool i will keep handy as it provides significant value and allow us to put so much into perspective. The world in numbers: Countries https://www.economist.com/interactive/twa-country-reports From The Economist

- Pedro

Read on Substack

Books to Understand the Men and Context That Created America's Institutions and Its Checks and Balances

Books to Understand the Men and Context That Created America's Institutions and Its Checks and Balances Recommended by The Economist, plus one of my own additions: 1-Founding Brothers: The Revolutionary Generation — Joseph J. Ellis (Knopf) 2-The Radicalism of the American Revolution — Gordon S. Wood 3-The Revolutionary: Samuel Adams — Stacy Schiff (Little, Brown) 4-John Adams — David McCullough (Simon & Schuster) 5-A Magnificent Catastrophe: The Tumultuous Election of 1800, America's First Presidential Campaign — Edward J. Larson 6-The Hemingses of Monticello: An American Family — Annette Gordon-Reed (W. W. Norton) All six are on my wish list. And I would add one classic of my own: 7-Democracy in America — Alexis de Tocqueville Seven books to understand the Founding Fathers. https://www.economist.com/culture/2026/01/06/six-books-to-understand-the-founding-fathers From The Economist

- Pedro

Read on Substack

The Cost of Short-Term Thinking

The Cost of Short-Term Thinking Just read this quote on a Russ Roberts Substack article citing Bastiat (french economist from the XIX),that, as most of his work, I really liked — it made me think, and I could not agree more. "...In the economic sphere an act, a habit, an institution, a law produces not only one effect, but a series of effects. Of these effects, the first alone is immediate; it appears simultaneously with its cause; it is seen. The other effects emerge only subsequently; they are not seen; we are fortunate if we foresee them. There is only one difference between a bad economist and a good one: the bad economist confines himself to the visible effect; the good economist takes into account both the effect that can be seen and those effects that must be foreseen.Yet this difference is tremendous; for it almost always happens that when the immediate consequence is favorable, the later consequences are disastrous, and vice versa. Whence it follows that the bad economist pursues a small present good that will be followed by a great evil to come, while the good economist pursues a great good to come, at the risk of a small present evil. …" Frederic Bastiat — French economist https://en.wikipedia.org/wiki/Fr%C3%A9d%C3%A9ric_Bastiat

- Pedro

Read on Substack