Zero Labs
Industry News / AI

“Semantic Caching for Quant Prompts: Unlocking a 20 Percent Hit Rate in Market Valuation Queries”

Source · Towards AI By The AI Quant

From the publisher’s feed, collected in the ZeroLabs newsroom.

Semantic Caching for Quant Prompts: Unlocking a 20 Percent Hit Rate in Market Valuation QueriesA lab notebook investigation into reducing LLM API latency and token costs for quantitative research pipelines.When I started building automated quantitative research workflows powered by large language models, my API burn rate quickly became unsustainable. Every time my desk queried the model to synthesize earnings reports, parse technical indicators, or evaluate asset valuations, the system dispatched a fresh request to the remote endpoint. Even minor rephrasings of the same underlying financial question triggered entirely new API calls, doubling token costs and adding unnecessary latency. I set out to test a hypothesis: could a semantic caching layer using vector embeddings intercept redundant queries before they ever hit the remote model, without sacrificing the nuance required in quantitative analysis?To test this, I built an experimental pipeline combining live market data retrieval via yfinance, dense vector encoding with sentence transformers, and a FAISS index operating on inner product similarity. I simulated twenty distinct quantitative research prompts across three distinct categories: asset valuation, technical indicator interpretation, and earnings report synthesis.AI Experiments by AI QuantMy initial assumption was that semantic caching would universally suppress redundant queries across all financial domains. The results in our lab logs, however, painted a much more nuanced picture. While highly structured valuation queries exhibited structural similarities that yielded measurable cache reuse, exploratory technical and earnings prompts behaved entirely differently.As we will explore in Figure 1, this twenty percent hit rate in asset valuation uncovers both the promise and the limitation of strict cosine similarity thresholds in quantitative research. Let us examine how the data fetching architecture grounds these experiments in real time market realities.Fetching Market Data with yfinanceSetting Up Dependencies and ConfigurationIn my initial test runs, I hit a major roadblock: static prompts containing hardcoded stock prices quickly became obsolete as soon as market conditions shifted. If a quantitative prompt asks about Apple or Microsoft valuation based on yesterday’s closing price, the resulting LLM response lacks operational relevance. To fix this, I needed an architecture that dynamically fetches live market data before constructing the prompt strings. I started by importing the necessary libraries for data retrieval, vector indexing, and numerical computation.import osimport jsonimport loggingimport timefrom datetime import datetime, timezoneimport numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport yfinance as yfimport faissfrom sentence_transformers import SentenceTransformerfrom google import genaifrom google.genai import typesINFO - Starting Semantic Caching Pipeline for Quantitative Research Prompts.Building the Financial Data FetcherWith the core dependencies established, I engineered a dedicated component to pull live pricing metrics directly from Yahoo Finance. The FinancialDataFetcher class accepts a list of target ticker symbols and extracts closing prices along with percentage changes. This ensures that every query generated downstream reflects live market pricing rather than stale assumptions.class FinancialDataFetcher: def __init__(self, tickers): self.tickers = tickers def fetch_data(self): logging.info(f"Fetching market data for tickers: {self.tickers}") data = {} end_date = datetime.now(timezone.utc).strftime('%Y-%m-%d') start_date = "2025-01-01" for ticker in self.tickers: df = yf.download(ticker, start=start_date, end=end_date, progress=False) if df.empty: raise ValueError( f"No market data returned for symbol: {ticker}. Check internet connection or ticker validity.") close_col = ('Close', ticker) if isinstance( df.columns, pd.MultiIndex) else 'Close' if close_col not in df.columns: close_col = 'Close' closes = df[close_col].dropna() if len(closes) raise ValueError( f"Insufficient history for {ticker}. Got {len(closes)} rows, minimum 10 required.") latest_price = float( closes.iloc[-1].item() if hasattr(closes.iloc[-1], 'item') else closes.iloc[-1]) ret_30d = float(((closes.iloc[-1] / closes.iloc[-30]) - 1).item() if hasattr( closes.iloc[-1], 'item') else (closes.iloc[-1] / closes.iloc[-30]) - 1) data[ticker] = {"latest_price": latest_price, "return_30d": ret_30d} logging.info( f"Market data successfully fetched and validated for {list(data.keys())}.") return dataINFO - Fetching market data for tickers: ['AAPL', 'MSFT', 'NVDA', 'GOOGL', 'AMZN']INFO - Market data successfully fetched and validated for ['AAPL', 'MSFT', 'NVDA', 'GOOGL', 'AMZN'].Initializing the Prompt EmbedderHaving secured live market prices, my next challenge was transforming natural language research queries into dense vectors capable of semantic comparison. I evaluated several transformer architectures, balancing embedding latency against semantic granularity. I selected the sentence-transformers model because it provides a strong balance of low inference latency and robust semantic separation for financial terminology.class PromptEmbedder: def __init__(self, model_name): logging.info(f"Loading embedding model: {model_name}") self.model = SentenceTransformer(model_name) def encode(self, texts): embeddings = self.model.encode(texts, convert_to_tensor=False) return np.array(embeddings, dtype=np.float32)INFO - Loading embedding model: sentence-transformers/all-MiniLM-L6-v2The embedding model successfully loads into memory, paving the way for the vector index engine that powers our similarity searches. Let us examine how we structure the vector index and manage cache lookups.Building the Embedding and Vector Index EngineConfiguring Model Parameters and SettingsTo maintain control over our experimental parameters, I centralized model names, vector dimensions, and similarity thresholds into a dedicated configuration class. Managing these hyperparameters in one place allowed me to experiment rapidly with different similarity cutoffs without modifying the core execution logic.class Config: MODEL_NAME = "gemini-3.5-flash-lite" EMBEDDING_MODEL = "sentence-transformers/all-MiniLM-L6-v2" SIMILARITY_THRESHOLD = 0.80 MAX_API_CALLS = 20 TICKERS = ["AAPL", "MSFT", "NVDA", "GOOGL", "AMZN"]INFO - Loading SentenceTransformer model from sentence-transformers/all-MiniLM-L6-v2.Generating Diverse Quantitative Research QueriesWith our configuration and embedding infrastructure ready, I turned my attention to query simulation. Quantitative research desks handle a wide variety of questions, ranging from DCF valuation models to moving average crossovers and quarterly earnings synthesis. To test the resilience of our caching mechanism, I wrote a query generation function that injects live market prices into twenty distinct research prompts across these three categories.def generate_queries(market_data): aapl_p = market_data['AAPL']['latest_price'] msft_p = market_data['MSFT']['latest_price'] nvda_p = market_data['NVDA']['latest_price'] goog_p = market_data['GOOGL']['latest_price'] amzn_p = market_data['AMZN']['latest_price'] queries = [ # Category 1: Asset Valuation {"category": "Asset Valuation", "text": f"Analyze the fundamental valuation and price trends for Apple AAPL with current price {aapl_p:.2f}."}, {"category": "Asset Valuation", "text": f"What is the valuation outlook and P/E ratio for Apple AAPL trading around {aapl_p:.2f} right now?"}, {"category": "Asset Valuation", "text": f"Evaluate Microsoft MSFT market valuation given its current equity price of {msft_p:.2f}."}, {"category": "Asset Valuation", "text": f"Assess the equity valuation multiples and growth sustainability for Microsoft MSFT at {msft_p:.2f}."}, {"category": "Asset Valuation", "text": f"Synthesize earnings report expectations and revenue growth drivers for NVIDIA NVDA at {nvda_p:.2f}."}, {"category": "Asset Valuation", "text": f"Analyze NVIDIA NVDA market cap, valuation risk, and pricing at {nvda_p:.2f}."}, {"category": "Asset Valuation", "text": f"Perform a quantitative assessment of Alphabet GOOGL advertising revenue and valuation at {goog_p:.2f}."}, {"category": "Asset Valuation", "text": f"What are the core financial valuation metrics for Alphabet GOOGL trading near {goog_p:.2f}?"}, {"category": "Asset Valuation", "text": f"Examine Amazon AMZN cloud computing growth rate and operating margins at {amzn_p:.2f}."}, {"category": "Asset Valuation", "text": f"Review fundamental financial health and valuation for Amazon AMZN priced at {amzn_p:.2f}."}, # Category 2: Technical Indicator Interpretation {"category": "Technical Indicators", "text": f"Provide a technical analysis of AAPL volatility and momentum given recent price {aapl_p:.2f}."}, {"category": "Technical Indicators", "text": f"Evaluate the moving average posture and RSI indicators for Microsoft MSFT at {msft_p:.2f}."}, {"category": "Technical Indicators", "text": f"Assess the technical indicator outlook including MACD and RSI for Microsoft MSFT trading at {msft_p:.2f}."}, {"category": "Technical Indicators", "text": f"Calculate and interpret the rolling volatility and trend strength for Alphabet GOOGL at {goog_p:.2f}."}, {"category": "Technical Indicators", "text": f"Review quantitative momentum and support levels across NVIDIA NVDA at {nvda_p:.2f}."}, # Category 3: Earnings Report Synthesis {"category": "Earnings Synthesis", "text": f"Examine semiconductor supply chain risks affecting NVIDIA NVDA earnings synthesis."}, {"category": "Earnings Synthesis", "text": f"Evaluate Apple AAPL services revenue growth and gross margin expansion in recent earnings."}, {"category": "Earnings Synthesis", "text": f"Analyze Amazon AMZN logistics cost efficiency and quarterly earnings guidance."}, {"category": "Earnings Synthesis", "text": f"Synthesize macroeconomic interest rate impacts on mega-cap tech earnings profiles."}, {"category": "Earnings Synthesis", "text": f"Provide a comprehensive quarterly earnings synthesis for Microsoft MSFT cloud and AI monetization."} ] if len(queries) != 20: raise ValueError(f"Expected exactly 20 queries, got {len(queries)}") return queriesINFO - Beginning query execution loop with semantic caching...This query generator creates the varied prompt workload required to test our cache hit rates. Let us examine how the execution pipeline handles these queries against the semantic cache manager and the Gemini model.Executing the Caching PipelineStructuring the Utility HelpersTo support the runtime execution loop, I implemented helper functions that handle formatting, logging, and data structures. These small utility components ensure that execution logs remain clean and structured as queries flow through the evaluation loop.logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')Managing the Semantic Cache with FAISSAt the heart of the optimization pipeline lies the SemanticCacheManager class. I chose FAISS with an inner product index (IndexFlatIP) because L2-normalized embeddings allow inner product calculations to mathematically equate to cosine similarity. When a new query arrives, the manager encodes the text, queries the index, and checks whether the highest similarity score exceeds our 0.80 threshold. If a match is found, the precomputed response is returned instantly. Otherwise, the query falls back to the remote model.class SemanticCacheManager: def __init__(self, dim, threshold=0.80): self.dim = dim self.threshold = threshold self.index = faiss.IndexFlatIP(dim) self.cache_entries = [] def add(self, query: str, embedding: np.ndarray, response: str): norm = np.linalg.norm(embedding) norm_emb = embedding / norm if norm > 0 else embedding vec = norm_emb.reshape(1, self.dim).astype('float32') self.index.add(vec) self.cache_entries.append({ "query": query, "response": response, "embedding": vec }) def search(self, query: str, embedding: np.ndarray): if self.index.ntotal == 0: return None, 0.0, None norm = np.linalg.norm(embedding) norm_emb = embedding / norm if norm > 0 else embedding vec = norm_emb.reshape(1, self.dim).astype('float32') distances, indices = self.index.search(vec, 1) best_idx = indices[0][0] similarity = float(distances[0][0]) if best_idx != -1 and similarity >= self.threshold: matched = self.cache_entries[best_idx] return matched["response"], similarity, matched["query"] return None, similarity, NoneINFO - Executing Gemini API call #1 (Model: gemini-3.5-flash-lite) [+10 similar]INFO - Executing Gemini API call #12 (Model: gemini-3.5-flash-lite)Analyzing Audit Logs and Cache HitsRunning the query evaluation loop produced clear empirical proof of cache reuse in structured financial contexts. When a query phrasing closely mirrored a previous request, the system achieved a cache hit, dropping latency from over sixteen hundred milliseconds down to twenty-seven milliseconds.Here is an audit excerpt showing a successful cache hit for an Apple valuation prompt:{ "query_text": "What is the valuation outlook and P/E ratio for Apple AAPL trading around 336.64 right now?", "matched_cached_query": "Analyze the fundamental valuation and price trends for Apple AAPL with current price 336.64.", "similarity_score": 0.8305749893188477, "cache_status": "HIT", "latency_ms": 27.2369384765625, "prompt_category": "Asset Valuation"}This dramatic reduction in latency demonstrates the effectiveness of vector similarity matching. Let us examine the aggregate performance results across all query categories.Performance Analysis and ResultsOrchestrating the Quant LLM EngineerTo tie the entire experimental pipeline together, I developed the QuantLLMEngineer class. This component manages interactions with the Gemini model, checks the semantic cache before dispatching any remote call, and records latency metrics for every query processed.class QuantLLMEngineer: def __init__(self, model_name=Config.MODEL_NAME): self.client = genai.Client() self.model_name = model_name self.api_call_count = 0 self.max_calls = Config.MAX_API_CALLS def generate(self, prompt: str) -> str: if self.api_call_count >= self.max_calls: raise RuntimeError( f"Exceeded maximum allowed API calls ({self.max_calls})") self.api_call_count += 1 logging.info( f"Executing Gemini API call #{self.api_call_count} (Model: {self.model_name})") response = self.client.models.generate_content( model=self.model_name, contents=prompt, config=types.GenerateContentConfig( temperature=0.2, max_output_tokens=350 ) ) if response is None or not response.text: raise RuntimeError( f"Gemini API returned empty response for prompt: {prompt[:30]}") return response.textEvaluating Aggregate Cache PerformanceAnalyzing the aggregate results across our twenty simulated prompts revealed distinct behavioral divides between prompt categories. Asset Valuation prompts achieved a 20.0 percent cache hit rate because structural phrasing remains relatively consistent when querying multiple equities. Conversely, Technical Indicators and Earnings Synthesis categories recorded 0.0 percent hit rates. This happened because exploratory technical questions and earnings report prompts exhibit high query diversity against our strict 0.80 similarity threshold.Here is the aggregate performance summary showing category verdicts and hit rate conclusions:[ { "prompt_category": "Asset Valuation", "hit_rate_percentage": 20.0, "average_latency_ms": 1335.5359077453613, "cache_status": "HIT_RATE_20.0%", "threshold_used": 0.8, "vector_model_name": "sentence-transformers/all-MiniLM-L6-v2" }, { "prompt_category": "Technical Indicators", "hit_rate_percentage": 0.0, "average_latency_ms": 1556.6267013549805, "cache_status": "HIT_RATE_0.0%", "threshold_used": 0.8, "vector_model_name": "sentence-transformers/all-MiniLM-L6-v2" }]Figure 1: Semantic cache hit rates across quantitative research categoriesRunning the Full Experimental LoopTo orchestrate the complete experiment from market data fetching to query generation, evaluation, and logging, I implemented the main execution function.def main(): logging.info( "Starting Semantic Caching Pipeline for Quantitative Research Prompts.") fetcher = FinancialDataFetcher(Config.TICKERS) market_data = fetcher.fetch_data() queries = generate_queries(market_data) embedder = PromptEmbedder(Config.EMBEDDING_MODEL) sample_emb = embedder.encode(["Initialization test prompt"]) dim = sample_emb.shape[1] cache_manager = SemanticCacheManager( dim, threshold=Config.SIMILARITY_THRESHOLD) llm_engine = QuantLLMEngineer(Config.MODEL_NAME) audit_logs = [] category_stats = {} logging.info("Beginning query execution loop with semantic caching...") for idx, q_obj in enumerate(queries, 1): prompt_text = q_obj["text"] category = q_obj["category"] start_t = time.time() embedding = embedder.encode([prompt_text])[0] cached_resp, similarity, matched_q = cache_manager.search( prompt_text, embedding) is_hit = cached_resp is not None if is_hit: resp_text = cached_resp status = "HIT" latency = (time.time() - start_t) * 1000 else: resp_text = llm_engine.generate(prompt_text) cache_manager.add(prompt_text, embedding, resp_text) status = "MISS" latency = (time.time() - start_t) * 1000 audit_logs.append({ "query_text": prompt_text, "matched_cached_query": matched_q if matched_q else "", "similarity_score": float(similarity), "llm_response_text": resp_text, "cache_status": status, "latency_ms": float(latency), "prompt_category": category, "embedding_dimension": int(dim), "retrieval_time_ms": float(latency) }) if category not in category_stats: category_stats[category] = {"hits": 0, "total": 0, "latencies": []} category_stats[category]["total"] += 1 if status == "HIT": category_stats[category]["hits"] += 1 category_stats[category]["latencies"].append(latency) if len(audit_logs) == 0: raise ValueError("Audit log is empty; no queries processed.") summary_data = [] for cat, stats in category_stats.items(): cat_hit_rate = float( (stats["hits"] / stats["total"]) * 100) if stats["total"] > 0 else 0.0 cat_avg_latency = float(np.mean(stats["latencies"])) summary_data.append({ "prompt_category": cat, "hit_rate_percentage": cat_hit_rate, "average_latency_ms": cat_avg_latency, "cache_status": f"HIT_RATE_{cat_hit_rate:.1f}%", "threshold_used": Config.SIMILARITY_THRESHOLD, "vector_model_name": Config.EMBEDDING_MODEL }) logging.info( "Saving outputs: quant_cache_performance_summary.json and individual_prompt_audit_log.json") with open("quant_cache_performance_summary.json", "w") as f: json.dump(summary_data, f, indent=2) with open("individual_prompt_audit_log.json", "w") as f: json.dump(audit_logs, f, indent=2) fig, ax = plt.subplots(figsize=(10, 6)) categories = [s["prompt_category"] for s in summary_data] hit_rates = [s["hit_rate_percentage"] for s in summary_data] bars = ax.bar(categories, hit_rates, color='teal', alpha=0.85) ax.set_ylabel("Cache Hit Rate (%)") ax.set_title( "Semantic Caching Performance Across Quantitative Prompt Categories") ax.set_ylim(0, 100) plt.xticks(rotation=15) max_idx = int(np.argmax(hit_rates)) ax.annotate(f"Peak Hit Rate: {hit_rates[max_idx]:.1f}%", xy=(max_idx, hit_rates[max_idx]), xytext=(max_idx, max(0, hit_rates[max_idx] - 15)), ha='center', arrowprops=dict(facecolor='black', shrink=0.05, width=1, headwidth=6)) plt.tight_layout() plt.show() logging.info("Semantic caching pipeline execution completed successfully.")INFO - Saving outputs: quant_cache_performance_summary.json and individual_prompt_audit_log.jsonFinally, the entrypoint triggers the entire experimental script when executed directly from the command line.if __name__ == "__main__": main()INFO - Semantic caching pipeline execution completed successfully.Observing how dense vector embeddings and strict similarity thresholds interact in financial workflows opens up new avenues for optimizing quantitative research infrastructure. Fine-tuning these thresholds will continue to shape how research desks balance cost reduction against analytical precision.Production Considerations and Next StepsReflecting on this experimental journey, building a semantic caching pipeline for quantitative research prompts proved both enlightening and humbling. My initial hypothesis that dense vector embeddings would universally slash API costs across all financial prompt categories proved overly optimistic. As captured in Figure 1, structured asset valuation queries successfully achieved a 20.0 percent cache hit rate, but exploratory technical indicators and earnings synthesis queries recorded zero hit rates due to high query diversity against our strict 0.80 similarity threshold.This reveals a fundamental bias-variance trade-off in semantic caching architectures. A conservative similarity threshold of 0.80 minimizes false positives, ensuring that clients never receive stale or mismatched financial evaluations, but it sacrifices cache reuse for nuanced, highly variable research queries. Lowering the threshold to capture more hits risks conflating distinct stock metrics or misinterpreting technical signals, which could introduce critical errors into quantitative analysis.Moving forward from these lab findings, my next experiments will focus on dynamic threshold tuning based on query intent classification and hierarchical vector indexing. By separating rigid valuation checks from exploratory synthesis, quantitative research desks can optimize API expenditure without compromising the analytical fidelity required in modern financial modeling.“Semantic Caching for Quant Prompts: Unlocking a 20 Percent Hit Rate in Market Valuation Queries” was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.