Spaces:
Sleeping
Sleeping
update some new tools
Browse filesFiles changed (3)
- app.py+3-1
- prompts.py+104-71
- tools.py+303-228
97 unmodified lines98991001011021032 unmodified lines10610710810911011111297 unmodified lines| Build a low-risk portfolio | "Create a minimum variance portfolio with Microsoft, Google, and Amazon" || Maximize return for the risk taken | "Give me the best risk-return portfolio using Apple, Nvidia, and Meta" || Reduce downside risk compared to the S&P500 | "Build a portfolio that minimizes losses relative to the S&P500 using these 5 stocks" || Check Mexican CETES rates | "What's the 28-day CETES rate today?" || Know monthly inflation in Mexico | "What was Mexico's monthly inflation last month?" || Know annual inflation in Mexico | "What's the current annual inflation rate in Mexico?" |2 unmodified lines| Know Mexico's central bank interest rate | "What is Mexico's target interest rate right now?" || Get cross-currency exchange rates | "What's the current exchange rate for EUR/USD?" || Analyze news sentiment for a stock | "What is the market sentiment around Tesla right now?" |""")97 unmodified lines98991001011021031042 unmodified lines10710810911011111211311497 unmodified lines| Build a low-risk portfolio | "Create a minimum variance portfolio with Microsoft, Google, and Amazon" || Maximize return for the risk taken | "Give me the best risk-return portfolio using Apple, Nvidia, and Meta" || Reduce downside risk compared to the S&P500 | "Build a portfolio that minimizes losses relative to the S&P500 using these 5 stocks" || Find economic data from the US (FRED) | "What was the unemployment rate in December 2024?" || Check Mexican CETES rates | "What's the 28-day CETES rate today?" || Know monthly inflation in Mexico | "What was Mexico's monthly inflation last month?" || Know annual inflation in Mexico | "What's the current annual inflation rate in Mexico?" |2 unmodified lines| Know Mexico's central bank interest rate | "What is Mexico's target interest rate right now?" || Get cross-currency exchange rates | "What's the current exchange rate for EUR/USD?" || Analyze news sentiment for a stock | "What is the market sentiment around Tesla right now?" || Calculate the impact of inflation | "how much would inflation in mexico affect my 1000 pesos over 5 months?" || Make a fundamental analysis of a stock | "What is the fundamental analysis of Microsoft?" |""")
1235 unmodified lines91011121314151664 unmodified lines8182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114249 unmodified lines19219319419519619730 unmodified lines22822923023123223323417 unmodified lines2522532542552562572582592602612622632647 unmodified lines27227327427527627727827928028116 unmodified lines298299300301DEFAULT_SYSTEM_PROMPT = """You are a financial data agent. You answer questions about companies and macroeconomic indicators using ONLY the results from your available tools. Never invent, estimate, or recall data from memory.STRICT RULES:5 unmodified linesDATA SOURCE ROUTING — mandatory, no exceptions:- CETES, TIE, UDIs, tasa objetivo, inflacion Mexico, or ANY Mexican indicator → use the specific Banxico tool.Available Banxico tools: get_cetes_28, get_cetes_91, get_cetes_182, get_cetes_364, get_cetes_728,get_tie_28, get_tie_91, get_tie_182, get_target_interest_rate_mexico,get_mensual_inflation_mexico, get_inflation_mexico, get_udis.- Cross rates(e.g. EUR/USD, GBP/JPY, USD/CAD) → use get_exchange_rate(base, quote, date). (date is optional)64 unmodified linesAnnualized volatility: <volatility>"Example call: ACTION: min_target_semivariance_portfolio(AAPL, MSFT, GOOGL)### get_cetes_28(date)Description: Returns the CETES 28-day yield from Banxico.If no date is provided, returns the most recent observation.Pass a date in YYYY-MM-DD format to get the nearest available observation.Returns: "The CETES 28-day rate (<label>) is <value>% as of <DD/MM/YYYY>."Example calls: ACTION: get_cetes_28()ACTION: get_cetes_28(2024-01-15)### get_cetes_91(date)Description: Returns the CETES 91-day yield from Banxico.If no date is provided, returns the most recent observation.Returns: "The CETES 91-day rate (<label>) is <value>% as of <DD/MM/YYYY>."Example calls: ACTION: get_cetes_91()ACTION: get_cetes_91(2024-01-15)### get_cetes_182(date)Description: Returns the CETES 182-day yield from Banxico.If no date is provided, returns the most recent observation.Returns: "The CETES 182-day rate (<label>) is <value>% as of <DD/MM/YYYY>."Example calls: ACTION: get_cetes_182()ACTION: get_cetes_182(2024-01-15)### get_cetes_364(date)Description: Returns the CETES 364-day yield from Banxico.If no date is provided, returns the most recent observation.Returns: "The CETES 364-day rate (<label>) is <value>% as of <DD/MM/YYYY>."Example calls: ACTION: get_cetes_364()ACTION: get_cetes_364(2024-01-15)### get_cetes_728(date)Description: Returns the CETES 728-day yield from Banxico.If no date is provided, returns the most recent observation.Returns: "The CETES 728-day rate (<label>) is <value>% as of <DD/MM/YYYY>."Example calls: ACTION: get_cetes_728()ACTION: get_cetes_728(2024-01-15)### get_tie_28(date)Description: Returns the TIE (Tasa de Interés de Equilibrio) 28-day rate from Banxico.If no date is provided, returns the most recent observation.Returns: "The TIE 28-day rate (<label>) is <value>% as of <DD/MM/YYYY>."Example calls: ACTION: get_tie_28()ACTION: get_tie_28(2024-01-15)### get_tie_91(date)Description: Returns the TIE 91-day rate from Banxico.If no date is provided, returns the most recent observation.Returns: "The TIE 91-day rate (<label>) is <value>% as of <DD/MM/YYYY>."Example calls: ACTION: get_tie_91()ACTION: get_tie_91(2024-01-15)### get_tie_182(date)Description: Returns the TIE 182-day rate from Banxico.If no date is provided, returns the most recent observation.Returns: "The TIE 182-day rate (<label>) is <value>% as of <DD/MM/YYYY>."Example calls: ACTION: get_tie_182()ACTION: get_tie_182(2024-01-15)### get_target_interest_rate_mexico(date)Description: Returns the Banxico target interest rate (tasa objetivo).49 unmodified linesACTION: get_news_sentiment(TSLA)ACTION: get_news_sentiment(BIMBOA.MX)### respond_to_greeting()Description: Responds to user greetings with a friendly introduction about the agent.Use this when the user greets you or asks a general question like "Hi", "Hello", "What are you?".30 unmodified linesACTION: get_company_profile(GMEXICOB.MX)After tool result: FINAL: Grupo México operates in the Basic Materials sector and Copper industry. The company is one of the largest mining groups in Latin America, focused on copper, silver, and zinc extraction.ACTION: get_company_profile(NVDA)After tool result: FINAL: Nvidia operates in the Technology sector and Semiconductors industry. The company designs GPUs and accelerated computing platforms for gaming, data centers, and artificial intelligence.17 unmodified linesACTION: get_news_sentiment(AAPL)After tool result: FINAL: Sentiment analysis for Apple Inc. (AAPL) across 10 recent articles: Composite score: +0.1823 (POSITIVE). Top influencing headlines: [POSITIVE 88%] Apple reports record services revenue (CNBC) --- ...User: What is the most recent CETES 28-day rate?ACTION: get_cetes_28()After tool result: FINAL: The CETES 28-day rate (most recent) is 8.9900% as of 27/03/2025.User: What was the CETES 91-day rate in January 2024?ACTION: get_cetes_91(2024-01-15)After tool result: FINAL: The CETES 91-day rate nearest to January 15, 2024 was 11.3100% as of 11/01/2024.User: What is the current Banxico target rate?ACTION: get_target_interest_rate_mexico()7 unmodified linesACTION: get_mensual_inflation_mexico(2023-06-15)After tool result: FINAL: The monthly inflation rate in Mexico nearest to June 15, 2023 was 0.2200% as of 15/06/2023.User: What is the TIE 182-day rate?ACTION: get_tie_182()After tool result: FINAL: The TIE 182-day rate (most recent) is 9.4500% as of 15/04/2025.User: What is the current UDI value?ACTION: get_udis()After tool result: FINAL: The value of UDIs in Mexico (most recent) is 8.2341 MXN as of 30/04/2025.16 unmodified linesACTION: min_variance_portfolio("AAPL, MSFT, GOOGL") <- never pack tickers into one string argumentFINAL: Apple's price is around $210 <- invented value, no tool was calledFINAL: The CETES rate is roughly 9% <- recalled from memory, no tool was called"""123456789101112131415161718195 unmodified lines252627282930313264 unmodified lines97989910010110210310410510610710810911011111211311411511611711811912012112212312449 unmodified lines17417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821930 unmodified lines25025125225325425517 unmodified lines2732742752762772782792802812822832842852862872882892902912922932942952962972982993003017 unmodified lines30931031131231331416 unmodified lines331332333334"""Prompt templates — update the system prompt here without touching agent logic.HOW TO ADD A NEW TOOL TO THE PROMPT-------------------------------------1. Add a new entry under AVAILABLE TOOLS following this block format:### tool_name(arg1, arg2, ...)Description: What the tool does and when to use it.Returns: What the tool output looks like.Example call: ACTION: tool_name(ARG1)2. Add one correct and one incorrect example under EXAMPLES if useful.3. That's it — no other file needs to change."""DEFAULT_SYSTEM_PROMPT = """You are a financial data agent. You answer questions about companies and macroeconomic indicators using ONLY the results from your available tools. Never invent, estimate, or recall data from memory.STRICT RULES:5 unmodified linesDATA SOURCE ROUTING — mandatory, no exceptions:- CETES, TIE, UDIs, tasa objetivo, inflacion Mexico, or ANY Mexican indicator → use the specific Banxico tool.Available Banxico tools: get_cetes_rate,get_tiie_rate, get_target_interest_rate_mexico,get_mensual_inflation_mexico, get_inflation_mexico, get_udis.- Cross rates(e.g. EUR/USD, GBP/JPY, USD/CAD) → use get_exchange_rate(base, quote, date). (date is optional)64 unmodified linesAnnualized volatility: <volatility>"Example call: ACTION: min_target_semivariance_portfolio(AAPL, MSFT, GOOGL)### get_cetes_rate(term_days, date)Description: Returns the CETES interest rate for a given term from Banxico.term_days must be one of: 28, 91, 182, 364, 728.If no date is provided, returns the most recent available rate.Pass a date in YYYY-MM-DD format to get the nearest available rate.Returns: "The CETES <term>-day rate (<label>) is <value>% as of <YYYY-MM-DD>."Example calls: ACTION: get_cetes_rate(28)ACTION: get_cetes_rate(91, 2024-06-01)ACTION: get_cetes_rate(182)ACTION: get_cetes_rate(364, 2023-01-15)ACTION: get_cetes_rate(728)### get_tiie_rate(term_days, date)Description: Returns the TIIE (Tasa de Interés Interbancaria de Equilibrio) ratefor a given term from Banxico.term_days must be one of: 28, 91, 182.If no date is provided, returns the most recent available rate.Pass a date in YYYY-MM-DD format to get the nearest available rate.Returns: "The TIIE <term>-day rate (<label>) is <value>% as of <YYYY-MM-DD>."Example calls: ACTION: get_tiie_rate(28)ACTION: get_tiie_rate(91, 2024-06-01)ACTION: get_tiie_rate(182, 2023-01-15)### get_target_interest_rate_mexico(date)Description: Returns the Banxico target interest rate (tasa objetivo).49 unmodified linesACTION: get_news_sentiment(TSLA)ACTION: get_news_sentiment(BIMBOA.MX)### get_fundamental_analysis(ticker)Description: Performs a quantitative fundamental analysis scorecard for a stock.Evaluates 15 metrics across four categories:- Valuation (P/E, P/B, EV/EBITDA, PEG) — sector-adjusted thresholds- Profitability (ROE, ROA, Gross margin, Net margin)- Financial Health (D/E ratio, Current ratio, Interest coverage, FCF yield)- Growth (Revenue growth, Earnings growth, Dividend yield)Each metric is scored 0 (weak), 1 (neutral/unavailable), or 2 (strong).Composite score out of 30: >=70% → BUY | 40-69% → HOLD | <40% → SELL.Apply the same exchange suffix rules as get_price_on_date.Use this when the user asks for a fundamental analysis, valuation, financialhealth overview, or a buy/sell/hold recommendation for a company.Returns: Single-paragraph scorecard with per-metric values and scores, category subtotals,composite score, percentage, and a BUY/HOLD/SELL recommendation with rationale.Example calls: ACTION: get_fundamental_analysis(AAPL)ACTION: get_fundamental_analysis(NVDA)ACTION: get_fundamental_analysis(BIMBOA.MX)### calculate_inflation_impact(amount, months, annual_inflation_rate)Description: Calculates the loss of purchasing power of a given amount of moneydue to compound inflation over a number of months.amount is the initial sum in pesos (or any currency).months is the number of months to project forward.annual_inflation_rate is the yearly inflation rate as a percentage (e.g. 4.5 for 4.5%).Always call get_inflation_rate() first to obtain the current rate, then passits result as annual_inflation_rate into this function.Returns: A sentence describing the effective value after inflation and the total purchasing power loss.Example calls: ACTION: calculate_inflation_impact(1000, 5, 4.5)ACTION: calculate_inflation_impact(5000, 12, 3.8)ACTION: calculate_inflation_impact(250, 3, 5.1)### multiply(a, b)Description: Multiplies two numbers together and returns the result.Use this whenever a multiplication is needed mid-reasoninginstead of computing it yourself.Returns: "The result of <a> × <b> is <result>."Example calls: ACTION: multiply(12, 8)ACTION: multiply(1053.5, 0.042)ACTION: multiply(3, 1000000)### respond_to_greeting()Description: Responds to user greetings with a friendly introduction about the agent.Use this when the user greets you or asks a general question like "Hi", "Hello", "What are you?".30 unmodified linesACTION: get_company_profile(GMEXICOB.MX)After tool result: FINAL: Grupo México operates in the Basic Materials sector and Copper industry. The company is one of the largest mining groups in Latin America, focused on copper, silver, and zinc extraction.ACTION: get_company_profile(NVDA)After tool result: FINAL: Nvidia operates in the Technology sector and Semiconductors industry. The company designs GPUs and accelerated computing platforms for gaming, data centers, and artificial intelligence.17 unmodified linesACTION: get_news_sentiment(AAPL)After tool result: FINAL: Sentiment analysis for Apple Inc. (AAPL) across 10 recent articles: Composite score: +0.1823 (POSITIVE). Top influencing headlines: [POSITIVE 88%] Apple reports record services revenue (CNBC) --- ...User: Can you do a fundamental analysis of Apple?ACTION: get_fundamental_analysis(AAPL)After tool result: FINAL: <full scorecard output from tool>User: Should I buy or sell Nvidia based on its fundamentals?ACTION: get_fundamental_analysis(NVDA)After tool result: FINAL: <full scorecard output from tool>User: Give me a fundamental valuation of Grupo Bimbo.ACTION: get_fundamental_analysis(BIMBOA.MX)After tool result: FINAL: <full scorecard output from tool>User: Is Tesla a good investment right now?ACTION: get_fundamental_analysis(TSLA)After tool result: FINAL: <full scorecard output from tool>User: What is the 28-day CETES rate?ACTION: get_cetes_rate(28)After tool result: FINAL: The CETES 28-day rate (CETES28D) is 9.0000% as of 20/03/2025.User: What is the current tiee rate for 91 days as of 20/03/2025?ACTION: get_tiie_rate(91, 2025-03-20)After tool result: FINAL: The TIIE 91-day rate (TIIE91D) is 9.5000% as of 20/03/2025.User: What is the current Banxico target rate?ACTION: get_target_interest_rate_mexico()7 unmodified linesACTION: get_mensual_inflation_mexico(2023-06-15)After tool result: FINAL: The monthly inflation rate in Mexico nearest to June 15, 2023 was 0.2200% as of 15/06/2023.User: What is the current UDI value?ACTION: get_udis()After tool result: FINAL: The value of UDIs in Mexico (most recent) is 8.2341 MXN as of 30/04/2025.16 unmodified linesACTION: min_variance_portfolio("AAPL, MSFT, GOOGL") <- never pack tickers into one string argumentFINAL: Apple's price is around $210 <- invented value, no tool was calledFINAL: The CETES rate is roughly 9% <- recalled from memory, no tool was called"""
12 unmodified lines1314151617181939 unmodified lines5960616263646566676869707172737475767778798081828376 unmodified lines1601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732747 unmodified lines28228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933022 unmodified lines35335435535635735835936036136236336426 unmodified lines39139239339439539639726 unmodified lines4244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045057 unmodified lines51351451551651751851952052152252352452552652752827 unmodified lines55655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859927 unmodified lines6276286296306316322 unmodified lines63563663763863964064117 unmodified lines65966066166266366418 unmodified lines68368468568668768840 unmodified lines7297307317327337342 unmodified lines73773873912 unmodified linesimport torch.nn.functional as Fimport osBANXICO_TOKEN = os.getenv("BANXICO_TOKEN")HF_LOGIN_KEY = os.getenv("HF_LOGIN_KEY")if HF_LOGIN_KEY:39 unmodified lines@tool("get_price_on_date")def get_price_on_date(ticker, date=None):t = yf.Ticker(ticker)use_default_date = date is Noneif date is None:date = datetime.date.today()else:date = datetime.datetime.strptime(date, "%Y-%m-%d").date()data = pd.DataFrame(t.history(start=date - datetime.timedelta(days=5), end=date + datetime.timedelta(days=5))['Close'])if data.empty:return f"No price data available for {t.ticker} around {date}."data['Date'] = data.index.datedata['DateDiff'] = np.abs(data['Date'] - date)nearest_row = data.loc[data['DateDiff'].idxmin()]price = nearest_row['Close']actual_date = nearest_row['Date']official_name = t.info['longName']if use_default_date:return f"The last price of {official_name} ({t.ticker}) is ${price:.2f} as of {actual_date}."else:76 unmodified linesf"Expected annual return: {(returns.mean() @ result.x * 252):.2%}\n"f"Annualized volatility: {(np.sqrt(result.x.T @ cov_matrix @ result.x) * np.sqrt(252)):.2%}")@tool("get_cetes_28")def get_cetes_28(date: str | None = None) -> str:URL = "https://www.banxico.org.mx/SieAPIRest/service/v1/series/SF43936/datos"headers = {"Bmx-Token": BANXICO_TOKEN,"Content-Type": "application/json",}try:response = requests.get(URL, headers=headers)response.raise_for_status()obs_list = response.json()["bmx"]["series"][0]["datos"]if date is None:obs = obs_list[-1]else:target = datetime.datetime.strptime(date, "%Y-%m-%d")obs = min(obs_list,key=lambda o: abs(datetime.datetime.strptime(o["fecha"], "%d/%m/%Y") - target),)fecha = obs["fecha"]fecha = datetime.datetime.strptime(fecha, "%d/%m/%Y").strftime("%Y-%m-%d")value = float(obs["dato"])label = f"nearest to {date}" if date else "most recent"return f"The CETES 28-day rate ({label}) is {value:.4f}% as of {fecha}."except ValueError:return f"Invalid date format '{date}'. Please use YYYY-MM-DD (e.g. 2024-01-15)."except Exception as exc:return f"Error fetching CETES 28-day rate: {exc}"@tool("get_cetes_91")def get_cetes_91(date: str | None = None) -> str:URL = "https://www.banxico.org.mx/SieAPIRest/service/v1/series/SF43939/datos"headers = {"Bmx-Token": BANXICO_TOKEN,"Content-Type": "application/json",}try:response = requests.get(URL, headers=headers)response.raise_for_status()obs_list = response.json()["bmx"]["series"][0]["datos"]if date is None:obs = obs_list[-1]else:target = datetime.datetime.strptime(date, "%Y-%m-%d")obs = min(obs_list,key=lambda o: abs(datetime.datetime.strptime(o["fecha"], "%d/%m/%Y") - target),)fecha = obs["fecha"]fecha = datetime.datetime.strptime(fecha, "%d/%m/%Y").strftime("%Y-%m-%d")value = float(obs["dato"])label = f"nearest to {date}" if date else "most recent"return f"The CETES 91-day rate ({label}) is {value:.4f}% as of {fecha}."except ValueError:return f"Invalid date format '{date}'. Please use YYYY-MM-DD (e.g. 2024-01-15)."except Exception as exc:return f"Error fetching CETES 91-day rate: {exc}"@tool("get_cetes_182")def get_cetes_182(date: str | None = None) -> str:URL = "https://www.banxico.org.mx/SieAPIRest/service/v1/series/SF43942/datos"headers = {"Bmx-Token": BANXICO_TOKEN,"Content-Type": "application/json",}try:response = requests.get(URL, headers=headers)response.raise_for_status()obs_list = response.json()["bmx"]["series"][0]["datos"]if date is None:obs = obs_list[-1]else:target = datetime.datetime.strptime(date, "%Y-%m-%d")obs = min(obs_list,key=lambda o: abs(datetime.datetime.strptime(o["fecha"], "%d/%m/%Y") - target),)fecha = obs["fecha"]fecha = datetime.datetime.strptime(fecha, "%d/%m/%Y").strftime("%Y-%m-%d")value = float(obs["dato"])label = f"nearest to {date}" if date else "most recent"return f"The CETES 182-day rate ({label}) is {value:.4f}% as of {fecha}."except ValueError:return f"Invalid date format '{date}'. Please use YYYY-MM-DD (e.g. 2024-01-15)."except Exception as exc:return f"Error fetching CETES 182-day rate: {exc}"@tool("get_cetes_364")def get_cetes_364(date: str | None = None) -> str:URL = "https://www.banxico.org.mx/SieAPIRest/service/v1/series/SF43945/datos"headers = {"Bmx-Token": BANXICO_TOKEN,"Content-Type": "application/json",}try:response = requests.get(URL, headers=headers)response.raise_for_status()obs_list = response.json()["bmx"]["series"][0]["datos"]7 unmodified lineskey=lambda o: abs(datetime.datetime.strptime(o["fecha"], "%d/%m/%Y") - target),)fecha = obs["fecha"]fecha = datetime.datetime.strptime(fecha, "%d/%m/%Y").strftime("%Y-%m-%d")value = float(obs["dato"])label = f"nearest to {date}" if date else "most recent"return f"The CETES 364-day rate ({label}) is {value:.4f}% as of {fecha}."except ValueError:return f"Invalid date format '{date}'. Please use YYYY-MM-DD (e.g. 2024-01-15)."except Exception as exc:return f"Error fetching CETES 364-day rate: {exc}"@tool("get_cetes_728")def get_cetes_728(date: str | None = None) -> str:URL = "https://www.banxico.org.mx/SieAPIRest/service/v1/series/SF349785/datos"headers = {"Bmx-Token": BANXICO_TOKEN,"Content-Type": "application/json",}try:response = requests.get(URL, headers=headers)response.raise_for_status()obs_list = response.json()["bmx"]["series"][0]["datos"]if date is None:obs = obs_list[-1]else:target = datetime.datetime.strptime(date, "%Y-%m-%d")obs = min(obs_list,key=lambda o: abs(datetime.datetime.strptime(o["fecha"], "%d/%m/%Y") - target),)fecha = obs["fecha"]fecha = datetime.datetime.strptime(fecha, "%d/%m/%Y").strftime("%Y-%m-%d")value = float(obs["dato"])label = f"nearest to {date}" if date else "most recent"return f"The CETES 728-day rate ({label}) is {value:.4f}% as of {fecha}."except ValueError:return f"Invalid date format '{date}'. Please use YYYY-MM-DD (e.g. 2024-01-15)."except Exception as exc:return f"Error fetching CETES 728-day rate: {exc}"@tool("get_mensual_inflation_mexico")def get_mensual_inflation_mexico(date: str | None = None) -> str:22 unmodified linesvalue = float(obs["dato"])label = f"nearest to {date}" if date else "most recent"return f"The monthly inflation rate in Mexico ({label}) is {value:.4f}% as of {fecha}."except ValueError:return f"Invalid date format '{date}'. Please use YYYY-MM-DD (e.g. 2024-01-15)."except Exception as exc:return f"Error fetching monthly inflation rate in Mexico: {exc}"@tool("get_inflation_mexico")def get_inflation_mexico(date: str | None = None) -> str:URL = "https://www.banxico.org.mx/SieAPIRest/service/v1/series/SP30577/datos"26 unmodified linesreturn f"Invalid date format '{date}'. Please use YYYY-MM-DD (e.g. 2024-01-15)."except Exception as exc:return f"Error fetching annual inflation rate in Mexico: {exc}"@tool("get_udis")def get_udis(date: str | None = None) -> str:URL = "https://www.banxico.org.mx/SieAPIRest/service/v1/series/SP68257/datos"26 unmodified linesreturn f"Invalid date format '{date}'. Please use YYYY-MM-DD (e.g. 2024-01-15)."except Exception as exc:return f"Error fetching UDIs value in Mexico: {exc}"@tool("get_tie_28")def get_tie_28(date: str | None = None) -> str:URL = "https://www.banxico.org.mx/SieAPIRest/service/v1/series/SF43783/datos"headers = {"Bmx-Token": BANXICO_TOKEN,"Content-Type": "application/json",}try:response = requests.get(URL, headers=headers)response.raise_for_status()obs_list = response.json()["bmx"]["series"][0]["datos"]if date is None:obs = obs_list[-1]else:target = datetime.datetime.strptime(date, "%Y-%m-%d")obs = min(obs_list,key=lambda o: abs(datetime.datetime.strptime(o["fecha"], "%d/%m/%Y") - target),)fecha = obs["fecha"]fecha = datetime.datetime.strptime(fecha, "%d/%m/%Y").strftime("%Y-%m-%d")value = float(obs["dato"])label = f"nearest to {date}" if date else "most recent"return f"The TIE 28-day rate ({label}) is {value:.4f}% as of {fecha}."except ValueError:return f"Invalid date format '{date}'. Please use YYYY-MM-DD (e.g. 2024-01-15)."except Exception as exc:return f"Error fetching TIE 28-day rate: {exc}"@tool("get_tie_91")def get_tie_91(date: str | None = None) -> str:URL = "https://www.banxico.org.mx/SieAPIRest/service/v1/series/SF43878/datos"headers = {"Bmx-Token": BANXICO_TOKEN,"Content-Type": "application/json",}try:response = requests.get(URL, headers=headers)response.raise_for_status()obs_list = response.json()["bmx"]["series"][0]["datos"]if date is None:obs = obs_list[-1]else:target = datetime.datetime.strptime(date, "%Y-%m-%d")obs = min(obs_list,key=lambda o: abs(datetime.datetime.strptime(o["fecha"], "%d/%m/%Y") - target),)fecha = obs["fecha"]fecha = datetime.datetime.strptime(fecha, "%d/%m/%Y").strftime("%Y-%m-%d")value = float(obs["dato"])label = f"nearest to {date}" if date else "most recent"return f"The TIE 91-day rate ({label}) is {value:.4f}% as of {fecha}."except ValueError:return f"Invalid date format '{date}'. Please use YYYY-MM-DD (e.g. 2024-01-15)."except Exception as exc:return f"Error fetching TIE 91-day rate: {exc}"@tool("get_tie_182")def get_tie_182(date: str | None = None) -> str:URL = "https://www.banxico.org.mx/SieAPIRest/service/v1/series/SF111916/datos"headers = {"Bmx-Token": BANXICO_TOKEN,"Content-Type": "application/json",}try:response = requests.get(URL, headers=headers)response.raise_for_status()obs_list = response.json()["bmx"]["series"][0]["datos"]7 unmodified lineskey=lambda o: abs(datetime.datetime.strptime(o["fecha"], "%d/%m/%Y") - target),)fecha = obs["fecha"]fecha = datetime.datetime.strptime(fecha, "%d/%m/%Y").strftime("%Y-%m-%d")value = float(obs["dato"])label = f"nearest to {date}" if date else "most recent"return f"The TIE 182-day rate ({label}) is {value:.4f}% as of {fecha}."except ValueError:return f"Invalid date format '{date}'. Please use YYYY-MM-DD (e.g. 2024-01-15)."except Exception as exc:return f"Error fetching TIE 182-day rate: {exc}"@tool("get_target_interest_rate_mexico")def get_target_interest_rate_mexico(date: str | None = None) -> str:27 unmodified linesreturn f"Invalid date format '{date}'. Please use YYYY-MM-DD (e.g. 2024-01-15)."except Exception as exc:return f"Error fetching target interest rate in Mexico: {exc}"@tool("get_exchange_rate")def get_exchange_rate(base: str, quote: str, date: str | None = None) -> str:base = base.strip().upper()quote = quote.strip().upper()ticker_symbol = f"{base}{quote}=X"try:if date is None:target_date = datetime.date.today()else:target_date = datetime.datetime.strptime(date, "%Y-%m-%d").date()t = yf.Ticker(ticker_symbol)data = t.history(start=target_date - datetime.timedelta(days=7),end=target_date + datetime.timedelta(days=7),)if data.empty:return (f"No exchange rate data found for {base}/{quote} ({ticker_symbol}). "f"Verify that both currency codes are valid ISO 4217 codes.")data["Date"] = data.index.datedata["DateDiff"] = data["Date"].apply(lambda d: abs((d - target_date).days))nearest = data.loc[data["DateDiff"].idxmin()]rate = nearest["Close"]actual_date = nearest["Date"]date_label = f"nearest to {date}" if date else "most recent"return f"The exchange rate for {base}/{quote} ({date_label}) is {rate:.6f} as of {actual_date}."except ValueError:return f"Invalid date format '{date}'. Please use YYYY-MM-DD (e.g. 2024-01-15)."except Exception as exc:return f"Error fetching exchange rate for {base}/{quote}: {exc}"def _get_news(ticker: str) -> list[dict]:t = yf.Ticker(ticker)news = t.news27 unmodified lines"negative": -1}def _bucket_label(score: float) -> str:if score > 0.15:return "positive"2 unmodified linesreturn "neutral"def _recency_weights(pub_dates: list[str]) -> list[float]:decay = 0.01parsed = []for d in pub_dates:try:17 unmodified linesreturn weightsdef _score_texts(texts: list[str]) -> list[dict]:tokenizer, model = _load_finbert()results = []with torch.no_grad():18 unmodified lines@tool("get_news_sentiment")def get_news_sentiment(ticker: str) -> str:articles = _get_news(ticker)comp_name = yf.Ticker(ticker).info.get("longName", ticker)if not articles:40 unmodified linesf"Composite score: {composite:+.4f} ({label}). "f"Top influencing headlines: {top_headlines}")@tool("respond_to_greeting")def respond_to_greeting() -> str:2 unmodified lines@tool("respond_no_available_tool")def respond_no_available_tool(tool_name: str) -> str:return f"Sorry, currently i'm capable of doing that. Check the list of avaiable tools for more information."12 unmodified lines13141516171819202139 unmodified lines6162636465666768697071727374757677787980818283848576 unmodified lines1621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911927 unmodified lines20020120220320420520620720820921021121221321421522 unmodified lines23823924024124224324424524624724824926 unmodified lines27627727827928028128226 unmodified lines3093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403417 unmodified lines34935035135235335435535635735835936036136236327 unmodified lines39139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343427 unmodified lines4624634644654664674684694704714722 unmodified lines47547647747847948048117 unmodified lines49950050150250350450518 unmodified lines52452552652752852953053140 unmodified lines5725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078082 unmodified lines81181281381412 unmodified linesimport torch.nn.functional as Fimport osfrom dotenv import load_dotenvload_dotenv()BANXICO_TOKEN = os.getenv("BANXICO_TOKEN")HF_LOGIN_KEY = os.getenv("HF_LOGIN_KEY")if HF_LOGIN_KEY:39 unmodified lines@tool("get_price_on_date")def get_price_on_date(ticker, date=None):t = yf.Ticker(ticker)use_default_date = date is Noneif date is None:date = datetime.date.today()else:date = datetime.datetime.strptime(date, "%Y-%m-%d").date()data = pd.DataFrame(t.history(start=date - datetime.timedelta(days=5), end=date + datetime.timedelta(days=5))['Close'])if data.empty:return f"No price data available for {t.ticker} around {date}."data['Date'] = data.index.datedata['DateDiff'] = np.abs(data['Date'] - date)nearest_row = data.loc[data['DateDiff'].idxmin()]price = nearest_row['Close']actual_date = nearest_row['Date']official_name = t.info['longName']if use_default_date:return f"The last price of {official_name} ({t.ticker}) is ${price:.2f} as of {actual_date}."else:76 unmodified linesf"Expected annual return: {(returns.mean() @ result.x * 252):.2%}\n"f"Annualized volatility: {(np.sqrt(result.x.T @ cov_matrix @ result.x) * np.sqrt(252)):.2%}")CETES_SERIES = {28: "SF43936",91: "SF43939",182: "SF43942",364: "SF43945",728: "SF349785",}@tool("get_cetes_rate")def get_cetes_rate(term_days: int, date: str | None = None) -> str:#valid days are the ones displayed aboveif term_days not in CETES_SERIES:valid = ", ".join(str(k) for k in CETES_SERIES)return f"Invalid term '{term_days}'. Valid options are: {valid}."series_id = CETES_SERIES[term_days]url = f"https://www.banxico.org.mx/SieAPIRest/service/v1/series/{series_id}/datos"headers = {"Bmx-Token": BANXICO_TOKEN,"Content-Type": "application/json",}try:response = requests.get(url, headers=headers)response.raise_for_status()obs_list = response.json()["bmx"]["series"][0]["datos"]7 unmodified lineskey=lambda o: abs(datetime.datetime.strptime(o["fecha"], "%d/%m/%Y") - target),)fecha = datetime.datetime.strptime(obs["fecha"], "%d/%m/%Y").strftime("%Y-%m-%d")value = float(obs["dato"])label = f"nearest to {date}" if date else "most recent"return f"The CETES {term_days}-day rate ({label}) is {value:.4f}% as of {fecha}."except ValueError:return f"Invalid date format '{date}'. Please use YYYY-MM-DD (e.g. 2024-01-15)."except Exception as exc:return f"Error fetching CETES {term_days}-day rate: {exc}"@tool("get_mensual_inflation_mexico")def get_mensual_inflation_mexico(date: str | None = None) -> str:22 unmodified linesvalue = float(obs["dato"])label = f"nearest to {date}" if date else "most recent"return f"The monthly inflation rate in Mexico ({label}) is {value:.4f}% as of {fecha}."except ValueError:return f"Invalid date format '{date}'. Please use YYYY-MM-DD (e.g. 2024-01-15)."except Exception as exc:return f"Error fetching monthly inflation rate in Mexico: {exc}"@tool("get_inflation_mexico")def get_inflation_mexico(date: str | None = None) -> str:URL = "https://www.banxico.org.mx/SieAPIRest/service/v1/series/SP30577/datos"26 unmodified linesreturn f"Invalid date format '{date}'. Please use YYYY-MM-DD (e.g. 2024-01-15)."except Exception as exc:return f"Error fetching annual inflation rate in Mexico: {exc}"@tool("get_udis")def get_udis(date: str | None = None) -> str:URL = "https://www.banxico.org.mx/SieAPIRest/service/v1/series/SP68257/datos"26 unmodified linesreturn f"Invalid date format '{date}'. Please use YYYY-MM-DD (e.g. 2024-01-15)."except Exception as exc:return f"Error fetching UDIs value in Mexico: {exc}"TIIE_SERIES = {28: "SF43783",91: "SF43878",182: "SF111916",}@tool("get_tiie_rate")def get_tiie_rate(term_days: int, date: str | None = None) -> str:"""Fetches the TIIE (Tasa de Interés Interbancaria de Equilibrio) ratefor a given term in days from Banxico.Valid terms are: 28, 91, 182."""if term_days not in TIIE_SERIES:valid = ", ".join(str(k) for k in TIIE_SERIES)return f"Invalid term '{term_days}'. Valid options are: {valid}."series_id = TIIE_SERIES[term_days]url = f"https://www.banxico.org.mx/SieAPIRest/service/v1/series/{series_id}/datos"headers = {"Bmx-Token": BANXICO_TOKEN,"Content-Type": "application/json",}try:response = requests.get(url, headers=headers)response.raise_for_status()obs_list = response.json()["bmx"]["series"][0]["datos"]7 unmodified lineskey=lambda o: abs(datetime.datetime.strptime(o["fecha"], "%d/%m/%Y") - target),)fecha = datetime.datetime.strptime(obs["fecha"], "%d/%m/%Y").strftime("%Y-%m-%d")value = float(obs["dato"])label = f"nearest to {date}" if date else "most recent"return f"The TIIE {term_days}-day rate ({label}) is {value:.4f}% as of {fecha}."except ValueError:return f"Invalid date format '{date}'. Please use YYYY-MM-DD (e.g. 2024-01-15)."except Exception as exc:return f"Error fetching TIIE {term_days}-day rate: {exc}"@tool("get_target_interest_rate_mexico")def get_target_interest_rate_mexico(date: str | None = None) -> str:27 unmodified linesreturn f"Invalid date format '{date}'. Please use YYYY-MM-DD (e.g. 2024-01-15)."except Exception as exc:return f"Error fetching target interest rate in Mexico: {exc}"@tool("get_exchange_rate")def get_exchange_rate(base: str, quote: str, date: str | None = None) -> str:base = base.strip().upper()quote = quote.strip().upper()ticker_symbol = f"{base}{quote}=X"try:if date is None:target_date = datetime.date.today()else:target_date = datetime.datetime.strptime(date, "%Y-%m-%d").date()t = yf.Ticker(ticker_symbol)data = t.history(start=target_date - datetime.timedelta(days=7),end=target_date + datetime.timedelta(days=7),)if data.empty:return (f"No exchange rate data found for {base}/{quote} ({ticker_symbol}). "f"Verify that both currency codes are valid ISO 4217 codes.")data["Date"] = data.index.datedata["DateDiff"] = data["Date"].apply(lambda d: abs((d - target_date).days))nearest = data.loc[data["DateDiff"].idxmin()]rate = nearest["Close"]actual_date = nearest["Date"]date_label = f"nearest to {date}" if date else "most recent"return f"The exchange rate for {base}/{quote} ({date_label}) is {rate:.6f} as of {actual_date}."except ValueError:return f"Invalid date format '{date}'. Please use YYYY-MM-DD (e.g. 2024-01-15)."except Exception as exc:return f"Error fetching exchange rate for {base}/{quote}: {exc}"def _get_news(ticker: str) -> list[dict]:t = yf.Ticker(ticker)news = t.news27 unmodified lines"negative": -1}_SCORE_TO_LABEL = {lambda s: s > 0.15: "positive",lambda s: s < -0.15: "negative",}def _bucket_label(score: float) -> str:if score > 0.15:return "positive"2 unmodified linesreturn "neutral"def _recency_weights(pub_dates: list[str]) -> list[float]:decay = 0.01parsed = []for d in pub_dates:try:17 unmodified linesreturn weightsdef _score_texts(texts: list[str]) -> list[dict]:"""Returns a list of {label, confidence} dicts, one per input text."""tokenizer, model = _load_finbert()results = []with torch.no_grad():18 unmodified lines@tool("get_news_sentiment")def get_news_sentiment(ticker: str) -> str:"""Fetches recent news for a ticker and returns a FinBERT-basedsentiment score aggregated across all available headlines."""articles = _get_news(ticker)comp_name = yf.Ticker(ticker).info.get("longName", ticker)if not articles:40 unmodified linesf"Composite score: {composite:+.4f} ({label}). "f"Top influencing headlines: {top_headlines}")@tool("calculate_inflation_impact")def calculate_inflation_impact(amount: float, months: int, annual_inflation_rate: float) -> str:monthly_rate = (1 + annual_inflation_rate / 100) ** (1 / 12) - 1future_equivalent = amount * (1 + monthly_rate) ** monthspurchasing_power_loss = future_equivalent - amounteffective_value = amount - purchasing_power_lossreturn (f"With an annual inflation rate of {annual_inflation_rate:.2f}%, "f"{amount:.2f} pesos today will have the purchasing power of "f"{effective_value:.2f} pesos after {months} month(s). "f"That is a loss of {purchasing_power_loss:.2f} pesos in real value.")@tool("multiply")def multiply(a: float, b: float) -> str:result = a * breturn f"The result of {a} × {b} is {result}."# --------------- sector-adjusted valuation thresholds -------------------------# Tuple layout: (pe_strong, pe_weak, pb_strong, pb_weak, ev_ebitda_strong, ev_ebitda_weak)# "strong" means the value that earns the maximum score of 2.# "weak" means the value that earns the minimum score of 0.# Values between the two thresholds score 1 (neutral)._SECTOR_VALUATION_THRESHOLDS: dict[str, tuple] = {"technology": (25, 45, 4.0, 10.0, 15, 30),"healthcare": (20, 35, 3.0, 8.0, 14, 25),"financial-services": (12, 20, 1.0, 2.5, 10, 18),"consumer-cyclical": (18, 30, 2.5, 6.0, 12, 22),"consumer-defensive": (18, 28, 3.0, 6.0, 12, 20),"energy": (10, 20, 1.5, 3.0, 6, 14),"basic-materials": (12, 22, 1.5, 3.5, 8, 16),"industrials": (18, 30, 2.5, 5.0, 12, 20),"real-estate": (30, 55, 1.5, 3.5, 18, 30),"utilities": (15, 25, 1.5, 3.0, 10, 18),"default": (18, 35, 2.5, 6.0, 12, 22),}def _valuation_thresholds(sector_key: str | None) -> tuple:key = (sector_key or "").lower()return _SECTOR_VALUATION_THRESHOLDS.get(key, _SECTOR_VALUATION_THRESHOLDS["default"])def _score_metric(value: float, strong_threshold: float, weak_threshold: float,lower_is_better: bool = True) -> int:"""Scores a single metric on a 0–2 scale.For lower_is_better metrics (P/E, D/E, EV/EBITDA …):value <= strong_threshold → 2value >= weak_threshold → 0in between → 1For higher_is_better metrics (ROE, margins, FCF yield …):value >= strong_threshold → 2value <= weak_threshold → 0in between → 1"""if lower_is_better:if value <= strong_threshold:return 2if value >= weak_threshold:return 0return 1else:if value >= strong_threshold:return 2if value <= weak_threshold:return 0return 1@tool("get_fundamental_analysis")def get_fundamental_analysis(ticker: str) -> str:"""Performs a quantitative fundamental analysis scorecard for a given ticker.Evaluates 15 metrics across four categories:- Valuation (P/E, P/B, EV/EBITDA, PEG) max 8 pts- Profitability (ROE, ROA, Gross margin, Net margin) max 8 pts- Financial Health (D/E, Current ratio, IC, FCF yield) max 8 pts- Growth (Revenue growth, Earnings growth, Div yield) max 6 pts──────────TOTAL max 30 ptsScoring per metric: 2 = strong, 1 = neutral / data unavailable, 0 = weak.Valuation thresholds are sector-adjusted via yfinance sectorKey.Composite: ≥70% → BUY | 40–69% → HOLD | <40% → SELL.Apply the same exchange suffix rules as get_price_on_date (e.g. BIMBOA.MX)."""t = yf.Ticker(ticker)info = t.infocompany_name = info.get("longName", ticker)sector_key = info.get("sectorKey", None)sector_label = info.get("sector", "Unknown sector")pe_s, pe_w, pb_s, pb_w, ev_s, ev_w = _valuation_thresholds(sector_key)def safe(key: str, scale: float = 1.0):"""Returns (scaled_value, is_available). Missing or non-numeric → (None, False)."""raw = info.get(key)if raw is None or not isinstance(raw, (int, float)):return None, Falsereturn raw * scale, True# ── Valuation (max 8 pts) ──────────────────────────────────────────────────pe, pe_ok = safe("trailingPE")pb, pb_ok = safe("priceToBook")ev_ebitda, ev_ok = safe("enterpriseToEbitda")peg, peg_ok = safe("pegRatio")pe_score = _score_metric(pe, pe_s, pe_w, lower_is_better=True) if pe_ok else 1pb_score = _score_metric(pb, pb_s, pb_w, lower_is_better=True) if pb_ok else 1ev_score = _score_metric(ev_ebitda, ev_s, ev_w, lower_is_better=True) if ev_ok else 1peg_score = _score_metric(peg, 1.0, 2.0, lower_is_better=True) if peg_ok else 1valuation_score = pe_score + pb_score + ev_score + peg_score # max 8# ── Profitability (max 8 pts) ──────────────────────────────────────────────roe, roe_ok = safe("returnOnEquity", scale=100)roa, roa_ok = safe("returnOnAssets", scale=100)gross_m, gm_ok = safe("grossMargins", scale=100)net_m, nm_ok = safe("profitMargins", scale=100)roe_score = _score_metric(roe, 15.0, 8.0, lower_is_better=False) if roe_ok else 1roa_score = _score_metric(roa, 5.0, 2.0, lower_is_better=False) if roa_ok else 1gm_score = _score_metric(gross_m, 40.0, 20.0, lower_is_better=False) if gm_ok else 1nm_score = _score_metric(net_m, 10.0, 3.0, lower_is_better=False) if nm_ok else 1profit_score = roe_score + roa_score + gm_score + nm_score # max 8# ── Financial Health (max 8 pts) ───────────────────────────────────────────de, de_ok = safe("debtToEquity")cr, cr_ok = safe("currentRatio")ebitda, ebit_ok = safe("ebitda")int_exp, ie_ok = safe("interestExpense")fcf, fcf_ok = safe("freeCashflow")mktcap, mc_ok = safe("marketCap")# yfinance returns D/E as a percentage (e.g. 150 means 1.50); normalise to ratio.de_adj = de / 100.0 if de_ok else Nonede_score = _score_metric(de_adj, 0.5, 1.5, lower_is_better=True) if de_ok else 1cr_score = _score_metric(cr, 2.0, 1.0, lower_is_better=False) if cr_ok else 1# Interest coverage = EBITDA / |interest expense|; higher is better.if ebit_ok and ie_ok and int_exp != 0:ic = abs(ebitda) / abs(int_exp)ic_score = _score_metric(ic, 5.0, 2.0, lower_is_better=False)else:ic = Noneic_score = 1# FCF yield = FCF / market cap (%); >5% strong, <0% weak.if fcf_ok and mc_ok and mktcap > 0:fcf_yield = (fcf / mktcap) * 100fcf_score = _score_metric(fcf_yield, 5.0, 0.0, lower_is_better=False)else:fcf_yield = Nonefcf_score = 1health_score = de_score + cr_score + ic_score + fcf_score # max 8# ── Growth (max 6 pts) ─────────────────────────────────────────────────────rev_g, rg_ok = safe("revenueGrowth", scale=100)earn_g, eg_ok = safe("earningsGrowth", scale=100)div_y, dy_ok = safe("dividendYield", scale=100)rev_score = _score_metric(rev_g, 10.0, 0.0, lower_is_better=False) if rg_ok else 1earn_score = _score_metric(earn_g, 10.0, 0.0, lower_is_better=False) if eg_ok else 1# Dividend yield: 2–5.5% is the ideal income range.# Below 0.5% is neutral (growth company, no penalty). Above 6% may signal distress.if dy_ok:if 2.0 <= div_y <= 5.5:div_score = 2elif div_y > 6.0 or div_y < 0.5:div_score = 0else:div_score = 1else:div_score = 1 # no dividend data → neutralgrowth_score = rev_score + earn_score + div_score # max 6# ── Composite & recommendation ─────────────────────────────────────────────MAX_SCORE = 30composite = valuation_score + profit_score + health_score + growth_scorepct = composite / MAX_SCOREif pct >= 0.70:recommendation = "BUY"rationale = "the company scores strongly across most fundamental dimensions"elif pct >= 0.40:recommendation = "HOLD"rationale = "the fundamentals are mixed with no compelling entry or exit signal"else:recommendation = "SELL"rationale = "the company shows material weakness across multiple fundamental dimensions"def fmt(value, decimals: int = 2, suffix: str = "") -> str:return "N/A" if value is None else f"{value:.{decimals}f}{suffix}"return (f"Fundamental analysis scorecard for {company_name} ({ticker.upper()}) | Sector: {sector_label}. "f"VALUATION ({valuation_score}/8): "f"P/E {fmt(pe)}x [score {pe_score}/2], "f"P/B {fmt(pb)}x [score {pb_score}/2], "f"EV/EBITDA {fmt(ev_ebitda)}x [score {ev_score}/2], "f"PEG {fmt(peg)} [score {peg_score}/2]. "f"PROFITABILITY ({profit_score}/8): "f"ROE {fmt(roe)}% [score {roe_score}/2], "f"ROA {fmt(roa)}% [score {roa_score}/2], "f"Gross margin {fmt(gross_m)}% [score {gm_score}/2], "f"Net margin {fmt(net_m)}% [score {nm_score}/2]. "f"FINANCIAL HEALTH ({health_score}/8): "f"D/E {fmt(de_adj)} [score {de_score}/2], "f"Current ratio {fmt(cr)} [score {cr_score}/2], "f"Interest coverage {fmt(ic)}x [score {ic_score}/2], "f"FCF yield {fmt(fcf_yield)}% [score {fcf_score}/2]. "f"GROWTH ({growth_score}/6): "f"Revenue growth {fmt(rev_g)}% [score {rev_score}/2], "f"Earnings growth {fmt(earn_g)}% [score {earn_score}/2], "f"Dividend yield {fmt(div_y)}% [score {div_score}/2]. "f"COMPOSITE SCORE: {composite}/{MAX_SCORE} ({pct:.0%}). "f"RECOMMENDATION: {recommendation} — {rationale}.")@tool("respond_to_greeting")def respond_to_greeting() -> str:2 unmodified lines@tool("respond_no_available_tool")def respond_no_available_tool(tool_name: str) -> str:return f"Sorry, currently i'm capable of doing that. Check the list of avaiable tools for more information."
app.py+3-1
prompts.py+104-71
tools.py+303-228