Monday, July 27, 2026
HomeArtificial IntelligenceDesigning Talent-Pushed Monetary Evaluation Brokers with Claude, Python, MCP Connectors, and Automated...

Designing Talent-Pushed Monetary Evaluation Brokers with Claude, Python, MCP Connectors, and Automated Deliverables

On this tutorial, we construct a complicated workflow round Anthropic’s financial-services repository and reproduce its skill-driven structure in pure Python. We start by putting in the required libraries, cloning the repository, and programmatically mapping its brokers, vertical plugins, companion integrations, managed-agent cookbooks, and monetary evaluation abilities. We then parse the repository’s SKILL.md information right into a searchable registry and assemble a reusable SkillAgent that injects chosen monetary playbooks into the Anthropic Messages API whereas supporting an iterative tool-use loop for Python calculations and file technology. Utilizing this structure, we execute an artificial discounted money circulation valuation, generate a WACC and terminal-growth sensitivity heatmap, carry out comparable-company evaluation with formatted Excel output, draft a private-equity funding committee memo, and examine a managed-agent deployment specification with out sending a reside deployment request.

import subprocess, sys, os, io, re, json, glob, textwrap, contextlib, pathlib
def sh(cmd):
   print(f"$ {cmd}")
   r = subprocess.run(cmd, shell=True, capture_output=True, textual content=True)
   if r.returncode != 0:
       print(r.stderr[-1500:])
   return r
sh(f"{sys.executable} -m pip set up -q anthropic pandas openpyxl pyyaml matplotlib")
import pandas as pd
import yaml
import matplotlib.pyplot as plt
REPO_URL = "https://github.com/anthropics/financial-services.git"
REPO_DIR = "financial-services"
if not os.path.isdir(REPO_DIR):
   sh(f"git clone --depth 1 {REPO_URL} {REPO_DIR}")
else:
   print("Repo already cloned — skipping.")
def get_api_key():
   strive:
       from google.colab import userdata
       ok = userdata.get("ANTHROPIC_API_KEY")
       if ok:
           return ok
   besides Exception:
       move
   if os.environ.get("ANTHROPIC_API_KEY"):
       return os.environ["ANTHROPIC_API_KEY"]
   from getpass import getpass
   return getpass("Enter your Anthropic API key: ")
os.environ["ANTHROPIC_API_KEY"] = get_api_key()
import anthropic
consumer = anthropic.Anthropic()
MODEL = "claude-sonnet-4-6"
print("SDK prepared. Mannequin:", MODEL)

We set up the required Python libraries, clone Anthropic’s financial-services repository, and put together the Google Colab runtime for execution. We retrieve the Anthropic API key from Colab secrets and techniques, setting variables, or a safe interactive immediate. We then initialize the official Anthropic SDK and choose the Claude mannequin that powers the financial-analysis workflows.

def repo_map(root=REPO_DIR):
   rows = []
   for sort, sample in [
       ("agent",   f"{root}/plugins/agent-plugins/*"),
       ("vertical",f"{root}/plugins/vertical-plugins/*"),
       ("partner", f"{root}/plugins/partner-built/*"),
       ("cookbook",f"{root}/managed-agent-cookbooks/*"),
   ]:
       for p in sorted(glob.glob(sample)):
           if not os.path.isdir(p):
               proceed
           abilities   = glob.glob(f"{p}/**/SKILL.md", recursive=True)
           instructions = glob.glob(f"{p}/instructions/*.md")
           rows.append({"sort": sort, "identify": os.path.basename(p),
                        "abilities": len(abilities), "instructions": len(instructions)})
   return pd.DataFrame(rows)
print("n=== REPO MAP ===")
repo_df = repo_map()
print(repo_df.to_string(index=False))
mcp_files = glob.glob(f"{REPO_DIR}/plugins/**/.mcp.json", recursive=True)
for f in mcp_files[:1]:
   print(f"n=== MCP CONNECTORS ({f}) ===")
   strive:
       cfg = json.load(open(f))
       for identify, srv in cfg.get("mcpServers", cfg).objects():
           print(f"  {identify:<14} -> {srv.get('url', srv)}")
   besides Exception as e:
       print("  (couldn't parse:", e, ")")
FRONTMATTER = re.compile(r"^---s*n(.*?)n---s*n", re.S)
class Talent:
   def __init__(self, path):
       self.path = path
       uncooked = open(path, encoding="utf-8", errors="exchange").learn()
       m = FRONTMATTER.match(uncooked)
       meta = {}
       if m:
           strive:
               meta = yaml.safe_load(m.group(1)) or {}
           besides Exception:
               meta = {}
       self.identify = str(meta.get("identify") or pathlib.Path(path).mum or dad.identify)
       self.description = str(meta.get("description", ""))[:300]
       self.physique = uncooked[m.end():] if m else uncooked
   def __repr__(self):
       return f""
class SkillRegistry:
   def __init__(self, root=REPO_DIR):
       paths  = sorted(glob.glob(f"{root}/plugins/vertical-plugins/**/SKILL.md", recursive=True))
       paths += sorted(glob.glob(f"{root}/plugins/**/SKILL.md", recursive=True))
       self.abilities = {}
       for p in paths:
           s = Talent(p)
           self.abilities.setdefault(s.identify.decrease(), s)
   def discover(self, question):
       q = question.decrease()
       hits = [s for k, s in self.skills.items() if q in k]
       if not hits:
           hits = [s for s in self.skills.values() if q in s.description.lower()]
       return hits
   def get(self, question):
       hits = self.discover(question)
       if not hits:
           increase KeyError(f"No ability matching '{question}'. "
                          f"Out there: {sorted(self.abilities)[:40]}")
       return hits[0]
registry = SkillRegistry()
print(f"nLoaded {len(registry.abilities)} distinctive abilities.")
print("Pattern:", sorted(registry.abilities)[:12], "...")

We examine the repository construction and determine its agent plugins, vertical plugins, companion integrations, managed-agent cookbooks, and accessible instructions. We find MCP configuration information and show the exterior monetary information connectors outlined within the repository. We then parse every SKILL.md file, extract its YAML metadata and methodology, and register each distinctive ability for searchable entry.

os.makedirs("outputs", exist_ok=True)
TOOLS = [
   {
       "name": "run_python",
       "description": ("Execute Python code and return stdout. pandas as pd "
                       "and numpy as np are pre-imported. Use print() to "
                       "return results. State persists across calls."),
       "input_schema": {
           "type": "object",
           "properties": {"code": {"type": "string"}},
           "required": ["code"],
       },
   },
   {
       "identify": "save_file",
       "description": "Save textual content content material to outputs/.",
       "input_schema": {
           "sort": "object",
           "properties": {"filename": {"sort": "string"},
                          "content material":  {"sort": "string"}},
           "required": ["filename", "content"],
       },
   },
]
_PY_NS = {}
def _tool_run_python(code):
   import numpy as np
   _PY_NS.setdefault("pd", pd); _PY_NS.setdefault("np", np)
   buf = io.StringIO()
   strive:
       with contextlib.redirect_stdout(buf):
           exec(code, _PY_NS)
       out = buf.getvalue()
       return out[:6000] if out else "(no stdout — use print())"
   besides Exception as e:
       return f"ERROR: {sort(e).__name__}: {e}"
def _tool_save_file(filename, content material):
   protected = os.path.basename(filename)
   path = os.path.be part of("outputs", protected)
   open(path, "w", encoding="utf-8").write(content material)
   return f"Saved {path} ({len(content material)} chars)"
DISPATCH = {"run_python": lambda i: _tool_run_python(i["code"]),
           "save_file":  lambda i: _tool_save_file(i["filename"], i["content"])}
BASE_SYSTEM = """You're a monetary analyst assistant working with the
ability playbooks offered beneath (from Anthropic's financial-services repo).
Comply with the ability's methodology, conventions, and output format intently.
Use the run_python device for all numerical work — by no means do arithmetic in
your head. Use save_file for closing deliverables. All work is a DRAFT for
human evaluation; don't current it as funding recommendation."""
class SkillAgent:
   """Minimal copy of Cowork's skill-firing: chosen abilities are
   concatenated into the system immediate; the agent then runs a regular
   tool-use loop in opposition to the Messages API till the mannequin stops."""
   def __init__(self, skill_queries, max_skill_chars=12000, verbose=True):
       self.abilities = [registry.get(q) for q in skill_queries]
       blocks = []
       for s in self.abilities:
           blocks.append(f"nn===== SKILL: {s.identify} =====n"
                         f"{s.description}n{s.physique[:max_skill_chars]}")
       self.system = BASE_SYSTEM + "".be part of(blocks)
       self.verbose = verbose
   def run(self, immediate, max_turns=12):
       messages = [{"role": "user", "content": prompt}]
       for flip in vary(max_turns):
           resp = consumer.messages.create(
               mannequin=MODEL, max_tokens=8000,
               system=self.system, instruments=TOOLS, messages=messages)
           messages.append({"function": "assistant", "content material": resp.content material})
           if resp.stop_reason != "tool_use":
               closing = "".be part of(b.textual content for b in resp.content material
                               if b.sort == "textual content")
               return closing, messages
           outcomes = []
           for block in resp.content material:
               if block.sort == "tool_use":
                   if self.verbose:
                       print(f"  [turn {turn}] device: {block.identify}")
                   out = DISPATCH[block.name](block.enter)
                   outcomes.append({"sort": "tool_result",
                                   "tool_use_id": block.id,
                                   "content material": str(out)})
           messages.append({"function": "consumer", "content material": outcomes})
       return "(hit max_turns)", messages

We outline instruments that enable Claude to execute Python calculations and save generated deliverables contained in the Colab setting. We construct a persistent Python namespace so numerical fashions, tables, and intermediate variables stay accessible throughout a number of agent turns. We then create the SkillAgent class, inject chosen monetary playbooks into its system immediate, and handle the Anthropic Messages API tool-use loop.

SAMPLE_CO = """
Goal: 'Meridian Software program' (artificial). FY2025 actuals, $mm:
Income 850 (grew 18% y/y) | EBITDA margin 27% | D&A 4% of rev
CapEx 5% of rev | NWC change 1% of rev progress | Tax price 24%
Web debt 320 | Diluted shares 92mm
Assumptions: income progress fades 18% -> 6% linearly over 5 yrs,
EBITDA margin expands 100bps whole, WACC 9.5%, terminal progress 2.5%.
"""
print("n" + "="*76 + "nDEMO A — DCF (dcf-model ability)n" + "="*76)
strive:
   dcf_agent = SkillAgent(["dcf"])
   dcf_answer, _ = dcf_agent.run(
       "Run a 5-year unlevered DCF per the ability playbook on this firm:n"
       + SAMPLE_CO +
       "nCompute enterprise worth, fairness worth, and implied share value "
       "with run_python. Then print a WACC (8.5%-10.5%, 50bp steps) x "
       "terminal progress (1.5%-3.5%, 50bp steps) sensitivity grid of implied "
       "share value as a JSON object below the marker SENS_JSON:, and provides "
       "a concise abstract.")
   print("n--- DCF RESULT ---n", dcf_answer[:3000])
   m = re.search(r"SENS_JSON:s*({.*})", dcf_answer, re.S)
   if m:
       grid = json.masses(m.group(1))
       sens = pd.DataFrame(grid)
       sens = sens.apply(pd.to_numeric, errors="coerce")
       fig, ax = plt.subplots(figsize=(7, 4))
       im = ax.imshow(sens.values, cmap="RdYlGn", side="auto")
       ax.set_xticks(vary(len(sens.columns)), sens.columns)
       ax.set_yticks(vary(len(sens.index)), sens.index)
       ax.set_xlabel("Terminal progress"); ax.set_ylabel("WACC")
       ax.set_title("Implied share value sensitivity ($)")
       for i in vary(sens.form[0]):
           for j in vary(sens.form[1]):
               v = sens.values[i, j]
               if pd.notna(v):
                   ax.textual content(j, i, f"{v:,.0f}", ha="heart", va="heart",
                           fontsize=8)
       fig.colorbar(im); plt.tight_layout(); plt.present()
besides Exception as e:
   print("Demo A skipped:", e)

We offer artificial working assumptions and instruct the DCF ability agent to assemble a five-year unlevered cash-flow valuation. We use the Python execution device to calculate enterprise worth, fairness worth, implied share value, and a two-dimensional sensitivity matrix. We then extract the structured sensitivity outcomes and visualize the connection between WACC, terminal progress, and implied valuation by means of a heatmap.

PEERS = """
Artificial peer set ($mm besides per-share):
Ticker  Worth  Shares  NetDebt  Rev_NTM  EBITDA_NTM  EPS_NTM
ALFA    64.2   210     450      2900     820         3.10
BRVO    28.7   540     -120     4100     980         1.45
CHRL    112.5  95      760      1850     610         5.60
DLTA    41.9   330     210      2600     700         2.05
"""
print("n" + "="*76 + "nDEMO B — COMPS (comps-analysis ability) -> Exceln" + "="*76)
strive:
   comps_agent = SkillAgent(["comps"])
   comps_answer, _ = comps_agent.run(
       "Per the comps ability, compute EV, EV/Income, EV/EBITDA and P/E "
       "(all NTM) for these friends with run_python:n" + PEERS +
       "nThen print the complete comps desk plus min/twenty fifth/median/seventy fifth/max "
       "abstract stats as JSON below the marker COMPS_JSON: with keys "
       "'desk' (record of row dicts) and 'stats' (dict of dicts).")
   print("n--- COMPS NARRATIVE ---n", comps_answer[:1500])
   m = re.search(r"COMPS_JSON:s*({.*})", comps_answer, re.S)
   if m:
       payload = json.masses(m.group(1))
       desk = pd.DataFrame(payload["table"])
       stats = pd.DataFrame(payload["stats"])
       xlsx = "outputs/comps_analysis.xlsx"
       with pd.ExcelWriter(xlsx, engine="openpyxl") as xl:
           desk.to_excel(xl, sheet_name="Comps", index=False)
           stats.to_excel(xl, sheet_name="Abstract Stats")
       from openpyxl import load_workbook
       from openpyxl.types import Font, PatternFill
       wb = load_workbook(xlsx)
       for ws in wb.worksheets:
           for cell in ws[1]:
               cell.font = Font(daring=True, coloration="FFFFFF")
               cell.fill = PatternFill("strong", start_color="1F4E79")
           for col in ws.columns:
               w = max(len(str(c.worth)) for c in col if c.worth is just not None)
               ws.column_dimensions[col[0].column_letter].width = w + 3
       wb.save(xlsx)
       print("Wrote", xlsx)
       print(desk.to_string(index=False))
besides Exception as e:
   print("Demo B skipped:", e)

We provide an artificial peer set and calculate enterprise worth, EV-to-revenue, EV-to-EBITDA, and price-to-earnings multiples. We convert the agent’s structured JSON response into detailed comparable-company and summary-statistics DataFrames. We then export the evaluation to a multi-sheet Excel workbook and apply skilled header formatting and automated column sizing.

print("n" + "="*76 + "nDEMO C — IC MEMO (ic-memo ability)n" + "="*76)
strive:
   ic_agent = SkillAgent(["ic-memo"])
   ic_answer, _ = ic_agent.run(
       "Draft a first-round IC memo per the ability for a hypothetical "
       "buyout of Meridian Software program (see information beneath). Base the valuation "
       "framing on ~11x EV/EBITDA entry, 45% leverage, 5-yr maintain. Use "
       "run_python for any fast math (e.g., tough MOIC/IRR math) and "
       "save the memo with save_file as ic_memo_meridian.md.n" + SAMPLE_CO)
   print("n--- IC MEMO (first 1500 chars of reply) ---n", ic_answer[:1500])
   memo_path = "outputs/ic_memo_meridian.md"
   if os.path.exists(memo_path):
       print(f"nMemo saved -> {memo_path} "
             f"({os.path.getsize(memo_path)} bytes)")
besides Exception as e:
   print("Demo C skipped:", e)
print("n" + "="*76 + "nPART 7 — MANAGED AGENT COOKBOOK (dry run)n" + "="*76)
yamls = sorted(glob.glob(f"{REPO_DIR}/managed-agent-cookbooks/*/agent.yaml")) 
     + sorted(glob.glob(f"{REPO_DIR}/managed-agent-cookbooks/*/*.yaml"))
if yamls:
   path = yamls[0]
   print("Inspecting:", path)
   strive:
       spec = yaml.safe_load(open(path))
       print(json.dumps(spec, indent=2, default=str)[:2500])
       print("nDeploy circulation: resolve file refs -> add abilities -> create "
             "leaf-worker subagents -> POST orchestrator to /v1/brokers "
             "(see scripts/orchestrate.py for the handoff_request occasion loop).")
   besides Exception as e:
       print("Couldn't parse yaml:", e)
else:
   print("No cookbook yaml discovered on this department — see "
         "managed-agent-cookbooks/ READMEs on GitHub.")
print("n" + "="*76)
print("DONE. Artifacts in ./outputs/:", os.listdir("outputs"))
print("""
The place to go subsequent:
* Swap SAMPLE_CO / PEERS for actual information through the repo's MCP connectors
  (Daloopa, FactSet, S&P, Morningstar, PitchBook...) — subscriptions apply.
* Load different abilities: SkillAgent(["lbo"]), ["merger"], ["earnings"],
  ["rebalance"], ["tlh"], ["kyc"] ... — see `sorted(registry.abilities)`.
* Stack abilities: SkillAgent(["comps", "dcf"]) for a football-field workflow.
* For manufacturing, set up as a Cowork plugin or deploy through Managed Brokers
  as an alternative of this Colab loop — similar abilities, ruled runtime.
All outputs are drafts for certified human evaluation — not funding recommendation.
""")

We apply the investment-committee memo ability to a hypothetical software program buyout and calculate supporting return metrics with Python. We save the ensuing memo as a Markdown deliverable and confirm that the generated file exists within the output listing. We then examine a managed-agent cookbook, show the deployment specification, and conclude by reviewing the generated artifacts and doable manufacturing extensions.

By finishing this tutorial, we implement a sensible Colab-based approximation of Anthropic’s financial-services ability and agent framework whereas preserving the repository’s methodology-driven method to monetary evaluation. We mix structured ability discovery, dynamic system-prompt building, persistent Python execution, API-based device orchestration, and automatic deliverable technology in a single reusable workflow. We additionally reveal how the identical agent structure helps a number of finance use instances, together with DCF valuation, trading-comps evaluation, sensitivity testing, Excel reporting, and funding committee memo preparation. From right here, we prolong the system by loading extra abilities, combining a number of valuation playbooks, connecting to licensed monetary information suppliers through MCP integrations, and changing the tutorial sandbox with a ruled manufacturing runtime in Claude Code, Cowork, or Managed Brokers.


Try the Full Code right hereAdditionally, be happy to observe us on Twitter and don’t neglect to hitch our 150k+ML SubReddit and Subscribe to our Publication. Wait! are you on telegram? now you’ll be able to be part of us on telegram as nicely.

Have to companion with us for selling your GitHub Repo OR Hugging Face Web page OR Product Launch OR Webinar and so forth.? Join with us


Sana Hassan, a consulting intern at Marktechpost and dual-degree pupil at IIT Madras, is obsessed with making use of expertise and AI to handle real-world challenges. With a eager curiosity in fixing sensible issues, he brings a contemporary perspective to the intersection of AI and real-life options.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments