<?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 Roman Ulasevich on Medium]]></title>
        <description><![CDATA[Stories by Roman Ulasevich on Medium]]></description>
        <link>https://medium.com/@ulasevichr?source=rss-2857b4e8bbb9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*7PyESbHeRZqw66NpZIRcuw.png</url>
            <title>Stories by Roman Ulasevich on Medium</title>
            <link>https://medium.com/@ulasevichr?source=rss-2857b4e8bbb9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 03:53:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ulasevichr/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[Bring your own AI agent to Google Sheets]]></title>
            <link>https://medium.com/@ulasevichr/bring-your-own-ai-agent-to-google-sheets-355944b32342?source=rss-2857b4e8bbb9------2</link>
            <guid isPermaLink="false">https://medium.com/p/355944b32342</guid>
            <category><![CDATA[python-libraries]]></category>
            <category><![CDATA[spreadsheets]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[google-sheets]]></category>
            <category><![CDATA[financial-modeling]]></category>
            <dc:creator><![CDATA[Roman Ulasevich]]></dc:creator>
            <pubDate>Tue, 13 Oct 2026 12:29:17 GMT</pubDate>
            <atom:updated>2026-10-13T12:43:32.588Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wCc9sPW36UCRAZuf-w0esg.png" /></figure><p>A while ago I wrote two articles here about using AI for financial modeling: one on <a href="https://medium.com/@ulasevichr/ai-for-financial-modeling-part-1-6907e1597c34">checking models for errors</a>, one on <a href="https://medium.com/@ulasevichr/ai-for-financial-modeling-part-2-b73c49811913">building them</a>. Both were written for Excel and VBA, using a free Gemini API and a lot of prompt experimentation. A lot has changed since then. Some things have not, and I will come back to both in follow-up articles. In this one I would like to do something simpler: show you a tool I have been building for spreadsheet-AI integration, which is now available for download.</p><p><em>One more thing before we start. I use AI tools to help me write, but I review and edit everything, and I have the final say on what gets published.</em></p><h3><strong>Why?</strong></h3><p><strong>What is GridShell?</strong></p><p>GridShell puts a real terminal inside a Google Sheet. The terminal is connected live to the spreadsheet you have open, and an AI agent can use it to read and change that spreadsheet: write values and formulas, format cells, build charts. You can also drive the same sheet from a plain Python script, with no AI involved.</p><p>Two things I want to highlight here. First, GridShell allows you to build up a spreadsheet iteratively (and interactively), instead of relying on one big prompt and hoping the result will be right. In this respect it is similar to some built-in add-ins for spreadsheets (e.g. Copilot, Gemini) and third-party ones (e.g. Claude, ChatGPT). Second, unlike those add-ins, there is no vendor lock-in. GridShell does not include or host any AI model, and it never sees your spreadsheet data. You bring the agent you already use, including ones running locally on your own machine, and GridShell only connects it to the sheet.</p><p>It comes in two parts. The add-on is installed from the Google Workspace Marketplace and gives you the terminal inside Sheets. The server is an open-source Python package (MIT license) that you run yourself, and it provides the shell and the connection for the agent.</p><p><strong>Why Sheets, and not Excel?</strong></p><p>I was building this tool with financial modeling in mind and Excel was a natural first choice. In fact, the first MVP I built was an Excel add-in, only to find out that Microsoft’s add-in marketplace does not work with private developers. So I had to re-prioritize and move to Google Sheets, where the add-on recently went live on the Marketplace. That said, the Excel add-in is still on my list, waiting for your reception of GridShell and your feedback.</p><p><strong>A quick word on CLI agents</strong></p><p>An agent that you will run in GridShell is a command-line (CLI) agent. Claude Code, Codex, OpenCode and Antigravity are well-known examples, and any CLI agent that supports MCP will work. These agents were initially built for coding tasks and allow for granular management of instructions, skills, tools and memory among other things. Running in GridShell, they can read files, run commands, write code and interact with your spreadsheet, which makes the whole setup very flexible. For example, you could ask an agent to adjust its own skills or tools while working with a spreadsheet.</p><p><strong>Not another MCP server</strong></p><p>GridShell uses the MCP protocol to connect your agent or script to a spreadsheet. However, in contrast to an MCP server making “external” API calls, it runs inside Sheets, so your agent or script can see and interact with your current selection of sheet, range or cell. That makes back-and-forth communication with the agent simple and allows you to reuse the same unmodified script with different layouts.</p><p><strong>You are in control</strong></p><p>You can run the GridShell server locally on your machine or on a remote host, but it is always your server. You can treat the gridshell library as a reference implementation that you are free to change to suit your needs, e.g. port it to another language or add security features. But most importantly, you can change the way an agent communicates with a spreadsheet. Want it to use focused tools instead of relying on instructions and skills? No problem, you can develop such tools and impose them server-side.</p><h3><strong>How?</strong></h3><p>I will keep this to a basic local setup on your own machine. That is the simplest way to start, and everything more advanced is linked at the end.</p><p><strong>1. Install the add-on</strong></p><p>Open the <a href="https://workspace.google.com/marketplace/app/gridshell/656676222795">GridShell page on the Google Workspace Marketplace</a> and install it. Then open a Google Sheet and reload it. A GridShell menu appears, under Extensions or as its own menu depending on your Workspace settings.</p><p><strong>2. Install and run the server</strong></p><p>You need Python 3.11 or later. Then:</p><pre>pip install gridshell<br>gridshell-server</pre><p>That will start a local server instance listening on port 3000 by default. If you want to change the port, pass the --port flag, e.g. gridshell-server --port 3012 .</p><p>The first time the server starts, it creates an access token and copies it to your clipboard. The token is required by default, even on your own machine, and it is never printed on screen. The token is saved to ~/.gridshell/token , so it survives restarts. If you lose it, gridshell-server --copy-token puts it on the clipboard again (run it when the server is stopped, or from a separate terminal window).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*8UoYGadReeUlejTumuF0Ng.png" /><figcaption>Server start on non-default port 3012</figcaption></figure><p>Back in the spreadsheet, choose GridShell → Open from the menu to open the sidebar, and expand Settings. Choose ws:// for a local server, enter localhost:PORT as the address, e.g. localhost:3012 , paste the token into the Auth token field and click Save. You only do this once per Google account.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/283/1*ml4CQJovwFTM5YvlelSeLg.png" /><figcaption>Server address and Auth token settings</figcaption></figure><p><strong>3. Open a shell, adjust view settings</strong></p><p>Click “+ New shell” in the sidebar. A new shell session starts and opens in a dialog window. You can add another session by clicking “+ New shell” again (the free version allows a maximum of 2 shells, see below). The new shell window replaces the previous one, but the first session is still running, and you can click it in the sidebar to re-open its window. These are two parallel sessions, so you can run completely different things in them, e.g. an agent in one and a script in the other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/326/1*rO7lZp1eZgSTeOtBK_CMXA.png" /><figcaption>Sidebar with two opened shells</figcaption></figure><p>Depending on your monitor, the default shell window size may be too large. Unfortunately, Sheets add-ons do not allow you to resize a dialog window by dragging. Instead, you change the window size in Settings, where you can also set the font size and theme.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/285/1*ECxq-ws9mADI87FHoAqq3A.png" /><figcaption>View settings</figcaption></figure><p>The new view settings are applied when the shell window is restarted. Simply click a shell in the sidebar and its window will reopen with the new settings.</p><p><strong>4. Close a shell, kill one or all sessions</strong></p><p>You can close (hide) and re-open a shell, and it will re-attach to the same session you were running before. Whatever was running prior to closing, including calls to the spreadsheet, keeps running while the window is closed. So be careful: if you work with two shell sessions and both are running calls against your spreadsheet, the result may be a mess even if all shell windows are closed.</p><p>Shell sessions are persistent. Unless you kill them (see below), they keep running for 12 hours (the default) after the respective shell window was closed, even if the GridShell sidebar is closed completely. So you can switch between different add-ons, or go and grab a coffee, without losing your work.</p><p>To destroy (kill) a shell session, press the bin button that appears next to the respective shell in the sidebar when you hover over it. You can also kill all running sessions from the GridShell menu under Extensions. A session is also destroyed when the 12-hour period mentioned above expires or when the server is stopped. A destroyed session cannot be restored, so be careful.</p><p>There are other, more advanced settings on both the add-on and the server side. See the <a href="https://gridshell.app/app/settings-and-limitations/">add-on</a> and <a href="https://gridshell.app/library/server/">server</a> documentation for more information about settings and server deployment options.</p><h3><strong>What?</strong></h3><p><strong>A CLI agent</strong></p><p>Now that GridShell is installed, you can run a CLI agent of your choice in it. However, for the agent to communicate with the spreadsheet, you need to point it at the MCP relay installed with the gridshell library. This is done the same way as for any MCP server (please refer to your agent’s documentation), but in most cases you need to add the relay to the agent’s config file. For example, for OpenCode’s opencode.json , if your server is running on a non-default port 3012:</p><pre>{<br>  &quot;mcp&quot;: {<br>    &quot;gridshell-sheets&quot;: {<br>      &quot;type&quot;: &quot;local&quot;,<br>      &quot;command&quot;: [&quot;gridshell-mcp&quot;, &quot;--port&quot;, &quot;3012&quot;]<br>    }<br>  }<br>}</pre><p>Some CLI agents have shortcuts for adding MCP servers. For example, in Claude Code you can just run:</p><pre>claude mcp add gridshell-sheets -- gridshell-mcp --port 3012</pre><p>Now you can start your agent, for example Claude Code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4E3lUMiH8vr-00-X9qOIKw.png" /><figcaption>Shell with Claude Code running (Claude Code is used here as an example)</figcaption></figure><p>Once it is running, the agent can manipulate the sheet through structured calls (tools). It can read what is in the sheet, or just the part you have selected. It can write values and formulas, format ranges, and add charts or pivots. There are certain limitations, which I describe below. You can find more information on the <a href="https://gridshell.app/library/mcp/#tools">available tools</a> in the documentation.</p><p>You can also equip your agent for a particular set of tasks or a workflow by changing its instructions or adding skills or tools (MCP servers). Please refer to your agent’s documentation for details. Just as an example, for financial modeling tasks with Claude Code you can add Anthropic’s financial-services plugin by following the instructions <a href="https://github.com/anthropics/financial-services">here</a>.</p><p>Finally, as I mentioned above, you can also customize GridShell’s own tools. You can find more information about <a href="https://gridshell.app/library/mcp/#customizing">customization</a> in the documentation. I am also planning to provide more concrete examples in follow-up articles.</p><p><strong>The Python client</strong></p><p>An alternative way to connect to and manipulate a spreadsheet using GridShell is through the Python client installed with the gridshell library. Out of the box, SheetsClient lets you read a range, write values back, or append a row from any Python program or the command line. For anything beyond these, the client also has a general-purpose method that accepts the same structured calls an agent uses, so you can build practically any operation yourself.</p><p>Here is a minimal example you can run in a Python REPL in a GridShell shell. Inside a GridShell shell, the client picks up the token and the target spreadsheet automatically. Add port= if your server is not on the default port:</p><pre>from gridshell import SheetsClient<br><br>grid = SheetsClient(port=3012)<br>grid.get_values()# get values from selected range<br>grid.set_values([[5, 6], [7, 8]], range=&quot;A3:B4&quot;)<br>grid.close()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yqfDUDDZg8Q59-zEat3_pg.png" /><figcaption>Shell with Python REPL running</figcaption></figure><p>The client is handy for repeatable jobs that you do not want an agent to reinvent each time. It can be run by you directly, with no AI involved, or by an agent. For basic and more advanced usage of the client, see the <a href="https://gridshell.app/library/python-client/">Python client docs</a>.</p><p><strong>Limitations</strong></p><p>Some limits are worth knowing from the beginning.</p><p>A few things are reserved for a possible future paid tier: cosmetic chart styling, conditional-formatting color scales, spreadsheet theming, protection and sharing controls, a higher (or removable) cap on the number of shells, and a longer time limit for a single batch of operations (currently about four and a half minutes). Some features are not available simply because they are not built yet, e.g. letting an agent work across more than one open spreadsheet from a single session, or creating native custom functions that can be called from a cell.</p><p>See the <a href="https://gridshell.app/app/settings-and-limitations/">limitations page</a> and <a href="https://gridshell.app/roadmap/">roadmap</a> for more information.</p><h3><strong>Beyond this article</strong></h3><p>I kept this one to the basics on purpose. The bigger topics are in the docs, and I would be glad to write about any of them:</p><ul><li>Running a server remotely, with TLS and hardening: <a href="https://gridshell.app/library/server/#security-deployment">Security and deployment</a>.</li><li>Building your own tools on top of the built-in ones: <a href="https://gridshell.app/library/mcp/#customizing">Customizing</a>.</li><li>Security in general. The short version is that the token is required by default, and the agent has the same shell access it already has in your terminal. Spreadsheet content is untrusted input, like any other.</li></ul><p>GridShell is free and provided as-is, with no warranty. The full terms are in the docs.</p><h3><strong>What next?</strong></h3><p>The next articles will have more in-depth finance examples, and I will also bring back the threads from my earlier pieces. If there is something else you would like to see covered, such as remote setup, custom tools, Python-driven workflows or other agents, leave a comment and tell me.</p><p>For bugs and feature requests, please use <a href="https://github.com/gridshell-app/gridshell/issues">GitHub issues</a>. For questions and general feedback about the tool itself, please use <a href="https://github.com/gridshell-app/gridshell/discussions">GitHub Discussions</a>, so that they do not get lost in the comments here.</p><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=355944b32342" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI for Financial Modeling — Part 2]]></title>
            <link>https://medium.com/@ulasevichr/ai-for-financial-modeling-part-2-b73c49811913?source=rss-2857b4e8bbb9------2</link>
            <guid isPermaLink="false">https://medium.com/p/b73c49811913</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[financial-modeling]]></category>
            <category><![CDATA[vba]]></category>
            <category><![CDATA[excel]]></category>
            <dc:creator><![CDATA[Roman Ulasevich]]></dc:creator>
            <pubDate>Wed, 02 Jul 2025 17:18:09 GMT</pubDate>
            <atom:updated>2025-07-03T09:43:43.080Z</atom:updated>
            <content:encoded><![CDATA[<h3>AI for Financial Modeling — Part 2</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XAwAzU_6JjHedjkd5VvI_w.png" /><figcaption>Image generated by Gemini</figcaption></figure><p>In the previous part, we discussed how AI could be used to identify errors in financial models. Next, we’ll explore whether we can utilize it to actually build a model.</p><p>Please refer to my previous <a href="https://medium.com/@ulasevichr/ai-for-financial-modeling-part-1-6907e1597c34">article</a> for more information about prerequisites and the experimental setup.</p><p>Let’s start with a simple example: assume that we want to build a schedule with various expense items that are dependent on the number of SG&amp;A employees, such as salaries and taxes, telecom expenses, travel expenses, etc. We have already forecasted base expenses per employee, the number of employees, and the inflation index. Now, we need to tie these together for one expense item and then repeat the calculation for the others.</p><p>As with error checking, we’ll start with a context.</p><h3>Context</h3><p>In this case, the context we need to provide is information about the inputs (labels and ranges) that we want to use for our calculations. Ideally, we’d have some sort of schema listing the financial model’s structure, including all inputs and calculations (and their respective ranges). Then, we could just specify input names in the prompt or let the LLM choose which inputs are required for the calculation. In the absence of such a schema, I’ll use a simplified approach, providing the required information explicitly. To make it more convenient, the following form can be used:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*Jt_8ObHKXJ7bx9Mgrsr-TQ.png" /><figcaption><em>Input form example</em></figcaption></figure><p>All we need to do is to choose input labels and ranges and once all inputs are added the following part of the prompt will be generated:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*x8KBvFl7bqguyzk9WDH0ZA.png" /><figcaption><em>Prompt example (input part)</em></figcaption></figure><p>Now we can specify the rest of the task resulting in the following prompt:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*v28e_gvudW3IfEPcNSUtOg.png" /><figcaption><em>Prompt example</em></figcaption></figure><p>As you can see at this point, we are calculating only the inflated salary per employee. I will continue the expense schedule example below but first let’s examine the output generated by the LLM.</p><h3>Output Formatting</h3><p>The most straightforward approach would be to generate VBA code that, upon execution, would produce the required calculations. However, this approach presents two potential problems.</p><p>First, even for simpler calculations, the output would be quite long, and a user would need VBA knowledge to review it. And we would definitely want to review it before allowing changes to our existing model.</p><p>Second, even if the calculations themselves are correct, the VBA code might be (and often will be) buggy. So, again, the user would need sound VBA knowledge and would have to spend considerable time reviewing the code rather than the calculation’s logic.</p><p>To avoid these problems, I’ve used another approach: “standardize” the output so it can be evaluated (executed) using a universal macro. For this purpose, I instructed the LLM (more on this below) to provide the output in the form of a simplified code-like notation.</p><p>Here is an example of the output for the prompt provided in the previous section:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*JJYPOr5dTqSCzfAwoeaeWw.png" /><figcaption><em>Output example</em></figcaption></figure><p>As you can see, the notation is somewhat similar to VBA and has the following form: <em>range.method(parameter)</em>.</p><p>Such output can be “executed” using a fairly simple macro, given that only three methods are required to build a financial model: VALUE, FORMULA, and COPYPASTE (I assume no formatting is required).</p><p>The output is also pretty compact, not only compared to normal VBA code but also to a cell-by-cell output (which is another alternative).</p><p>To further increase user-friendliness, we could reformat the output displayed to a user — for example, by hiding method/property names or replacing cell references with labels (see the first part of this article). However, in this case, we’d need to be sure there are no mistakes in the “hidden” part.</p><h3>Prompt Engineering</h3><p>Given that we’d like the output to be in a specific and non-standard format, we need to add some examples. So, a zero-shot prompt won’t do the job (please note that by prompt I mean a system instruction rather than a user prompt).</p><p>Based on my experiments, a few examples of base methods — value, formula, and copy and paste — should be sufficient for the LLM to output the correct format. If you’d like to follow some specific modeling conventions — for example, repeating (link) the inputs from other sheets before making calculations on a new sheet — some additional examples should be added.</p><p>The above (along with some descriptive instructions) should work fine for fairly simple calculations, as in our expense schedule example. However, as I mentioned in my previous <a href="https://medium.com/@ulasevichr/ai-for-financial-modeling-part-1-6907e1597c34">article</a>, due to the lack of adequate training data, LLMs aren’t very good at financial modeling. Hence, for more comprehensive calculations — for example, building a depreciation schedule using the corkscrew method — an additional example should be added.</p><p>This way, we may end up with too many examples to squeeze into our system instruction. So, I’ll discuss an alternative path below.</p><h3>Results and Examples</h3><p>Now let’s go back to building our expense schedule.</p><p><strong>Previous Example Continued</strong></p><p>We have calculated the inflated salary per employee, and now we can calculate the total salary:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*MiuRfijzJL5P5t5obOB6qQ.png" /><figcaption><em>Prompt</em>/<em>Output example</em></figcaption></figure><p>If we run the macro to evaluate both outputs (per employee and total salary), the following calculation will be produced:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*cXhHLhYD1ZwvFkuFEzNCJQ.png" /><figcaption><em>Calculation output example (formatting added by the author)</em></figcaption></figure><p>A few things to mention here — the formatting was added separately to make the output more readable; the calculation output is somewhat simplified and doesn’t fully comply with good modeling practices, for example, there is no unit column.</p><p>Also, sometimes the LLM will make mistakes even in simpler calculations. For instance, it might forget an anchor. In such cases, you can ask it to correct the mistake.</p><p>And now comes the beautiful part. As you remember, we had several expense items to model. These items are modeled the same way, so we can reuse the calculation block we just created. However, we’ll need to change the labels and the links. When done manually, this takes some time and can result in mistakes. Using AI, it can be done rather quickly:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*is4RIG1L3LykvOd7MSYMMA.png" /><figcaption><em>Prompt</em>/<em>Output example (some of the output rows are hidden)</em></figcaption></figure><p>Now, for several calculation blocks, the output is somewhat long, so I’ve hidden some of the rows. But it was generated in seconds and correctly:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*C1Xj_nL6Dfp44O7pgvymtQ.png" /><figcaption><em>Calculation output example (formatting added by the author)</em></figcaption></figure><p>So, once we have a working calculation example, repeating it in another context shouldn’t be a problem. As you’ll see below, it even works for more comprehensive calculations.</p><p><strong>Another Example</strong></p><p>Now, let’s see if we can build something more comprehensive, like a depreciation schedule. As I mentioned previously, the model’s system instruction contains a general example of a depreciation schedule for PPE. So, basically, what it needs to do is to correctly tie the inputs and change the labels if needed.</p><p>We’ll start with the depreciable basis:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*xOYBigsKqsxzd-tBrY1kww.png" /><figcaption><em>Prompt</em>/<em>Output example</em></figcaption></figure><p>The output is correct, and I’ll provide the resulting calculation below. The only thing I asked the LLM to change was to insert a blank row before the corkscrew calculation. Now, it’s pretty easy to insert it yourself, so why use AI to do it?</p><p>The reason is that I intend to continue the calculation and will need some of the already generated outputs. If I insert a row myself, the later formulas produced by the LLM will reference incorrect rows (alternatively, I could provide these already generated outputs as new inputs).</p><p>For the sake of space, I’ll provide only the prompt here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/983/1*OF0HQ8seoC_KjppmyJpRbg.png" /><figcaption><em>Prompt example</em></figcaption></figure><p>Now moving to depreciation schedule:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*RzDfjO9qxmGrQfxcqb8NLw.png" /><figcaption><em>Prompt</em>/<em>Output example</em></figcaption></figure><p>And here is the resulting calculation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*5uI6uAmegGVbftTwrJKCKg.png" /><figcaption><em>Calculation output example (formatting added by the author)</em></figcaption></figure><p>The output seems fine to me, and it can now be replicated for other fixed assets in seconds. However, I should underline once again that it’s not something the LLM generated on its own, but rather copied from the provided example, albeit fitting the example to the context.</p><p>To illustrate the point, the depreciation example can be extended beyond the one provided in the system instruction. For example, we may want to take into account the equipment’s salvage value and add sales proceeds to the calculation.</p><p>A rather simple change, but it took me more than an hour of trial and error to get to the prompt that produced a satisfactory output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*Vvr1f2PKHuiRvVHwh1NEBQ.png" /><figcaption><em>Prompt example</em></figcaption></figure><p>As you can see, the prompt is rather long and detailed, and basically, I’m describing all the steps required to make the change. This definitely isn’t something you’d be willing to waste your time on when working on a real model.</p><p>So, to summarize: as soon as a financial modeling task goes beyond plain vanilla stepwise calculations, the LLM would need an example to accomplish such a task efficiently, as what it does best is “smart” copy-pasting.</p><p>At this point, it could be argued that a more advanced model (e.g., one with reasoning capabilities) could probably do better. That might be true for the above example, but how reliable would it be in general and for more advanced cases (see, for example, <a href="https://machinelearning.apple.com/research/illusion-of-thinking">https://machinelearning.apple.com/research/illusion-of-thinking</a>)? And do we really need something more than “smart” copy-pasting to build a meaningful tool for financial modeling?</p><h3>Discussion and Further Development</h3><p>As a financial modeling practitioner, I use templates a lot. Sometimes these can be whole models or sheets, but most often it’s just calculation blocks that I copy directly or replicate their logic. Still, it takes a lot of time to relink, relabel, and duplicate as may be required, not to mention the potential mistakes that can be made during this process.</p><p>As we’ve seen above, this work can be outsourced to an LLM. The only thing it needs is examples. And these examples can be extracted from existing models and/or templates. Moreover, this can be done in at least a semi-automatic way, as the process of converting the simplified notation output by an LLM to calculations can be reversed using another macro.</p><p>Once we have the example collection, there are two options to “inject” this knowledge into the model: Retrieval Augmented Generation (RAG) and/or fine-tuning.</p><p>At this point, I haven’t tested any of these options, but I suppose that fine-tuning might be preferable in this case as we’d like the model to learn a specific way of “thinking” and formatting its answers. That said, it could be further combined with RAG to allow for updates without retraining the model. And the good thing is that the proposed simplified notation should be quite efficient in terms of token usage.</p><p>So far, I’ve implicitly assumed an LLM’s role to be that of an assistant helping to develop parts of a financial model, but why not build one from scratch?</p><p>I don’t think it’s impossible, but I suppose it will require an LLM to work in agent mode, allowing it, among other things, to verify the results of the output it produces. Not to mention a vast training dataset that should include a large number of financial models for different industries and tasks, and probably be available only at a larger consulting firm level.</p><h3>Conclusions</h3><ul><li>Using an LLM to generate financial calculations in Excel requires considering both input (context) and output.</li><li>The LLM’s output should be convertible into actual calculations. This can be achieved by imposing a code-like notation that can be evaluated using a macro and is more efficient than a cell-by-cell or a direct VBA code output.</li><li>While a general-purpose LLM might work for simple stepwise calculations and “smart” copy-pasting, building more advanced, specialized calculations requires additional examples.</li><li>Such examples can be extracted from the existing financial models with minimal human intervention and used for fine-tuning and/or RAG.</li></ul><p>My intent is to continue this series of articles with the next part devoted to fine-tuning LLM for generating financial calculations. Please note that it may take considerable time, especially given my current workload. Please stay tuned.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b73c49811913" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI for Financial Modeling — Part 1]]></title>
            <link>https://medium.com/@ulasevichr/ai-for-financial-modeling-part-1-6907e1597c34?source=rss-2857b4e8bbb9------2</link>
            <guid isPermaLink="false">https://medium.com/p/6907e1597c34</guid>
            <category><![CDATA[financial-modeling]]></category>
            <category><![CDATA[vba]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[excel]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Roman Ulasevich]]></dc:creator>
            <pubDate>Thu, 24 Apr 2025 13:16:07 GMT</pubDate>
            <atom:updated>2025-04-24T13:16:07.065Z</atom:updated>
            <content:encoded><![CDATA[<h3>AI for Financial Modeling — Part 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aFu99ENdxYrhsSmw" /><figcaption>Photo by <a href="https://unsplash.com/@amstram?utm_source=medium&amp;utm_medium=referral">Scott Graham</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3><strong>Abstract</strong></h3><p>This article is aimed at financial modeling practitioners, spreadsheet tool developers, and anyone interested in AI, financial modeling, and spreadsheet automation.</p><p>Although I will be sharing some results from practical experiments, I have decided not to include code. First, the article already feels quite long. Second, the tools I will be discussing are in an early stage of development, and I don’t believe that including code would add significant practical value.</p><p>To fully understand the examples provided in this article, prior experience with financial modeling is highly recommended.</p><p>Please note that this is not formal research, and the conclusions presented here may be subjective.</p><h3><strong>Introduction</strong></h3><p>Large Language Models (LLM) are increasingly used in coding to automate tasks, provide assistance, and generate code. Spreadsheet modeling, while less abstract, shares similarities with coding. AI is finding its way into spreadsheet applications through tools like Microsoft’s Copilot for Excel, which assists with data analysis, visualization, and even formula creation. But can we leverage AI tools to automate financial modeling tasks?</p><p>As with coding, AI is not a magic bullet, and you should not expect it to miraculously build a financial model from scratch without human intervention. However, certain modeling tasks could potentially be automated (or semi-automated) to aid model developers, auditors, and other stakeholders in building and reviewing spreadsheet models.</p><p>So, let’s see how AI could help.</p><h3><strong>How AI could help</strong></h3><p><strong>Error checking</strong></p><p>According to some studies more than 90% of spreadsheets used in business decision-making contain errors (see for example <a href="https://phys.org/news/2024-08-business-spreadsheets-critical-errors.html">https://phys.org/news/2024-08-business-spreadsheets-critical-errors.html</a>) and financial models are no exception. Error checking is a tedious process, particularly for large, complex models and there are even specialized firms out there to audit these models. Not to mention various programs, individual macros and stress tests developed for this purpose. And still errors remain.</p><p>Some errors are easier to detect algorithmically than others, e.g. checking formula consistency across a row can be accomplished with a simple macro. However, other errors, such as logical formula errors, are typically identified using less consistent, reliable, and time-consuming methods like sense-checking (paired with testing).</p><p>The question is whether generative AI, with its current limited reasoning capabilities and potential lack of domain knowledge (especially when using a general-purpose LLM), can effectively identify these types of errors.</p><p><strong>Model development</strong></p><p>Despite being built for diverse situations, industries, and company life stages, financial models frequently utilize similar, reusable building blocks, such as depreciation schedules, tax schedules, working capital schedules, DCF calculations, equity waterfalls etc. Many modeling practitioners re-use templates or calculation blocks from previous models to speed up the process of building a new model.</p><p>That said, in many cases it is not as simple as mere copying and pasting. Templates and blocks often require relinking, label modifications, and formula or logic adjustments. This process is also error-prone. Even though calculation blocks are usually thoroughly checked, a single missed row anchor can easily lead to a difficult-to-detect error.</p><p>Based on my experience with AI code generation, it works best for generating standard code segments adapted to specific context. And essentially, I would like to apply this same capability to financial modeling.</p><p><strong>Other</strong></p><p>There are also other potential use cases for AI in financial modeling. For example, it could explain complex calculations or model sections to external recipients or assist model developers in streamlining individual formulas or calculation blocks. While I won’t focus on these applications here, I believe they can be developed based on error-checking and model-building capabilities.</p><h3><strong>Experimental Setup</strong></h3><p>Although there are other popular spreadsheet programs, e.g. Google Sheets, financial models are still mainly built in Excel. Therefore, I used VBA to build the tool prototype.</p><p>While VBA is not ideal for constructing LLM workflows, particularly for API connections and JSON handling, libraries like openpyxl (<a href="https://pypi.org/project/openpyxl/">https://pypi.org/project/openpyxl/</a>) offer the capability to migrate workflows to Python. However, considering the prototype’s simplicity and the absence of complex calculations or large datasets, introducing a Python layer at this stage would only add unnecessary complexity without providing significant advantages.</p><p>For the LLM, I chose Gemini. In my opinion, it is among the best models currently available, and its API remains free for experimental use.</p><p>As previously stated, I am not sharing code in this article. However, you can find an example of connecting to the Gemini API endpoint from Excel here: <a href="https://www.listendata.com/2023/12/integrate-gemini-into-excel.html">https://www.listendata.com/2023/12/integrate-gemini-into-excel.html</a>. If you prefer OpenAI’s products, a similar example is available here: <a href="https://github.com/Sven-Bo/excel-add-in-tutorial-template/blob/master/mChatGPT.bas">https://github.com/Sven-Bo/excel-add-in-tutorial-template/blob/master/mChatGPT.bas</a>.</p><h3><strong>Error checking</strong></h3><p>Let’s now examine how we can approach the error-checking task.</p><p>Current LLM models demonstrate a reasonable “proficiency” with Excel. Given sufficient context, they can explain, streamline, create, or check Excel formulas through a web UI (similar to other applications, the quality of responses varies based on the context and task complexity). However, manually copying and pasting formulas into a model chat and explaining their interdependencies formula by formula is not a practical approach for error checking. Therefore, we will aim to automate this process.</p><p><strong>Adding context</strong></p><p><em>Layout</em></p><p>Financial models are mostly time series; the right side contains calculations for each period, while the left provides row labels and supporting information such as units. Knowing this we could try to extract the required information without any additional layout specification.</p><p>However, in practice the left side may contain much more than just contextual information. Part of this information, such as constants, needs to be considered for our analysis, yet another, such as display-only elements (e.g. row totals), is probably better left outside of the analysis perimeter to keep LLM focused.</p><p>Therefore, to keep things simple I explicitly specify the base layout structure for the context extraction as shown in the example below (although here I focus on a typical time-series model layout, the same principles apply to cross-sectional data).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/381/1*djMss9tVfn2IuJ9kds_6lg.png" /><figcaption>Layout form example</figcaption></figure><p>The key layout items that we need to specify are the columns for series, constants and labels. For models with consistent layout the need to repeat this setup is minimized.</p><p>For non-standard layouts, additional input ranges can be specified using the lower section of the form.</p><p>This is a simplified example. As you will see below, currently I am not extracting section headers and units, although sometimes this part of a context might be useful. Also, for poorly structured models with issues like repeating labels, inconsistent label placement, and mixed time resolutions (just to name a few) the extraction algorithm might need to be further developed. At the same time, I have a subtle hope that the appearance of modeling tools that could significantly increase productivity might also encourage standardization in the financial modeling sector.</p><p><em>Formula “translation”</em></p><p>Now when we have the layout, let’s see how we can add context to the formulas (or formula blocks). I have experimented with two approaches that I will describe below based on the following example:</p><p>J31=J18*J23/J29</p><p>Without knowing the output and input names, it’s difficult to understand what this formula calculates, let alone determine its correctness. However, since we’ve already extracted the layout, we can use VBA code to identify that J31 represents the Accounts Receivable Balance, J18 the Revenue Forecast, J23 the Accounts Receivable Days, and J29 the Number of Days in a period. Excellent. How can we communicate this information to LLM?</p><p><em>Formula “translation” — 1st approach</em></p><p>My initial approach was rewriting the formula using the labels. However, given that we are working with two-dimensional time series, I also incorporated the time dimension to get the following formula for the first column in the series range:</p><p><em>‘</em>Accounts Receivable Balance’ [t0] = ‘Revenue Forecast’ [t0] * ‘Accounts Receivable Days’ [t0] / ‘Number of Days’ [t0]</p><p>The formula “translation” is done automatically. The time dimension is probably less critical here, but calculations like “corkscrew” would make little sense without it.</p><p>The formula notation, though seemingly straightforward to me, proves challenging for the LLM. This is likely due to insufficient training data of this type.</p><p>Also note that the preceding formula is relatively simple; consider, however, formulas involving SUMIFs, anchors, and multiple time periods. Furthermore, the notation inverts rows and columns (label = row, time dimension = column) and hence row and column anchors. All of this requires a lengthy prompt or system instruction, which must also incorporate additional relevant information (as detailed below). And to provide adequate context, oftentimes we should analyze a formula block rather than a single formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*2vbBzlbBcMPfiL0aoRSj7g.png" /><figcaption><em>Formula block “translation” example — 1st approach</em></figcaption></figure><p>Although the model occasionally identifies errors, it produces an excessive number of false positives and hallucinations. Fine-tuning the model presents a potential solution, however for this particular task, i.e. error checking, it might require some considerable investment in the dataset preparation (more on this below).</p><p><em>Formula “translation” — 2nd approach</em></p><p>As I mentioned previously LLMs are “used to” the normal Excel notation. Therefore, we could try a more straightforward approach. Here is an example for a single formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*NQZdA8t3pzTGsaNBKyzkIQ.png" /><figcaption><em>Single formula “translation” example — 2nd approach</em></figcaption></figure><p>And another one for several calculations (calculation block):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*8eowei3dm1tVxyRqSwYfEw.png" /><figcaption><em>Formula block “translation” example — 2nd approach</em></figcaption></figure><p>As you can see, the model receives some basic information about the layout, as well as calculation inputs and output, i.e. raw formulas with a label and an indication of whether it’s a series or a constant (though the latter is not shown in the example). The formulas are for the first series column only unless there are row-inconsistent formulas, that are also included (note that this should be clearly indicated in the user prompt or system instruction). The “translation” is done automatically for a selected time series range.</p><p>To my surprise the model is able to follow the calculation logic using the above notation even for considerably larger calculation blocks or several blocks (I’ve tried up to 100 rows). And I have not noticed any problems with matching inputs with outputs. Compared to the first approach this method also works better with anchoring, and it is much easier to “explain” notation logic to LLM.</p><p>So, does it work flawlessly? Unfortunately, not, but for other reasons that I explain below.</p><p><strong>Prompt Engineering</strong></p><p>In my experiments I used two types of prompts:</p><p>i. <strong>Zero-Shot </strong>— the model receives only instructions and task.</p><p>ii. <strong>Few-Shot </strong>— in addition to the instructions and task the model receives some examples.</p><p>I won’t go into much detail here. However, I began experimenting with the few-shot approach because the model consistently made the same mistakes, primarily type I errors (false positives), for specific calculation types. Adding examples (positive, negative or both) helped to reduce these errors, but it also increased the type II error rate (false negatives). The model was “concentrating” too heavily on the examples and missed everything else.</p><p>For the task of error checking, I think type II errors are relatively more important. Yes, reading through some repeated false alarms can be annoying, but still better than missing a mistake. Therefore, in my opinion, zero-shot prompting appears to work better, at least for my specific setup.</p><p><strong>Results and Examples</strong></p><p>As I mentioned previously, this is not formal research. Therefore, the examples I provide here are by no means exhaustive.</p><p>Let’s start with examples of the correct model behavior.</p><p><em>True Positive — Labeling Error</em></p><p>Here I just switched the label (Accounts Receivable to Accounts Payable), and as you can see the model correctly spotted the mistake.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*RSOFKxg9ctmCytcyveDL3g.png" /><figcaption>Model response example</figcaption></figure><p>Is this behavior consistent? Not always, as you will see in the following examples, sometimes the model can miss an incorrect label.</p><p><em>True Positive — Formula (Logic) Error</em></p><p>Here the error is harder to detect, and it certainly requires some domain knowledge.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*mX71bmG66hcHaKmuG5X-Jg.png" /><figcaption>Model response example</figcaption></figure><p>As you can see, COGS were used as the basis for the Accrued Expenses Balance calculation instead of the more typical SG&amp;A. While not always incorrect, using SG&amp;A is more customary, and it’s good that the model flags this type of potential error.</p><p>That said, there is a hint here: SG&amp;A Expenses Forecast is mentioned both in the Inputs and the Output. Without this hint, the model often overlooks this potential error.</p><p><em>True Positive — Formula (Anchor) Error</em></p><p>This is a very common mistake: anchoring a row and then copying a block for a similar calculation. As a result, the formula refers to an incorrect variable (Base Office Rent instead of Base Outsource Expenses).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*2jSkHNqRd0CknfLP19OZJA.png" /><figcaption>Model response example</figcaption></figure><p>The model correctly detects the error. And it has done so fairly consistently across different inputs, at least in my experiments.</p><p><em>False Positive</em></p><p>Unfortunately, the error detection results aren’t always this accurate. Here’s an example of a false alarm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*pHc62nExn96KpOpkPntnZw.png" /><figcaption>Model response example</figcaption></figure><p>I am a big fan of formula consistency in financial modeling. So, I use a blank spacer column for the lookback calculations. Unfortunately, this is not the method that most examples on the Internet utilize and it seems that the model has learned that balance calculation typically starts with a value.</p><p>Another example of similar behavior, which I luckily resolved with explicit instruction, involved the use of links. These are formulas that simply reference another cell’s value and are often used to group calculations and improve model’s readability.</p><p>Overall, it seems that LLMs’ “understanding” of a transparent and concise calculation flow often contradicts good modeling standards. I believe this stems from the numerous “bad” examples present in its training data.</p><p>Returning to the previous example, another issue (related to the discussion above) becomes apparent with one more iteration using the same inputs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*RYmC-1yH4Pafmg1GSdqKQw.png" /><figcaption>Model response example</figcaption></figure><p>Now, the model hallucinates, likely because it’s unfamiliar with this type of the Depreciable Basis calculation (see also the examples below), possibly due to its underrepresentation (or absence) in the training data.</p><p><em>False Negative — Labeling Error</em></p><p>As I mentioned previously, the model is not always able to spot the labeling mistakes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*wcRo3v9N_m6wlE9NXCow3A.png" /><figcaption>Model response example</figcaption></figure><p>And based on my experiments the result can vary depending on the context. If you feed in both SG&amp;A and R&amp;D schedules, then the model will likely detect the labeling inconsistency. Overall, using larger context windows, for example an entire schedule or even multiple schedules, often leads to more consistent and concise output. Therefore, ideally, I would perform two passes: first with a larger context window and then block by block.</p><p><em>False Negative — Formula (Logic) Error</em></p><p>And here we go back to the Depreciable Basis calculation. The formula for the basis reduction is now incorrect — the basis is reduced in the same year that the equipment is purchased without taking into account its useful life.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*hXyy7o-GZlF3m1gySH3rDw.png" /><figcaption>Model response example</figcaption></figure><p>The model does not detect the error. Rerunning the analysis with the same inputs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*isLhHk5NDxpZXO3goKBkcA.png" /><figcaption>Model response example</figcaption></figure><p>Now the model correctly suggests that the formula for basis reduction “sums only the current column’s purchase” (item 2 in the answer). However, as discussed above, it is not “familiar” with this type of calculation. And therefore, the proposed correction is completely wrong.</p><p><strong>Results discussion and further development</strong></p><p>So, based on the examples above, can we utilize LLMs to check financial models for errors? My answer is yes, but only if used as a complementary tool.</p><p>When auditing a model, it’s always good to have a second pair of eyes, even if they belong to a first-year analyst (and this analyst is quick and never tired). That said, it’s definitely not a magic bullet that will audit all your models for you from now on. At least not at this stage of development.</p><p>I also think that the quality of this tool can be considerably improved by fine-tuning the model. However, here comes the tricky part — developing a dataset.</p><p>We could likely improve the model’s domain knowledge by tuning it on “good” financial modeling examples (asking it to complete calculations). Such a dataset could be generated more or less easily from the existing models.</p><p>However, I believe that for the best results the dataset should also include error examples (and be pretty exhaustive both in terms of error types and modeling styles) annotated by humans, who are also professionals in financial modeling. And that might require significant time and labor (= money) investment.</p><p>An alternative (or complementary) development path might be to utilize an AI model (not necessarily LLM) to automate stress testing, i.e. to generate test inputs and signal abnormal outputs. Although I am not sure it is viable given the number of outputs that need to be considered, e.g. a whole array of data in financial statements, and variability in financial models’ design (implicit assumptions).</p><p>Finally, a couple of words on context extraction. Clearly, the quality of the context directly influences the quality of the LLM’s responses. As I mentioned previously, model layout variability can present challenges for context extraction. While many of these challenges can likely be addressed algorithmically, we could also explore utilizing an LLM by feeding it a portion of a spreadsheet in raw format. This approach could further automate the process.</p><h3>Conclusions</h3><ul><li>To utilize LLM for error checking we need to provide it with enough context.</li><li>The closer the context format aligns with the LLM’s training data, the better the results.</li><li>Generating high-quality context is not always straightforward due to variability in financial models’ style and quality.</li><li>Given sufficient context, even a general-purpose LLM can serve as a second pair of eyes for error checking, though these eyes are not perfect.</li><li>Fine-tuning could be instrumental in further improving the quality of the model’s responses. However, developing the necessary dataset might require a significant investment.</li></ul><p>In the next part of this article we will explore whether an LLM can help us with generating parts of a financial model. Please stay tuned.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6907e1597c34" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>