Financial Deep Research <!-- STATIC CONTEXT BLOCK START - Optimized for prompt caching -- <!-- All static instructions, methodology, and templates below this line -- <!-- Dynamic content (user queries, results) added after this block -- Core System Instructions Purpose: Deliver citation-backed, verified financial research reports through 8-phase pipeline (Scope Plan Retrieve Triangulate Synthesize Critique Refine Package) with financial source credibility scoring, regulatory compliance tracking, and progressive context management. Financial Focus: This skill specializes in: - Market analysis…

,\n r'\u003cdiv class=\"section\">\u003ch2 class=\"section-title\">\\1\u003c/h2>',\n html,\n flags=re.MULTILINE\n )\n\n html = re.sub(\n r'^### (.+)

Financial Deep Research <!-- STATIC CONTEXT BLOCK START - Optimized for prompt caching -- <!-- All static instructions, methodology, and templates below this line -- <!-- Dynamic content (user queries, results) added after this block -- Core System Instructions Purpose: Deliver citation-backed, verified financial research reports through 8-phase pipeline (Scope Plan Retrieve Triangulate Synthesize Critique Refine Package) with financial source credibility scoring, regulatory compliance tracking, and progressive context management. Financial Focus: This skill specializes in: - Market analysis…

,\n r'\u003ch3 class=\"subsection-title\">\\1\u003c/h3>',\n html,\n flags=re.MULTILINE\n )\n\n html = re.sub(\n r'^#### (.+)

Financial Deep Research <!-- STATIC CONTEXT BLOCK START - Optimized for prompt caching -- <!-- All static instructions, methodology, and templates below this line -- <!-- Dynamic content (user queries, results) added after this block -- Core System Instructions Purpose: Deliver citation-backed, verified financial research reports through 8-phase pipeline (Scope Plan Retrieve Triangulate Synthesize Critique Refine Package) with financial source credibility scoring, regulatory compliance tracking, and progressive context management. Financial Focus: This skill specializes in: - Market analysis…

,\n r'\u003ch4 class=\"subsubsection-title\">\\1\u003c/h4>',\n html,\n flags=re.MULTILINE\n )\n\n # Convert **bold** text\n html = re.sub(r'\\*\\*(.+?)\\*\\*', r'\u003cstrong>\\1\u003c/strong>', html)\n\n # Convert *italic* text\n html = re.sub(r'\\*(.+?)\\*', r'\u003cem>\\1\u003c/em>', html)\n\n # Convert inline code\n html = re.sub(r'`(.+?)`', r'\u003ccode>\\1\u003c/code>', html)\n\n # Convert lists\n html = _convert_lists(html)\n\n # Convert tables\n html = _convert_tables(html)\n\n # Convert paragraphs\n html = _convert_paragraphs(html)\n\n # Close sections\n html = _close_sections(html)\n\n # Wrap executive summary\n html = html.replace(\n '\u003ch2 class=\"section-title\">Executive Summary\u003c/h2>',\n '\u003cdiv class=\"executive-summary\">\u003ch2 class=\"section-title\">Executive Summary\u003c/h2>'\n )\n if '\u003cdiv class=\"executive-summary\">' in html:\n html = html.replace(\n '\u003c/h2>\\n\u003cdiv class=\"section\">',\n '\u003c/h2>\u003c/div>\\n\u003cdiv class=\"section\">',\n 1\n )\n\n return html\n\n\ndef _convert_bibliography_section(markdown: str) -> str:\n \"\"\"Convert bibliography section to HTML with tier organization\"\"\"\n if not markdown.strip():\n return \"\"\n\n html = markdown\n\n # Convert tier headers\n html = re.sub(\n r'^### (Tier \\d.+)

Financial Deep Research <!-- STATIC CONTEXT BLOCK START - Optimized for prompt caching -- <!-- All static instructions, methodology, and templates below this line -- <!-- Dynamic content (user queries, results) added after this block -- Core System Instructions Purpose: Deliver citation-backed, verified financial research reports through 8-phase pipeline (Scope Plan Retrieve Triangulate Synthesize Critique Refine Package) with financial source credibility scoring, regulatory compliance tracking, and progressive context management. Financial Focus: This skill specializes in: - Market analysis…

,\n r'\u003cdiv class=\"bib-tier\">\u003cdiv class=\"bib-tier-title\">\\1\u003c/div>',\n html,\n flags=re.MULTILINE\n )\n\n # Convert citation entries\n html = re.sub(\n r'\\[(\\d+)\\]\\s*(.+?)\\s*(https?://[^\\s\\)]+)',\n r'\u003cdiv class=\"bib-entry\">\u003cspan class=\"bib-number\">[\\1]\u003c/span> \\2 \u003ca href=\"\\3\" target=\"_blank\">\\3\u003c/a>\u003c/div>',\n html\n )\n\n # Convert bold\n html = re.sub(r'\\*\\*(.+?)\\*\\*', r'\u003cstrong>\\1\u003c/strong>', html)\n\n html = f'\u003cdiv class=\"bibliography-content\">{html}\u003c/div>'\n\n return html\n\n\ndef _convert_lists(html: str) -> str:\n \"\"\"Convert markdown lists to HTML lists\"\"\"\n lines = html.split('\\n')\n result = []\n in_list = False\n list_type = None\n\n for line in lines:\n stripped = line.strip()\n\n if stripped.startswith('- ') or stripped.startswith('* '):\n if not in_list:\n result.append('\u003cul>')\n in_list = True\n list_type = 'ul'\n content = stripped[2:]\n result.append(f'\u003cli>{content}\u003c/li>')\n\n elif re.match(r'^\\d+\\.\\s', stripped):\n if not in_list:\n result.append('\u003col>')\n in_list = True\n list_type = 'ol'\n content = re.sub(r'^\\d+\\.\\s', '', stripped)\n result.append(f'\u003cli>{content}\u003c/li>')\n\n else:\n if in_list:\n result.append(f'\u003c/{list_type}>')\n in_list = False\n list_type = None\n result.append(line)\n\n if in_list:\n result.append(f'\u003c/{list_type}>')\n\n return '\\n'.join(result)\n\n\ndef _convert_tables(html: str) -> str:\n \"\"\"Convert markdown tables to HTML tables\"\"\"\n lines = html.split('\\n')\n result = []\n in_table = False\n is_header = False\n\n for line in lines:\n if '|' in line and line.strip().startswith('|'):\n if not in_table:\n result.append('\u003ctable class=\"data-table\">')\n in_table = True\n is_header = True\n cells = [cell.strip() for cell in line.split('|')[1:-1]]\n result.append('\u003cthead>\u003ctr>')\n for cell in cells:\n result.append(f'\u003cth>{cell}\u003c/th>')\n result.append('\u003c/tr>\u003c/thead>')\n result.append('\u003ctbody>')\n elif '---' in line:\n continue\n else:\n cells = [cell.strip() for cell in line.split('|')[1:-1]]\n result.append('\u003ctr>')\n for cell in cells:\n # Add numeric class for numbers\n css_class = 'numeric' if re.match(r'^[\\$\\d\\.\\,\\%\\+\\-]+

Financial Deep Research <!-- STATIC CONTEXT BLOCK START - Optimized for prompt caching -- <!-- All static instructions, methodology, and templates below this line -- <!-- Dynamic content (user queries, results) added after this block -- Core System Instructions Purpose: Deliver citation-backed, verified financial research reports through 8-phase pipeline (Scope Plan Retrieve Triangulate Synthesize Critique Refine Package) with financial source credibility scoring, regulatory compliance tracking, and progressive context management. Financial Focus: This skill specializes in: - Market analysis…

, cell.replace('B', '').replace('M', '').replace('K', '')) else ''\n # Add positive/negative class for changes\n if cell.startswith('+'):\n css_class += ' positive'\n elif cell.startswith('-') and '%' in cell:\n css_class += ' negative'\n result.append(f'\u003ctd class=\"{css_class.strip()}\">{cell}\u003c/td>')\n result.append('\u003c/tr>')\n else:\n if in_table:\n result.append('\u003c/tbody>\u003c/table>')\n in_table = False\n result.append(line)\n\n if in_table:\n result.append('\u003c/tbody>\u003c/table>')\n\n return '\\n'.join(result)\n\n\ndef _convert_paragraphs(html: str) -> str:\n \"\"\"Wrap non-HTML lines in paragraph tags\"\"\"\n lines = html.split('\\n')\n result = []\n in_paragraph = False\n\n for line in lines:\n stripped = line.strip()\n\n if not stripped:\n if in_paragraph:\n result.append('\u003c/p>')\n in_paragraph = False\n result.append(line)\n continue\n\n if (stripped.startswith('\u003c') and stripped.endswith('>')) or \\\n stripped.startswith('\u003c/') or \\\n '\u003ch' in stripped or '\u003cdiv' in stripped or '\u003cul' in stripped or \\\n '\u003col' in stripped or '\u003cli' in stripped or '\u003ctable' in stripped:\n if in_paragraph:\n result.append('\u003c/p>')\n in_paragraph = False\n result.append(line)\n continue\n\n if not in_paragraph:\n result.append('\u003cp>' + line)\n in_paragraph = True\n else:\n result.append(line)\n\n if in_paragraph:\n result.append('\u003c/p>')\n\n return '\\n'.join(result)\n\n\ndef _close_sections(html: str) -> str:\n \"\"\"Close all open section divs\"\"\"\n lines = html.split('\\n')\n result = []\n section_open = False\n\n for line in lines:\n if '\u003cdiv class=\"section\">' in line:\n if section_open:\n result.append('\u003c/div>')\n section_open = True\n result.append(line)\n\n if section_open:\n result.append('\u003c/div>')\n\n return '\\n'.join(result)\n\n\ndef main():\n \"\"\"Test the converter\"\"\"\n import sys\n\n if len(sys.argv) \u003c 2:\n print(\"Usage: python md_to_html.py \u003cmarkdown_file>\")\n sys.exit(1)\n\n md_file = Path(sys.argv[1])\n if not md_file.exists():\n print(f\"Error: File {md_file} not found\")\n sys.exit(1)\n\n markdown_text = md_file.read_text()\n content_html, bib_html = convert_markdown_to_html(markdown_text)\n\n print(\"=== CONTENT HTML ===\")\n print(content_html[:1500])\n print(\"\\n=== BIBLIOGRAPHY HTML ===\")\n print(bib_html[:500])\n\n\nif __name__ == \"__main__\":\n main()\n","content_type":"text/x-python; charset=utf-8","language":"python","size":8580,"content_sha256":"42d7b42d3a4d8dfa8d26e3d5a1d56b91d1bc20b31e5328bca83eda9cb39792a8"},{"filename":"scripts/research_engine.py","content":"#!/usr/bin/env python3\n\"\"\"\nFinancial Research Engine\nCore orchestration for financial deep research pipeline\n\nNote: This is a placeholder for the research engine. The actual orchestration\nis handled by Claude Code when the skill is invoked. This module provides\nutility functions that can be called from the command line for testing.\n\"\"\"\n\nimport argparse\nimport sys\nfrom pathlib import Path\nfrom datetime import datetime\n\n\ndef main():\n \"\"\"Entry point for financial research engine\"\"\"\n parser = argparse.ArgumentParser(\n description=\"Financial Deep Research Engine\",\n formatter_class=argparse.RawDescriptionHelpFormatter,\n epilog=\"\"\"\nFinancial Research Modes:\n quick - Market snapshot, 2-5 min, 10+ sources\n standard - Most analysis, 5-10 min, 15-30 sources (default)\n deep - Investment decisions, 10-20 min, 25-50 sources\n ultradeep - M&A due diligence, 20-45 min, 30-100+ sources\n\nExamples:\n python research_engine.py --query \"Analyze Apple investment thesis\" --mode standard\n python research_engine.py --query \"NVDA vs AMD competitive analysis\" --mode deep\n python research_engine.py --query \"Fintech sector due diligence\" --mode ultradeep\n\nNote: This engine is typically invoked through Claude Code's skill system.\nDirect CLI usage is for testing and debugging.\n \"\"\"\n )\n\n parser.add_argument(\n '--query', '-q',\n type=str,\n required=True,\n help='Financial research query'\n )\n\n parser.add_argument(\n '--mode', '-m',\n type=str,\n choices=['quick', 'standard', 'deep', 'ultradeep'],\n default='standard',\n help='Research mode (default: standard)'\n )\n\n parser.add_argument(\n '--output', '-o',\n type=str,\n default=None,\n help='Output directory (default: /code/research_output/)'\n )\n\n args = parser.parse_args()\n\n print(f\"\\n{'='*60}\")\n print(f\"FINANCIAL DEEP RESEARCH ENGINE\")\n print(f\"{'='*60}\\n\")\n\n print(f\"Query: {args.query}\")\n print(f\"Mode: {args.mode}\")\n print(f\"Output: {args.output or '/code/research_output/'}\")\n print()\n\n # Mode configuration\n mode_config = {\n 'quick': {\n 'phases': [1, 3, 8],\n 'min_sources': 10,\n 'target_time': '2-5 min',\n 'description': 'Market snapshot'\n },\n 'standard': {\n 'phases': [1, 2, 3, 4, 4.5, 5, 8],\n 'min_sources': 15,\n 'target_time': '5-10 min',\n 'description': 'Standard analysis'\n },\n 'deep': {\n 'phases': [1, 2, 3, 4, 4.5, 5, 6, 7, 8],\n 'min_sources': 25,\n 'target_time': '10-20 min',\n 'description': 'Investment decision'\n },\n 'ultradeep': {\n 'phases': [1, 2, 3, 4, 4.5, 5, 6, 7, 8],\n 'min_sources': 30,\n 'target_time': '20-45 min',\n 'description': 'M&A due diligence'\n }\n }\n\n config = mode_config[args.mode]\n\n print(f\"Configuration:\")\n print(f\" Phases: {config['phases']}\")\n print(f\" Min Sources: {config['min_sources']}\")\n print(f\" Target Time: {config['target_time']}\")\n print(f\" Description: {config['description']}\")\n print()\n\n print(\"Note: Full research execution requires Claude Code skill invocation.\")\n print(\"This CLI provides configuration preview and testing utilities.\")\n print()\n\n # Generate output directory name\n timestamp = datetime.now().strftime('%Y%m%d')\n topic_slug = args.query[:30].replace(' ', '_').replace('/', '_')\n output_dir = f\"/code/{topic_slug}_Financial_Research_{timestamp}/\"\n\n print(f\"Recommended output directory: {output_dir}\")\n print()\n\n return 0\n\n\nif __name__ == '__main__':\n sys.exit(main())\n","content_type":"text/x-python; charset=utf-8","language":"python","size":3761,"content_sha256":"a1014c87a9a332cd5687c73b53445960bf9cfa2887c266a98eb40d0be137b6bf"},{"filename":"scripts/source_evaluator.py","content":"#!/usr/bin/env python3\n\"\"\"\nFinancial Source Credibility Evaluator\nAssesses source quality, credibility, and potential biases for financial research\n\"\"\"\n\nfrom dataclasses import dataclass\nfrom typing import List, Dict, Optional\nfrom urllib.parse import urlparse\nfrom datetime import datetime, timedelta\nimport re\n\n\n@dataclass\nclass CredibilityScore:\n \"\"\"Represents financial source credibility assessment\"\"\"\n overall_score: float # 0-100\n domain_authority: float # 0-100\n recency: float # 0-100\n expertise: float # 0-100\n bias_score: float # 0-100 (higher = more neutral)\n tier: int # 1-4 (1 = highest credibility)\n factors: Dict[str, str]\n recommendation: str # \"high_trust\", \"moderate_trust\", \"low_trust\", \"verify\"\n\n\nclass FinancialSourceEvaluator:\n \"\"\"Evaluates financial source credibility and quality with tiered system\"\"\"\n\n # Tier 1: Primary/Regulatory Sources (Highest Credibility)\n TIER_1_DOMAINS = {\n # SEC & Regulatory\n 'sec.gov', 'edgar.sec.gov', 'investor.gov',\n 'federalreserve.gov', 'treasury.gov', 'fdic.gov',\n 'occ.gov', 'finra.org', 'cftc.gov', 'bis.org',\n\n # Company IR (pattern-based, checked separately)\n # ir.*, investor.*, investors.*\n\n # Stock Exchanges\n 'nyse.com', 'nasdaq.com', 'ice.com', 'cmegroup.com',\n\n # International Regulators\n 'fca.org.uk', 'esma.europa.eu', 'bafin.de',\n }\n\n # Tier 2: Financial Data Providers (High Credibility)\n TIER_2_DOMAINS = {\n # Major Data Providers\n 'bloomberg.com', 'reuters.com', 'refinitiv.com',\n 'spglobal.com', 'capitaliq.com', 'moodys.com',\n 'fitchratings.com', 'factset.com', 'morningstar.com',\n 'pitchbook.com', 'preqin.com', 'dealogic.com',\n\n # Research Providers\n 'mckinsey.com', 'bcg.com', 'bain.com', 'deloitte.com',\n 'pwc.com', 'ey.com', 'kpmg.com',\n }\n\n # Tier 3: Financial News & Research (Moderate-High Credibility)\n TIER_3_DOMAINS = {\n # Established Financial News\n 'wsj.com', 'ft.com', 'barrons.com', 'economist.com',\n 'marketwatch.com', 'investopedia.com', 'thestreet.com',\n\n # Business News\n 'cnbc.com', 'fortune.com', 'businessinsider.com',\n 'forbes.com', 'bloomberg.com', # News articles\n\n # Industry Publications\n 'americanbanker.com', 'institutionalinvestor.com',\n 'privateequityinternational.com', 'pensions-investments.com',\n }\n\n # Tier 4: General Business Sources (Moderate Credibility)\n TIER_4_DOMAINS = {\n # General Finance\n 'finance.yahoo.com', 'google.com/finance',\n 'seekingalpha.com', 'fool.com', 'zacks.com',\n 'tipranks.com', 'gurufocus.com',\n\n # General News\n 'nytimes.com', 'washingtonpost.com', 'bbc.com',\n 'cnn.com', 'theguardian.com',\n\n # Tech/Business Blogs\n 'medium.com', 'substack.com', 'linkedin.com',\n }\n\n # Low credibility indicators\n LOW_CREDIBILITY_INDICATORS = [\n 'blogspot.com', 'wordpress.com', 'wix.com',\n 'reddit.com', 'twitter.com', 'facebook.com',\n 'stocktwits.com', 'wallstreetbets',\n ]\n\n def __init__(self):\n pass\n\n def evaluate_source(\n self,\n url: str,\n title: str,\n content: Optional[str] = None,\n publication_date: Optional[str] = None,\n author: Optional[str] = None\n ) -> CredibilityScore:\n \"\"\"Evaluate financial source credibility\"\"\"\n\n domain = self._extract_domain(url)\n\n # Determine tier first\n tier = self._determine_tier(domain, url)\n\n # Calculate component scores\n domain_score = self._evaluate_domain_authority(domain, tier)\n recency_score = self._evaluate_recency(publication_date)\n expertise_score = self._evaluate_expertise(domain, title, author, tier)\n bias_score = self._evaluate_bias(domain, title, content, tier)\n\n # Calculate overall score (weighted average)\n overall = (\n domain_score * 0.40 + # Higher weight for domain in financial\n recency_score * 0.20 +\n expertise_score * 0.25 +\n bias_score * 0.15\n )\n\n # Determine factors\n factors = self._identify_factors(\n domain, tier, domain_score, recency_score, expertise_score, bias_score\n )\n\n # Generate recommendation\n recommendation = self._generate_recommendation(overall, tier)\n\n return CredibilityScore(\n overall_score=round(overall, 2),\n domain_authority=round(domain_score, 2),\n recency=round(recency_score, 2),\n expertise=round(expertise_score, 2),\n bias_score=round(bias_score, 2),\n tier=tier,\n factors=factors,\n recommendation=recommendation\n )\n\n def _extract_domain(self, url: str) -> str:\n \"\"\"Extract domain from URL\"\"\"\n parsed = urlparse(url)\n domain = parsed.netloc.lower()\n # Remove www prefix\n domain = domain.replace('www.', '')\n return domain\n\n def _determine_tier(self, domain: str, url: str) -> int:\n \"\"\"Determine source tier (1-4)\"\"\"\n\n # Check Tier 1\n if domain in self.TIER_1_DOMAINS:\n return 1\n # Check for company IR sites (Tier 1)\n if any(pattern in domain for pattern in ['ir.', 'investor.', 'investors.']):\n return 1\n # SEC EDGAR links\n if 'sec.gov' in url:\n return 1\n\n # Check Tier 2\n if domain in self.TIER_2_DOMAINS:\n return 2\n\n # Check Tier 3\n if domain in self.TIER_3_DOMAINS:\n return 3\n\n # Check Tier 4\n if domain in self.TIER_4_DOMAINS:\n return 4\n\n # Check low credibility\n if any(indicator in domain for indicator in self.LOW_CREDIBILITY_INDICATORS):\n return 4 # Lowest tier\n\n # Unknown domain - default to tier 4\n return 4\n\n def _evaluate_domain_authority(self, domain: str, tier: int) -> float:\n \"\"\"Evaluate domain authority based on tier (0-100)\"\"\"\n tier_scores = {\n 1: 95.0, # Regulatory/Primary\n 2: 82.0, # Data Providers\n 3: 68.0, # Financial News\n 4: 50.0, # General Business\n }\n\n base_score = tier_scores.get(tier, 50.0)\n\n # Bonus for specific high-authority domains\n if 'sec.gov' in domain:\n base_score = 100.0\n elif 'federalreserve.gov' in domain:\n base_score = 98.0\n elif domain in ['bloomberg.com', 'reuters.com']:\n base_score = 88.0\n\n # Penalty for low credibility indicators\n if any(indicator in domain for indicator in self.LOW_CREDIBILITY_INDICATORS):\n base_score = min(base_score, 35.0)\n\n return base_score\n\n def _evaluate_recency(self, publication_date: Optional[str]) -> float:\n \"\"\"Evaluate information recency (0-100)\"\"\"\n if not publication_date:\n return 50.0 # Unknown date\n\n try:\n pub_date = datetime.fromisoformat(publication_date.replace('Z', '+00:00'))\n age = datetime.now() - pub_date\n\n # Financial data has stricter recency requirements\n if age \u003c timedelta(days=30): # \u003c 1 month\n return 100.0\n elif age \u003c timedelta(days=90): # \u003c 3 months\n return 90.0\n elif age \u003c timedelta(days=180): # \u003c 6 months\n return 75.0\n elif age \u003c timedelta(days=365): # \u003c 1 year\n return 60.0\n elif age \u003c timedelta(days=730): # \u003c 2 years\n return 45.0\n else:\n return 30.0\n\n except Exception:\n return 50.0\n\n def _evaluate_expertise(\n self,\n domain: str,\n title: str,\n author: Optional[str],\n tier: int\n ) -> float:\n \"\"\"Evaluate source expertise (0-100)\"\"\"\n base_score = 50.0\n\n # Tier-based expertise\n tier_expertise = {1: 40, 2: 30, 3: 20, 4: 10}\n base_score += tier_expertise.get(tier, 0)\n\n # SEC filings are authoritative\n if 'sec.gov' in domain or '10-K' in title or '10-Q' in title:\n base_score += 20\n\n # Earnings/financial content\n if any(term in title.lower() for term in ['earnings', 'quarterly', 'annual report', 'financial results']):\n base_score += 10\n\n # Analyst/research content\n if any(term in title.lower() for term in ['analysis', 'research', 'rating', 'estimate']):\n base_score += 5\n\n # Author credentials\n if author:\n if any(title in author.lower() for title in ['cfa', 'cpa', 'phd', 'analyst', 'economist']):\n base_score += 10\n\n return min(base_score, 100.0)\n\n def _evaluate_bias(\n self,\n domain: str,\n title: str,\n content: Optional[str],\n tier: int\n ) -> float:\n \"\"\"Evaluate potential bias (0-100, higher = more neutral)\"\"\"\n base_score = 70.0\n\n # Tier-based bias (regulatory sources are most neutral)\n tier_bias = {1: 20, 2: 10, 3: 0, 4: -10}\n base_score += tier_bias.get(tier, 0)\n\n # Check for sensationalism in title\n sensational_indicators = [\n '!', 'shocking', 'crash', 'explode', 'moon', 'rocket',\n 'guaranteed', 'secret', 'you won\\'t believe', 'millionaire'\n ]\n title_lower = title.lower()\n if any(indicator in title_lower for indicator in sensational_indicators):\n base_score -= 25\n\n # Promotional content indicators\n promotional = ['buy now', 'limited time', 'act fast', 'don\\'t miss']\n if any(promo in title_lower for promo in promotional):\n base_score -= 30\n\n # Seeking Alpha, retail sources may have bias\n if 'seekingalpha' in domain or 'fool.com' in domain:\n base_score -= 10\n\n # Check for balance in content\n if content:\n balanced_indicators = ['however', 'risk', 'downside', 'bear case', 'concerns']\n if any(indicator in content.lower() for indicator in balanced_indicators):\n base_score += 10\n\n return min(max(base_score, 0), 100.0)\n\n def _identify_factors(\n self,\n domain: str,\n tier: int,\n domain_score: float,\n recency_score: float,\n expertise_score: float,\n bias_score: float\n ) -> Dict[str, str]:\n \"\"\"Identify key credibility factors\"\"\"\n factors = {}\n\n # Tier factor\n tier_names = {\n 1: \"Tier 1: Primary/Regulatory source\",\n 2: \"Tier 2: Financial data provider\",\n 3: \"Tier 3: Financial news/research\",\n 4: \"Tier 4: General business source\"\n }\n factors['tier'] = tier_names.get(tier, \"Unknown tier\")\n\n if domain_score >= 90:\n factors['domain'] = \"Highest authority financial source\"\n elif domain_score >= 75:\n factors['domain'] = \"High authority financial source\"\n elif domain_score \u003c= 45:\n factors['domain'] = \"Low authority - verify with primary sources\"\n\n if recency_score >= 90:\n factors['recency'] = \"Very recent financial data\"\n elif recency_score \u003c= 50:\n factors['recency'] = \"Dated information - verify currency\"\n\n if expertise_score >= 80:\n factors['expertise'] = \"Expert financial source\"\n elif expertise_score \u003c= 50:\n factors['expertise'] = \"Limited financial expertise\"\n\n if bias_score >= 80:\n factors['bias'] = \"Objective/neutral perspective\"\n elif bias_score \u003c= 50:\n factors['bias'] = \"Potential bias detected\"\n\n return factors\n\n def _generate_recommendation(self, overall_score: float, tier: int) -> str:\n \"\"\"Generate trust recommendation\"\"\"\n # Tier 1 sources get higher trust\n if tier == 1 and overall_score >= 70:\n return \"high_trust\"\n elif tier == 1:\n return \"moderate_trust\"\n\n # Other tiers\n if overall_score >= 80:\n return \"high_trust\"\n elif overall_score >= 65:\n return \"moderate_trust\"\n elif overall_score >= 50:\n return \"low_trust\"\n else:\n return \"verify\"\n\n\n# Example usage\nif __name__ == '__main__':\n evaluator = FinancialSourceEvaluator()\n\n # Test sources\n test_sources = [\n {\n 'url': 'https://www.sec.gov/cgi-bin/browse-edgar?action=getcompany&CIK=0000320193',\n 'title': 'Apple Inc. 10-K Annual Report 2024',\n 'publication_date': '2024-11-01'\n },\n {\n 'url': 'https://www.bloomberg.com/news/articles/2024-10-30/apple-earnings',\n 'title': 'Apple Reports Record Q4 Revenue',\n 'publication_date': '2024-10-30'\n },\n {\n 'url': 'https://seekingalpha.com/article/apple-buy-now',\n 'title': 'Apple: BUY NOW Before It Explodes!',\n 'publication_date': '2024-10-15'\n },\n {\n 'url': 'https://ir.apple.com/investor-relations',\n 'title': 'Apple Investor Relations - Q4 2024 Earnings Call',\n 'publication_date': '2024-10-31'\n }\n ]\n\n for source in test_sources:\n score = evaluator.evaluate_source(**source)\n print(f\"\\nSource: {source['title'][:50]}...\")\n print(f\"URL: {source['url'][:60]}...\")\n print(f\"Tier: {score.tier}\")\n print(f\"Overall Score: {score.overall_score}/100\")\n print(f\"Recommendation: {score.recommendation}\")\n print(f\"Factors: {score.factors}\")\n","content_type":"text/x-python; charset=utf-8","language":"python","size":13731,"content_sha256":"975602cf4d0e93c18b60e696801f0ca2d67271ba3b3f5eb985584e1312b71697"},{"filename":"scripts/validate_report.py","content":"#!/usr/bin/env python3\n\"\"\"\nFinancial Report Validation Script\nEnsures financial research reports meet quality standards before delivery\n\"\"\"\n\nimport argparse\nimport re\nimport sys\nfrom pathlib import Path\nfrom typing import List, Tuple, Dict\n\n\nclass FinancialReportValidator:\n \"\"\"Validates financial research report quality\"\"\"\n\n def __init__(self, report_path: Path):\n self.report_path = report_path\n self.content = self._read_report()\n self.errors: List[str] = []\n self.warnings: List[str] = []\n\n def _read_report(self) -> str:\n \"\"\"Read report file\"\"\"\n try:\n with open(self.report_path, 'r', encoding='utf-8') as f:\n return f.read()\n except Exception as e:\n print(f\"ERROR: Cannot read report: {e}\")\n sys.exit(1)\n\n def validate(self) -> bool:\n \"\"\"Run all validation checks\"\"\"\n print(f\"\\n{'='*60}\")\n print(f\"VALIDATING FINANCIAL REPORT: {self.report_path.name}\")\n print(f\"{'='*60}\\n\")\n\n checks = [\n (\"Executive Summary\", self._check_executive_summary),\n (\"Required Sections\", self._check_required_sections),\n (\"Financial Sections\", self._check_financial_sections),\n (\"Citations\", self._check_citations),\n (\"Bibliography\", self._check_bibliography),\n (\"Placeholder Text\", self._check_placeholders),\n (\"Content Truncation\", self._check_content_truncation),\n (\"Word Count\", self._check_word_count),\n (\"Source Count\", self._check_source_count),\n (\"Financial Data\", self._check_financial_data),\n (\"Broken Links\", self._check_broken_references),\n ]\n\n for check_name, check_func in checks:\n print(f\"Checking: {check_name}...\", end=\" \")\n passed = check_func()\n if passed:\n print(\"PASS\")\n else:\n print(\"FAIL\")\n\n self._print_summary()\n\n return len(self.errors) == 0\n\n def _check_executive_summary(self) -> bool:\n \"\"\"Check executive summary exists and is under 250 words\"\"\"\n pattern = r'## Executive Summary(.*?)(?=##|\\Z)'\n match = re.search(pattern, self.content, re.DOTALL | re.IGNORECASE)\n\n if not match:\n self.errors.append(\"Missing 'Executive Summary' section\")\n return False\n\n summary = match.group(1).strip()\n word_count = len(summary.split())\n\n if word_count > 300:\n self.warnings.append(f\"Executive summary too long: {word_count} words (should be \u003c=250)\")\n\n if word_count \u003c 50:\n self.warnings.append(f\"Executive summary too short: {word_count} words (should be >=50)\")\n\n # Check for investment thesis\n if 'thesis' not in summary.lower() and 'recommendation' not in summary.lower():\n self.warnings.append(\"Executive summary missing clear investment thesis/recommendation\")\n\n return True\n\n def _check_required_sections(self) -> bool:\n \"\"\"Check all required sections are present\"\"\"\n required = [\n \"Executive Summary\",\n \"Overview\", # Company/Topic Overview\n \"Financial Analysis\",\n \"Valuation\",\n \"Competitive\", # Competitive Position\n \"Risk\", # Risk Factors\n \"Recommendation\",\n \"Bibliography\",\n \"Methodology\"\n ]\n\n missing = []\n for section in required:\n if not re.search(rf'##.*{section}', self.content, re.IGNORECASE):\n missing.append(section)\n\n if missing:\n self.errors.append(f\"Missing required sections: {', '.join(missing)}\")\n return False\n\n return True\n\n def _check_financial_sections(self) -> bool:\n \"\"\"Check financial-specific sections\"\"\"\n recommended = [\n \"Revenue\",\n \"Margin\",\n \"Cash Flow\",\n \"Balance Sheet\",\n \"Bull Case\",\n \"Bear Case\"\n ]\n\n missing_recommended = []\n for section in recommended:\n if section.lower() not in self.content.lower():\n missing_recommended.append(section)\n\n if len(missing_recommended) > 3:\n self.warnings.append(f\"Missing recommended financial content: {', '.join(missing_recommended)}\")\n\n return True\n\n def _check_citations(self) -> bool:\n \"\"\"Check citation format and presence\"\"\"\n citations = re.findall(r'\\[(\\d+)\\]', self.content)\n\n if not citations:\n self.errors.append(\"No citations found in report\")\n return False\n\n unique_citations = set(citations)\n\n if len(unique_citations) \u003c 10:\n self.warnings.append(f\"Only {len(unique_citations)} unique sources cited (recommended: >=10)\")\n\n # Check for consecutive citation numbers\n citation_nums = sorted([int(c) for c in unique_citations])\n if citation_nums:\n max_citation = max(citation_nums)\n expected = set(range(1, max_citation + 1))\n missing = expected - set(citation_nums)\n\n if missing:\n self.warnings.append(f\"Non-consecutive citation numbers, missing: {sorted(missing)}\")\n\n return True\n\n def _check_bibliography(self) -> bool:\n \"\"\"Check bibliography exists, matches citations, and has no truncation placeholders\"\"\"\n pattern = r'## Bibliography(.*?)(?=##|\\Z)'\n match = re.search(pattern, self.content, re.DOTALL | re.IGNORECASE)\n\n if not match:\n self.errors.append(\"Missing 'Bibliography' section\")\n return False\n\n bib_section = match.group(1)\n\n # Check for truncation placeholders\n truncation_patterns = [\n (r'\\[\\d+-\\d+\\]', 'Citation range (e.g., [8-75])'),\n (r'Additional.*citations', 'Phrase \"Additional citations\"'),\n (r'would be included', 'Phrase \"would be included\"'),\n (r'\\[\\.\\.\\.continue', 'Pattern \"[...continue\"'),\n (r'\\[Continue with', 'Pattern \"[Continue with\"'),\n (r'etc\\.(?!\\w)', 'Standalone \"etc.\"'),\n ]\n\n for pattern_re, description in truncation_patterns:\n if re.search(pattern_re, bib_section, re.IGNORECASE):\n self.errors.append(f\"CRITICAL: Bibliography contains truncation placeholder: {description}\")\n return False\n\n # Count bibliography entries\n bib_entries = re.findall(r'^\\[(\\d+)\\]', bib_section, re.MULTILINE)\n\n if not bib_entries:\n self.errors.append(\"Bibliography has no entries\")\n return False\n\n # Check for tier organization (recommended for financial)\n if 'Tier 1' not in bib_section and 'tier 1' not in bib_section.lower():\n self.warnings.append(\"Bibliography not organized by source tier (recommended for financial reports)\")\n\n # Find citations in text\n text_citations = set(re.findall(r'\\[(\\d+)\\]', self.content))\n bib_citations = set(bib_entries)\n\n # Check all citations have bibliography entries\n missing_in_bib = text_citations - bib_citations\n if missing_in_bib:\n self.errors.append(f\"Citations missing from bibliography: {sorted(missing_in_bib)}\")\n return False\n\n return True\n\n def _check_placeholders(self) -> bool:\n \"\"\"Check for placeholder text that shouldn't be in final report\"\"\"\n placeholders = [\n 'TBD', 'TODO', 'FIXME', 'XXX',\n '[citation needed]', '[needs citation]',\n '[placeholder]', '[TODO]', '[TBD]',\n '$X.XB', 'XX.X%', '[N]' # Template placeholders\n ]\n\n found_placeholders = []\n for placeholder in placeholders:\n if placeholder in self.content:\n found_placeholders.append(placeholder)\n\n if found_placeholders:\n self.errors.append(f\"Found placeholder text: {', '.join(found_placeholders)}\")\n return False\n\n return True\n\n def _check_content_truncation(self) -> bool:\n \"\"\"Check for content truncation patterns\"\"\"\n truncation_patterns = [\n (r'Content continues', 'Phrase \"Content continues\"'),\n (r'Due to length', 'Phrase \"Due to length\"'),\n (r'would continue', 'Phrase \"would continue\"'),\n (r'\\[Sections \\d+-\\d+', 'Pattern \"[Sections X-Y\"'),\n (r'Additional sections', 'Phrase \"Additional sections\"'),\n ]\n\n for pattern_re, description in truncation_patterns:\n if re.search(pattern_re, self.content, re.IGNORECASE):\n self.errors.append(f\"CRITICAL: Content truncation detected: {description}\")\n return False\n\n return True\n\n def _check_word_count(self) -> bool:\n \"\"\"Check overall report length\"\"\"\n word_count = len(self.content.split())\n\n if word_count \u003c 1000:\n self.warnings.append(f\"Report is very short: {word_count} words (financial reports should be 2000+)\")\n\n print(f\" (Word count: {word_count})\")\n return True\n\n def _check_source_count(self) -> bool:\n \"\"\"Check minimum source count\"\"\"\n pattern = r'## Bibliography(.*?)(?=##|\\Z)'\n match = re.search(pattern, self.content, re.DOTALL | re.IGNORECASE)\n\n if not match:\n return True # Already caught in bibliography check\n\n bib_section = match.group(1)\n bib_entries = re.findall(r'^\\[(\\d+)\\]', bib_section, re.MULTILINE)\n\n source_count = len(set(bib_entries))\n\n if source_count \u003c 10:\n self.warnings.append(f\"Only {source_count} sources (recommended: >=10 for financial reports)\")\n\n # Check for Tier 1 sources (regulatory/primary)\n tier1_indicators = ['sec.gov', 'SEC', '10-K', '10-Q', 'EDGAR', 'investor relations', 'IR']\n tier1_count = sum(1 for indicator in tier1_indicators if indicator in bib_section)\n\n if tier1_count \u003c 2:\n self.warnings.append(\"Limited Tier 1 (regulatory/primary) sources - consider adding SEC filings\")\n\n return True\n\n def _check_financial_data(self) -> bool:\n \"\"\"Check for presence of key financial data\"\"\"\n required_metrics = [\n (r'\\$[\\d,.]+[BMK]', 'Dollar amounts'),\n (r'\\d+\\.?\\d*%', 'Percentages'),\n (r'FY\\d{4}|Q[1-4]\\s*\\d{4}', 'Fiscal periods'),\n ]\n\n for pattern, description in required_metrics:\n if not re.search(pattern, self.content):\n self.warnings.append(f\"Missing financial data: {description}\")\n\n # Check for financial tables\n if '|' not in self.content:\n self.warnings.append(\"No data tables found (recommended for financial reports)\")\n\n return True\n\n def _check_broken_references(self) -> bool:\n \"\"\"Check for broken internal references\"\"\"\n internal_links = re.findall(r'\\[.*?\\]\\((\\.\\/.*?)\\)', self.content)\n\n broken = []\n for link in internal_links:\n link_path = link.split('#')[0]\n full_path = self.report_path.parent / link_path\n\n if not full_path.exists():\n broken.append(link)\n\n if broken:\n self.errors.append(f\"Broken internal links: {', '.join(broken)}\")\n return False\n\n return True\n\n def _print_summary(self):\n \"\"\"Print validation summary\"\"\"\n print(f\"\\n{'='*60}\")\n print(f\"VALIDATION SUMMARY\")\n print(f\"{'='*60}\\n\")\n\n if self.errors:\n print(f\"ERRORS ({len(self.errors)}):\")\n for error in self.errors:\n print(f\" - {error}\")\n print()\n\n if self.warnings:\n print(f\"WARNINGS ({len(self.warnings)}):\")\n for warning in self.warnings:\n print(f\" - {warning}\")\n print()\n\n if not self.errors and not self.warnings:\n print(\"ALL CHECKS PASSED - Report meets financial quality standards!\\n\")\n elif not self.errors:\n print(\"VALIDATION PASSED (with warnings)\\n\")\n else:\n print(\"VALIDATION FAILED - Please fix errors before delivery\\n\")\n\n\ndef main():\n parser = argparse.ArgumentParser(\n description=\"Validate financial research report quality\",\n formatter_class=argparse.RawDescriptionHelpFormatter,\n epilog=\"\"\"\nExamples:\n python validate_report.py --report report.md\n python validate_report.py -r ~/research/financial_report_20251104.md\n \"\"\"\n )\n\n parser.add_argument(\n '--report', '-r',\n type=str,\n required=True,\n help='Path to financial research report markdown file'\n )\n\n args = parser.parse_args()\n\n report_path = Path(args.report)\n\n if not report_path.exists():\n print(f\"ERROR: Report file not found: {report_path}\")\n sys.exit(1)\n\n validator = FinancialReportValidator(report_path)\n passed = validator.validate()\n\n sys.exit(0 if passed else 1)\n\n\nif __name__ == '__main__':\n main()\n","content_type":"text/x-python; charset=utf-8","language":"python","size":13043,"content_sha256":"fed430537cf355dc21c94c967a1b86d062559dfe74fd0d42eee1ab77e191666d"},{"filename":"scripts/verify_citations.py","content":"#!/usr/bin/env python3\n\"\"\"\nFinancial Citation Verification Script\n\nCatches fabricated citations by checking:\n1. SEC EDGAR filing verification\n2. DOI resolution (via doi.org)\n3. Basic metadata matching\n4. URL accessibility verification\n5. Financial data pattern detection\n6. Flags suspicious entries for manual review\n\nUsage:\n python verify_citations.py --report [path]\n python verify_citations.py --report [path] --strict\n\nDoes NOT require API keys - uses free DOI resolver and SEC EDGAR.\n\"\"\"\n\nimport sys\nimport argparse\nimport re\nfrom pathlib import Path\nfrom typing import List, Dict, Tuple\nfrom urllib import request, error\nfrom urllib.parse import quote\nimport json\nimport time\n\n\nclass FinancialCitationVerifier:\n \"\"\"Verify citations in financial research report\"\"\"\n\n def __init__(self, report_path: Path, strict_mode: bool = False):\n self.report_path = report_path\n self.strict_mode = strict_mode\n self.content = self._read_report()\n self.suspicious = []\n self.verified = []\n self.errors = []\n\n # Financial-specific hallucination patterns\n self.suspicious_patterns = [\n # Generic financial-sounding but potentially fake\n (r'^(A |An |The )?(Comprehensive |Complete )?(Analysis|Review|Study) of',\n \"Generic financial title pattern\"),\n (r'^[A-Z][a-z]+ (Inc|Corp|Ltd)\\.? (Financial|Earnings|Annual) (Report|Review)',\n \"Too generic company report title\"),\n # Future financial data (impossible)\n (r'(Q[1-4]|FY)\\s*202[6-9]',\n \"Future fiscal period reference\"),\n (r'(Q[1-4]|FY)\\s*203\\d',\n \"Future fiscal period reference\"),\n ]\n\n # SEC filing patterns for verification\n self.sec_filing_patterns = [\n r'10-K', r'10-Q', r'8-K', r'DEF 14A', r'S-1', r'424B',\n r'Form 10-K', r'Form 10-Q', r'Form 8-K'\n ]\n\n def _read_report(self) -> str:\n \"\"\"Read report file\"\"\"\n try:\n with open(self.report_path, 'r', encoding='utf-8') as f:\n return f.read()\n except Exception as e:\n print(f\"ERROR: Cannot read report: {e}\")\n sys.exit(1)\n\n def extract_bibliography(self) -> List[Dict]:\n \"\"\"Extract bibliography entries from report\"\"\"\n pattern = r'## Bibliography(.*?)(?=##|\\Z)'\n match = re.search(pattern, self.content, re.DOTALL | re.IGNORECASE)\n\n if not match:\n self.errors.append(\"No Bibliography section found\")\n return []\n\n bib_section = match.group(1)\n\n entries = []\n lines = bib_section.strip().split('\\n')\n\n current_entry = None\n for line in lines:\n line = line.strip()\n if not line or line.startswith('#'):\n continue\n\n match_num = re.match(r'^\\[(\\d+)\\]\\s+(.+)

Financial Deep Research <!-- STATIC CONTEXT BLOCK START - Optimized for prompt caching -- <!-- All static instructions, methodology, and templates below this line -- <!-- Dynamic content (user queries, results) added after this block -- Core System Instructions Purpose: Deliver citation-backed, verified financial research reports through 8-phase pipeline (Scope Plan Retrieve Triangulate Synthesize Critique Refine Package) with financial source credibility scoring, regulatory compliance tracking, and progressive context management. Financial Focus: This skill specializes in: - Market analysis…

, line)\n if match_num:\n if current_entry:\n entries.append(current_entry)\n\n num = match_num.group(1)\n rest = match_num.group(2)\n\n # Parse entry components\n year_match = re.search(r'\\((\\d{4})\\)', rest)\n title_match = re.search(r'\"([^\"]+)\"', rest)\n doi_match = re.search(r'doi\\.org/(10\\.\\S+)', rest)\n url_match = re.search(r'https?://[^\\s\\)]+', rest)\n sec_match = any(re.search(p, rest, re.IGNORECASE) for p in self.sec_filing_patterns)\n\n current_entry = {\n 'num': num,\n 'raw': rest,\n 'year': year_match.group(1) if year_match else None,\n 'title': title_match.group(1) if title_match else None,\n 'doi': doi_match.group(1) if doi_match else None,\n 'url': url_match.group(0) if url_match else None,\n 'is_sec_filing': sec_match,\n 'is_tier1': sec_match or ('sec.gov' in rest.lower()) or ('ir.' in rest.lower())\n }\n elif current_entry:\n current_entry['raw'] += ' ' + line\n\n if current_entry:\n entries.append(current_entry)\n\n return entries\n\n def verify_sec_edgar(self, url: str) -> Tuple[bool, str]:\n \"\"\"Verify SEC EDGAR URL is accessible\"\"\"\n if not url or 'sec.gov' not in url:\n return False, \"Not an SEC URL\"\n\n try:\n req = request.Request(url)\n req.add_header('User-Agent', 'Mozilla/5.0 (Financial Research Verifier)')\n\n with request.urlopen(req, timeout=15) as response:\n if response.status == 200:\n return True, \"SEC filing verified\"\n else:\n return False, f\"HTTP {response.status}\"\n except error.HTTPError as e:\n return False, f\"HTTP {e.code}\"\n except Exception as e:\n return False, f\"Connection error: {str(e)[:50]}\"\n\n def verify_doi(self, doi: str) -> Tuple[bool, Dict]:\n \"\"\"Verify DOI exists and get metadata\"\"\"\n if not doi:\n return False, {}\n\n try:\n url = f\"https://doi.org/{quote(doi)}\"\n req = request.Request(url)\n req.add_header('Accept', 'application/vnd.citationstyles.csl+json')\n\n with request.urlopen(req, timeout=10) as response:\n data = json.loads(response.read().decode('utf-8'))\n return True, {\n 'title': data.get('title', ''),\n 'year': data.get('issued', {}).get('date-parts', [[None]])[0][0],\n }\n except error.HTTPError as e:\n if e.code == 404:\n return False, {'error': 'DOI not found'}\n return False, {'error': f'HTTP {e.code}'}\n except Exception as e:\n return False, {'error': str(e)}\n\n def verify_url(self, url: str) -> Tuple[bool, str]:\n \"\"\"Verify URL is accessible\"\"\"\n if not url:\n return False, \"No URL\"\n\n try:\n req = request.Request(url, method='HEAD')\n req.add_header('User-Agent', 'Mozilla/5.0 (Financial Research Verifier)')\n\n with request.urlopen(req, timeout=10) as response:\n if response.status == 200:\n return True, \"URL accessible\"\n else:\n return False, f\"HTTP {response.status}\"\n except error.HTTPError as e:\n # Some sites block HEAD, try GET\n if e.code == 405:\n try:\n req = request.Request(url)\n req.add_header('User-Agent', 'Mozilla/5.0')\n with request.urlopen(req, timeout=10) as response:\n return True, \"URL accessible (GET)\"\n except:\n pass\n return False, f\"HTTP {e.code}\"\n except Exception as e:\n return False, f\"Error: {str(e)[:50]}\"\n\n def detect_hallucination_patterns(self, entry: Dict) -> List[str]:\n \"\"\"Detect common LLM hallucination patterns in financial citations\"\"\"\n issues = []\n title = entry.get('title', '')\n raw = entry.get('raw', '')\n\n if not title:\n return issues\n\n # Check suspicious patterns\n for pattern, description in self.suspicious_patterns:\n if re.match(pattern, title, re.IGNORECASE):\n issues.append(f\"Suspicious pattern: {description}\")\n\n # Check for future dates\n if entry.get('year'):\n year = int(entry['year'])\n if year > 2025:\n issues.append(f\"Future year: {year}\")\n\n # Financial-specific: Check for impossible metrics\n impossible_patterns = [\n (r'\\d{4,}%', \"Implausible percentage (1000%+)\"),\n (r'\\$\\d{15,}', \"Implausible dollar amount\"),\n ]\n for pattern, desc in impossible_patterns:\n if re.search(pattern, raw):\n issues.append(desc)\n\n # Check for Tier 1 sources without verification method\n if entry.get('is_tier1') and not entry.get('url') and not entry.get('doi'):\n issues.append(\"Tier 1 source without verification URL\")\n\n return issues\n\n def verify_entry(self, entry: Dict) -> Dict:\n \"\"\"Verify a single bibliography entry\"\"\"\n result = {\n 'num': entry['num'],\n 'status': 'unknown',\n 'issues': [],\n 'tier': 1 if entry.get('is_tier1') else 4,\n 'verification_methods': []\n }\n\n # Step 1: Hallucination detection\n hallucination_issues = self.detect_hallucination_patterns(entry)\n if hallucination_issues:\n result['issues'].extend(hallucination_issues)\n result['status'] = 'suspicious'\n\n # Step 2: SEC filing verification (Tier 1)\n if entry.get('is_sec_filing') and entry.get('url') and 'sec.gov' in entry['url']:\n print(f\" [{entry['num']}] Checking SEC EDGAR...\", end=' ')\n success, msg = self.verify_sec_edgar(entry['url'])\n if success:\n result['status'] = 'verified'\n result['verification_methods'].append('SEC_EDGAR')\n print(\"OK\")\n else:\n result['issues'].append(f\"SEC verification failed: {msg}\")\n print(f\"FAIL: {msg}\")\n\n # Step 3: DOI verification\n elif entry.get('doi'):\n print(f\" [{entry['num']}] Checking DOI...\", end=' ')\n success, metadata = self.verify_doi(entry['doi'])\n if success:\n result['status'] = 'verified'\n result['verification_methods'].append('DOI')\n print(\"OK\")\n else:\n result['issues'].append(f\"DOI failed: {metadata.get('error', 'unknown')}\")\n result['status'] = 'unverified'\n print(f\"FAIL\")\n\n # Step 4: URL verification\n if entry.get('url') and result['status'] not in ['verified']:\n url_ok, url_status = self.verify_url(entry['url'])\n if url_ok:\n result['verification_methods'].append('URL')\n if result['status'] in ['unknown', 'unverified']:\n result['status'] = 'url_verified'\n print(f\" [{entry['num']}] URL verified\")\n else:\n result['issues'].append(f\"URL check failed: {url_status}\")\n\n # Step 5: No verification method\n if not entry.get('url') and not entry.get('doi'):\n result['issues'].append(\"No verification method (URL or DOI)\")\n if result['status'] == 'unknown':\n result['status'] = 'unverified'\n\n return result\n\n def verify_all(self):\n \"\"\"Verify all bibliography entries\"\"\"\n print(f\"\\n{'='*60}\")\n print(f\"FINANCIAL CITATION VERIFICATION: {self.report_path.name}\")\n print(f\"{'='*60}\\n\")\n\n entries = self.extract_bibliography()\n\n if not entries:\n print(\"No bibliography entries found\\n\")\n return False\n\n # Count by tier\n tier1_count = sum(1 for e in entries if e.get('is_tier1'))\n print(f\"Found {len(entries)} citations ({tier1_count} Tier 1 sources)\\n\")\n\n results = []\n for entry in entries:\n result = self.verify_entry(entry)\n results.append(result)\n time.sleep(0.3) # Rate limiting\n\n # Summarize\n print(f\"\\n{'='*60}\")\n print(f\"VERIFICATION SUMMARY\")\n print(f\"{'='*60}\\n\")\n\n verified = [r for r in results if r['status'] == 'verified']\n url_verified = [r for r in results if r['status'] == 'url_verified']\n suspicious = [r for r in results if r['status'] == 'suspicious']\n unverified = [r for r in results if r['status'] in ['unverified', 'unknown']]\n\n total_verified = len(verified) + len(url_verified)\n\n print(f\"Fully Verified: {len(verified)}/{len(results)}\")\n print(f\"URL Verified: {len(url_verified)}/{len(results)}\")\n print(f\"Suspicious: {len(suspicious)}/{len(results)}\")\n print(f\"Unverified: {len(unverified)}/{len(results)}\")\n print()\n\n if suspicious:\n print(\"SUSPICIOUS CITATIONS (Manual Review Required):\")\n for r in suspicious:\n print(f\"\\n [{r['num']}]\")\n for issue in r['issues']:\n print(f\" - {issue}\")\n print()\n\n # Financial-specific: Check Tier 1 source ratio\n tier1_verified = sum(1 for r in results if r['tier'] == 1 and r['status'] in ['verified', 'url_verified'])\n if tier1_verified \u003c 2:\n print(\"WARNING: Less than 2 verified Tier 1 sources (SEC filings, company IR)\")\n print(\" Financial reports should include primary sources\\n\")\n\n # Decision\n if suspicious and self.strict_mode:\n print(\"STRICT MODE: Failing due to suspicious citations\")\n return False\n\n if total_verified / len(results) \u003c 0.5:\n print(\"WARNING: Less than 50% citations verified\")\n return True # Pass with warning\n\n print(\"CITATION VERIFICATION PASSED\")\n return True\n\n\ndef main():\n parser = argparse.ArgumentParser(\n description=\"Verify citations in financial research report\"\n )\n\n parser.add_argument(\n '--report', '-r',\n type=str,\n required=True,\n help='Path to financial research report'\n )\n\n parser.add_argument(\n '--strict',\n action='store_true',\n help='Strict mode: fail on suspicious citations'\n )\n\n args = parser.parse_args()\n report_path = Path(args.report)\n\n if not report_path.exists():\n print(f\"ERROR: Report not found: {report_path}\")\n sys.exit(1)\n\n verifier = FinancialCitationVerifier(report_path, strict_mode=args.strict)\n passed = verifier.verify_all()\n\n sys.exit(0 if passed else 1)\n\n\nif __name__ == '__main__':\n main()\n","content_type":"text/x-python; charset=utf-8","language":"python","size":14024,"content_sha256":"b6f28f348357759556abb7b9f0c6e936dd07d72b5b36623a04475053b76dfa88"},{"filename":"scripts/verify_html.py","content":"#!/usr/bin/env python3\n\"\"\"\nHTML Financial Report Verification Script\nValidates that HTML reports are properly generated with all sections from MD\n\"\"\"\n\nimport argparse\nimport re\nfrom pathlib import Path\nfrom typing import List\n\n\nclass FinancialHTMLVerifier:\n \"\"\"Verify HTML financial research reports\"\"\"\n\n def __init__(self, html_path: Path, md_path: Path):\n self.html_path = html_path\n self.md_path = md_path\n self.errors = []\n self.warnings = []\n\n def verify(self) -> bool:\n \"\"\"Run all verification checks\"\"\"\n print(f\"\\n{'='*60}\")\n print(f\"HTML FINANCIAL REPORT VERIFICATION\")\n print(f\"{'='*60}\\n\")\n\n print(f\"HTML File: {self.html_path}\")\n print(f\"MD File: {self.md_path}\\n\")\n\n try:\n html_content = self.html_path.read_text()\n md_content = self.md_path.read_text()\n except Exception as e:\n self.errors.append(f\"Failed to read files: {e}\")\n return False\n\n # Run checks\n self._check_sections(html_content, md_content)\n self._check_no_placeholders(html_content)\n self._check_no_emojis(html_content)\n self._check_structure(html_content)\n self._check_financial_elements(html_content)\n self._check_citations(html_content, md_content)\n self._check_bibliography(html_content, md_content)\n\n self._print_results()\n\n return len(self.errors) == 0\n\n def _check_sections(self, html: str, md: str):\n \"\"\"Verify all markdown sections are present in HTML\"\"\"\n md_sections = re.findall(r'^## (.+)

Financial Deep Research <!-- STATIC CONTEXT BLOCK START - Optimized for prompt caching -- <!-- All static instructions, methodology, and templates below this line -- <!-- Dynamic content (user queries, results) added after this block -- Core System Instructions Purpose: Deliver citation-backed, verified financial research reports through 8-phase pipeline (Scope Plan Retrieve Triangulate Synthesize Critique Refine Package) with financial source credibility scoring, regulatory compliance tracking, and progressive context management. Financial Focus: This skill specializes in: - Market analysis…

, md, re.MULTILINE)\n html_sections = re.findall(r'\u003ch2 class=\"section-title\">(.+?)\u003c/h2>', html)\n\n if len(md_sections) > len(html_sections) + 1:\n self.errors.append(\n f\"Section count mismatch: MD has {len(md_sections)}, HTML has {len(html_sections)}\"\n )\n\n def _check_no_placeholders(self, html: str):\n \"\"\"Check for unreplaced placeholders\"\"\"\n placeholders = [\n '{{TITLE}}', '{{DATE}}', '{{CONTENT}}', '{{BIBLIOGRAPHY}}',\n '{{METRICS_DASHBOARD}}', '{{SOURCE_COUNT}}', '{{INVESTMENT_THESIS}}',\n 'TODO', 'TBD', 'PLACEHOLDER', '$X.XB', 'XX.X%'\n ]\n\n found = [p for p in placeholders if p in html]\n if found:\n self.errors.append(f\"Found unreplaced placeholders: {', '.join(found)}\")\n\n def _check_no_emojis(self, html: str):\n \"\"\"Verify no emojis in HTML\"\"\"\n emoji_pattern = re.compile(\n \"[\"\n \"\\U0001F600-\\U0001F64F\"\n \"\\U0001F300-\\U0001F5FF\"\n \"\\U0001F680-\\U0001F6FF\"\n \"\\U0001F1E0-\\U0001F1FF\"\n \"\\U00002702-\\U000027B0\"\n \"\\U000024C2-\\U0001F251\"\n \"]+\",\n flags=re.UNICODE\n )\n\n emojis = emoji_pattern.findall(html)\n if emojis:\n self.errors.append(f\"Found {len(emojis)} emojis in HTML (should be none)\")\n\n def _check_structure(self, html: str):\n \"\"\"Verify HTML has proper structure\"\"\"\n required = [\n ('\u003chtml', 'HTML tag'),\n ('\u003chead', 'head tag'),\n ('\u003cbody', 'body tag'),\n ('\u003ctitle>', 'title tag'),\n ('class=\"header\"', 'header section'),\n ('class=\"content\"', 'content section'),\n ('class=\"bibliography\"', 'bibliography section'),\n ]\n\n for element, name in required:\n if element not in html:\n self.errors.append(f\"Missing {name} in HTML\")\n\n def _check_financial_elements(self, html: str):\n \"\"\"Check for financial-specific HTML elements\"\"\"\n financial_elements = [\n ('class=\"metrics-dashboard\"', 'Metrics dashboard'),\n ('class=\"data-table\"', 'Data tables'),\n ]\n\n for element, name in financial_elements:\n if element not in html:\n self.warnings.append(f\"Missing {name} (recommended for financial reports)\")\n\n # Check for investment thesis\n if 'investment-thesis' not in html and 'Investment Thesis' not in html:\n self.warnings.append(\"Missing investment thesis section\")\n\n def _check_citations(self, html: str, md: str):\n \"\"\"Verify citations are present\"\"\"\n md_citations = set(re.findall(r'\\[(\\d+)\\]', md))\n html_content = html.split('class=\"bibliography\"')[0] if 'class=\"bibliography\"' in html else html\n html_citations = set(re.findall(r'\\[(\\d+)\\]', html_content))\n\n if len(md_citations) > 0 and len(html_citations) == 0:\n self.errors.append(\"No citations found in HTML content\")\n\n def _check_bibliography(self, html: str, md: str):\n \"\"\"Verify bibliography is present\"\"\"\n if '## Bibliography' in md:\n if 'class=\"bibliography\"' not in html:\n self.errors.append(\"Bibliography section missing from HTML\")\n\n def _print_results(self):\n \"\"\"Print verification results\"\"\"\n print(f\"\\n{'-'*60}\")\n print(\"VERIFICATION RESULTS\")\n print(f\"{'-'*60}\\n\")\n\n if self.errors:\n print(f\"ERRORS ({len(self.errors)}):\")\n for error in self.errors:\n print(f\" - {error}\")\n print()\n\n if self.warnings:\n print(f\"WARNINGS ({len(self.warnings)}):\")\n for warning in self.warnings:\n print(f\" - {warning}\")\n print()\n\n if not self.errors and not self.warnings:\n print(\"All checks passed! HTML report is valid.\\n\")\n\n print(f\"{'-'*60}\\n\")\n\n\ndef main():\n parser = argparse.ArgumentParser(description='Verify HTML financial report')\n parser.add_argument('--html', type=Path, required=True, help='Path to HTML report')\n parser.add_argument('--md', type=Path, required=True, help='Path to markdown report')\n\n args = parser.parse_args()\n\n if not args.html.exists():\n print(f\"Error: HTML file not found: {args.html}\")\n return 1\n\n if not args.md.exists():\n print(f\"Error: Markdown file not found: {args.md}\")\n return 1\n\n verifier = FinancialHTMLVerifier(args.html, args.md)\n success = verifier.verify()\n\n return 0 if success else 1\n\n\nif __name__ == \"__main__\":\n exit(main())\n","content_type":"text/x-python; charset=utf-8","language":"python","size":6252,"content_sha256":"73d3943a8ced1b0555894e1fd0be7c69c455f1f863516f2c9251f44e070431a6"},{"filename":"templates/report_template.md","content":"# Financial Research Report: [Topic/Company]\n\n\u003c!-- =============================================================================\nPROGRESSIVE FILE ASSEMBLY STRATEGY (2025 - Unlimited Length):\n\nThis financial report is generated section-by-section using progressive file assembly.\nEach section is generated to APPROPRIATE depth and written to file immediately.\n\nFINANCIAL PRECISION REQUIREMENTS:\n- Every financial metric must include: exact number, currency, time period, source\n- Examples: \"Revenue of $94.8B in FY2024 [1]\" not \"strong revenue\"\n- Examples: \"Gross margin of 43.2%, up 180bps YoY [2]\" not \"improving margins\"\n\nGENERATION WORKFLOW:\n1. Executive Summary with Investment Thesis -> Write to file\n2. Company/Topic Overview -> Edit/append to file\n3. Financial Analysis -> Edit/append to file\n4. Valuation Analysis -> Edit/append to file\n5. Competitive Position -> Edit/append to file\n6. Risk Factors -> Edit/append to file\n7. Investment Thesis (Bull/Base/Bear) -> Edit/append to file\n8. Recommendations -> Edit/append to file\n9. Bibliography (ALL citations) -> Edit/append to file\n10. Methodology Appendix -> Edit/append to file\n\nCITATION TRACKING (CRITICAL):\n- Maintain running list: citations_used = [1, 2, 3, ...]\n- After each section: Add new citations to list\n- In Bibliography: Generate entry for EVERY citation in final list\n- NO gaps, NO ranges, NO placeholders\n\n============================================================================= -->\n\n## Executive Summary\n\n**Investment Thesis:** [One clear sentence stating the core investment thesis]\n\n**Key Metrics:**\n| Metric | Value | vs. Prior | Source |\n|--------|-------|-----------|--------|\n| Market Cap | $X.XB | +X% YoY | [1] |\n| Revenue (LTM) | $X.XB | +X% YoY | [1] |\n| Net Income (LTM) | $X.XB | +X% YoY | [1] |\n| P/E (Forward) | XX.Xx | vs XX.Xx sector | [2] |\n\n**Key Findings:**\n- **Finding 1:** [Major discovery with specific financial data]\n- **Finding 2:** [Important insight with metrics]\n- **Finding 3:** [Critical conclusion with implications]\n\n**Recommendation:** [Buy/Hold/Sell or specific action] with [X]% confidence\n\n**Primary Risks:** [Top 2-3 risks in brief]\n\n---\n\n## Company/Topic Overview\n\n### Business Description\n[2-3 paragraphs describing the company/topic]\n- Business model and revenue drivers\n- Key products/services and segments\n- Geographic presence and customer base\n\n### Industry Context\n[1-2 paragraphs on industry dynamics]\n- Market size and growth rate\n- Key trends affecting the industry\n- Regulatory environment\n\n### Management Overview\n[1 paragraph on leadership]\n- CEO and key executives\n- Track record and tenure\n- Insider ownership and recent transactions\n\n---\n\n## Financial Analysis\n\n\u003c!-- CRITICAL: Include specific numbers with sources for ALL metrics -->\n\n### Revenue Analysis\n\n**Revenue Performance:**\n| Period | Revenue | YoY Growth | Source |\n|--------|---------|------------|--------|\n| FY2024 | $X.XB | +X.X% | [1] |\n| FY2023 | $X.XB | +X.X% | [1] |\n| FY2022 | $X.XB | +X.X% | [1] |\n\n[2-3 paragraphs analyzing revenue trends, drivers, and sustainability]\n\n**Segment Breakdown:**\n| Segment | Revenue | % of Total | Growth | Source |\n|---------|---------|------------|--------|--------|\n| Segment A | $X.XB | XX% | +X% | [1] |\n| Segment B | $X.XB | XX% | +X% | [1] |\n\n### Profitability Analysis\n\n**Margin Trends:**\n| Metric | Current | Prior Year | Change | Source |\n|--------|---------|------------|--------|--------|\n| Gross Margin | XX.X% | XX.X% | +XXbps | [1] |\n| Operating Margin | XX.X% | XX.X% | +XXbps | [1] |\n| Net Margin | XX.X% | XX.X% | +XXbps | [1] |\n\n[2-3 paragraphs analyzing margin trends, drivers, and outlook]\n\n### Cash Flow Analysis\n\n**Cash Flow Summary:**\n| Metric | FY2024 | FY2023 | Source |\n|--------|--------|--------|--------|\n| Operating Cash Flow | $X.XB | $X.XB | [1] |\n| CapEx | $X.XB | $X.XB | [1] |\n| Free Cash Flow | $X.XB | $X.XB | [1] |\n| FCF Margin | XX.X% | XX.X% | Calculated |\n\n[1-2 paragraphs on cash flow quality and capital allocation]\n\n### Balance Sheet Analysis\n\n**Financial Position:**\n| Metric | Current | Prior Year | Source |\n|--------|---------|------------|--------|\n| Cash & Equivalents | $X.XB | $X.XB | [1] |\n| Total Debt | $X.XB | $X.XB | [1] |\n| Net Debt | $X.XB | $X.XB | [1] |\n| Debt/EBITDA | X.Xx | X.Xx | Calculated |\n\n[1-2 paragraphs on balance sheet strength, liquidity, and leverage]\n\n---\n\n## Valuation Analysis\n\n### Comparable Company Analysis\n\n**Peer Comparison:**\n| Company | Market Cap | P/E (Fwd) | EV/EBITDA | Rev Growth | Source |\n|---------|------------|-----------|-----------|------------|--------|\n| [Target] | $X.XB | XX.Xx | XX.Xx | +X.X% | [2] |\n| Peer 1 | $X.XB | XX.Xx | XX.Xx | +X.X% | [2] |\n| Peer 2 | $X.XB | XX.Xx | XX.Xx | +X.X% | [2] |\n| Sector Median | - | XX.Xx | XX.Xx | +X.X% | [2] |\n\n[2-3 paragraphs analyzing valuation relative to peers, premium/discount justification]\n\n### Historical Valuation\n\n[1-2 paragraphs on historical valuation range and current positioning]\n\n### Analyst Consensus\n\n**Price Targets:**\n| Source | Rating | Price Target | Upside | Date | Source |\n|--------|--------|--------------|--------|------|--------|\n| Consensus | Buy | $XXX | +XX% | Current | [3] |\n| High | - | $XXX | +XX% | - | [3] |\n| Low | - | $XXX | -XX% | - | [3] |\n\n[1 paragraph on analyst sentiment and recent rating changes]\n\n---\n\n## Competitive Position\n\n### Market Position\n\n[2-3 paragraphs on competitive positioning]\n- Market share and ranking\n- Competitive advantages (moat)\n- Key differentiators\n\n### Competitive Dynamics\n\n**Competitive Landscape:**\n| Competitor | Market Share | Strengths | Weaknesses | Source |\n|------------|--------------|-----------|------------|--------|\n| [Target] | XX% | [Key strength] | [Key weakness] | [4] |\n| Competitor 1 | XX% | [Key strength] | [Key weakness] | [4] |\n| Competitor 2 | XX% | [Key strength] | [Key weakness] | [4] |\n\n[1-2 paragraphs on competitive threats and defensive positioning]\n\n### Competitive Moat Assessment\n\n[1-2 paragraphs assessing durability of competitive advantages]\n- Switching costs\n- Network effects\n- Cost advantages\n- Intangible assets\n- Efficient scale\n\n---\n\n## Risk Factors\n\n\u003c!-- CRITICAL: Include specific, material risks with potential impact -->\n\n### Business Risks\n\n**Risk 1: [Specific Risk Name]**\n- Description: [What is the risk]\n- Probability: [High/Medium/Low]\n- Impact: [Potential financial impact]\n- Mitigation: [How company addresses it]\n- Source: [N]\n\n**Risk 2: [Specific Risk Name]**\n- [Same structure]\n\n### Financial Risks\n\n**Risk 1: [Specific Risk Name]**\n- [Same structure as above]\n\n### Regulatory Risks\n\n**Risk 1: [Specific Risk Name]**\n- [Same structure as above]\n\n### Market Risks\n\n**Risk 1: [Specific Risk Name]**\n- [Same structure as above]\n\n### Risk Summary Matrix\n\n| Risk | Probability | Impact | Overall | Mitigation |\n|------|-------------|--------|---------|------------|\n| [Risk 1] | High/Med/Low | High/Med/Low | [Score] | [Brief] |\n| [Risk 2] | High/Med/Low | High/Med/Low | [Score] | [Brief] |\n\n---\n\n## Investment Thesis\n\n### Bull Case\n\n**Thesis:** [One sentence summary of bull case]\n\n**Key Assumptions:**\n1. [Assumption 1 with supporting evidence]\n2. [Assumption 2 with supporting evidence]\n3. [Assumption 3 with supporting evidence]\n\n**Implied Valuation:** [Target price and upside]\n\n### Base Case\n\n**Thesis:** [One sentence summary of base case]\n\n**Key Assumptions:**\n1. [Assumption 1]\n2. [Assumption 2]\n3. [Assumption 3]\n\n**Implied Valuation:** [Target price and expected return]\n\n### Bear Case\n\n**Thesis:** [One sentence summary of bear case]\n\n**Key Assumptions:**\n1. [Assumption 1]\n2. [Assumption 2]\n3. [Assumption 3]\n\n**Implied Valuation:** [Target price and downside]\n\n---\n\n## Recommendations\n\n### Immediate Actions\n\n1. **[Action Title]**\n - What: [Specific action]\n - Why: [Rationale based on findings]\n - Priority: [High/Medium/Low]\n\n2. **[Action Title]**\n - [Same structure]\n\n### Catalysts to Watch\n\n| Catalyst | Expected Date | Potential Impact | Source |\n|----------|---------------|------------------|--------|\n| [Event 1] | [Date/Quarter] | [Impact description] | [N] |\n| [Event 2] | [Date/Quarter] | [Impact description] | [N] |\n\n### Further Research Needs\n\n1. **[Research Topic]**\n - What to investigate: [Specific question]\n - Why it matters: [Connection to thesis]\n\n---\n\n## Bibliography\n\n\u003c!-- ============================================================================ -->\n\u003c!-- CRITICAL: Generate COMPLETE bibliography with ALL sources cited in report -->\n\u003c!-- DO NOT use placeholders like \"[8-75] Additional citations\" or \"etc.\" -->\n\u003c!-- EVERY citation [N] in report body MUST have corresponding entry here -->\n\u003c!-- Format: [N] Source (Date). \"Title\". Publication/Filing. URL -->\n\u003c!-- ============================================================================ -->\n\n### Tier 1 Sources (Regulatory/Primary)\n\n[1] Company Name (2024). \"Form 10-K Annual Report\". SEC EDGAR. https://www.sec.gov/... (Retrieved: 2025-01-06)\n\n[2] Company Name (2024). \"Q3 2024 Earnings Release\". Company IR. https://ir.company.com/... (Retrieved: 2025-01-06)\n\n### Tier 2 Sources (Data Providers)\n\n[3] S&P Capital IQ (2024). \"Company Financial Data\". S&P Global. (Retrieved: 2025-01-06)\n\n### Tier 3 Sources (Financial News/Research)\n\n[4] Author Name (2024). \"Article Title\". Wall Street Journal. https://wsj.com/... (Retrieved: 2025-01-06)\n\n### Tier 4 Sources (General Business)\n\n[5] Author Name (2024). \"Article Title\". Source. https://... (Retrieved: 2025-01-06)\n\n\u003c!-- Continue with ALL remaining citations -->\n\n---\n\n## Appendix: Methodology\n\n### Research Process\n\n**Phase Execution:**\n- Phase 1 (SCOPE): [What was done]\n- Phase 2 (PLAN): [What was done]\n- Phase 3 (RETRIEVE): [What was done]\n- [Continue for all phases executed]\n\n### Sources Consulted\n\n**Total Sources:** [Number]\n\n**Source Tier Breakdown:**\n- Tier 1 (Regulatory/Primary): [Number]\n- Tier 2 (Data Providers): [Number]\n- Tier 3 (Financial News): [Number]\n- Tier 4 (General Business): [Number]\n\n**Average Credibility Score:** [Number]/100\n\n### Verification Approach\n\n**Triangulation:**\n- Core financial claims verified across 2+ sources\n- Primary source (SEC filing) used for all key metrics\n- Analyst estimates cross-referenced\n\n**Quality Control:**\n- Validation checks performed\n- Issues found and corrected\n- Final quality metrics\n\n### Claims-Evidence Table\n\n| Claim ID | Major Financial Claim | Evidence Type | Sources | Confidence |\n|----------|----------------------|---------------|---------|------------|\n| C1 | [First major claim] | SEC Filing | [1], [2] | High |\n| C2 | [Second major claim] | Data Provider | [3], [4] | High |\n| C3 | [Third major claim] | Analyst Research | [5] | Medium |\n\n---\n\n## Report Metadata\n\n**Research Mode:** [Quick/Standard/Deep/UltraDeep]\n**Total Sources:** [Number]\n**Tier 1 Sources:** [Number]\n**Word Count:** [Approximate count]\n**Research Duration:** [Time taken]\n**Generated:** [Date and time]\n**Validation Status:** [Passed with X warnings / Passed without warnings]\n\n---\n\n\u003c!-- END OF TEMPLATE -->\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":11055,"content_sha256":"fa7770b0929cfacfc19021781a9a8379a324d9030f511261376cd8b7362bddb1"}],"content_json":{"type":"doc","content":[{"type":"heading","attrs":{"level":1},"content":[{"text":"Financial Deep Research","type":"text"}]},{"type":"paragraph","content":[{"text":"\u003c!-- STATIC CONTEXT BLOCK START - Optimized for prompt caching --> \u003c!-- All static instructions, methodology, and templates below this line --> \u003c!-- Dynamic content (user queries, results) added after this block -->","type":"text"}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"Core System Instructions","type":"text"}]},{"type":"paragraph","content":[{"text":"Purpose:","type":"text","marks":[{"type":"strong"}]},{"text":" Deliver citation-backed, verified financial research reports through 8-phase pipeline (Scope > Plan > Retrieve > Triangulate > Synthesize > Critique > Refine > Package) with financial source credibility scoring, regulatory compliance tracking, and progressive context management.","type":"text"}]},{"type":"paragraph","content":[{"text":"Financial Focus:","type":"text","marks":[{"type":"strong"}]},{"text":" This skill specializes in:","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Market analysis and investment research","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Due diligence and competitive benchmarking","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Regulatory compliance and risk assessment","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Financial modeling support and valuation analysis","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Earnings analysis and financial statement review","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Sector/industry deep dives","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"Context Strategy:","type":"text","marks":[{"type":"strong"}]},{"text":" This skill uses 2025 context engineering best practices:","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Static instructions cached (this section)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Progressive disclosure (load references only when needed)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Avoid \"loss in the middle\" (critical info at start/end, not buried)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Explicit section markers for context navigation","type":"text"}]}]}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"Decision Tree (Execute First)","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":""},"content":[{"text":"Request Analysis\n|-- Simple stock quote? -> STOP: Use WebSearch, not this skill\n|-- Basic company lookup? -> STOP: Use WebSearch, not this skill\n|-- Debugging code? -> STOP: Use standard tools, not this skill\n+-- Complex financial analysis needed? -> CONTINUE\n\nMode Selection\n|-- Quick market check? -> quick (3 phases, 2-5 min)\n|-- Standard analysis? -> standard (6 phases, 5-10 min) [DEFAULT]\n|-- Investment decision? -> deep (8 phases, 10-20 min)\n|-- Due diligence/M&A? -> ultradeep (8+ phases, 20-45 min)\n\nExecution Loop (per phase)\n|-- Load phase instructions from [methodology](./reference/methodology.md#phase-N)\n|-- Execute phase tasks\n|-- Spawn parallel agents if applicable\n+-- Update progress\n\nValidation Gate\n|-- Run `python scripts/validate_report.py --report [path]`\n|-- Pass? -> Deliver\n+-- Fail? -> Fix (max 2 attempts) -> Still fails? -> Escalate","type":"text"}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"Workflow (Clarify > Plan > Act > Verify > Report)","type":"text"}]},{"type":"paragraph","content":[{"text":"AUTONOMY PRINCIPLE:","type":"text","marks":[{"type":"strong"}]},{"text":" This skill operates independently. Infer assumptions from query context. Only stop for critical errors or incomprehensible queries.","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"1. Clarify (Rarely Needed - Prefer Autonomy)","type":"text"}]},{"type":"paragraph","content":[{"text":"DEFAULT: Proceed autonomously. Derive assumptions from query signals.","type":"text","marks":[{"type":"strong"}]}]},{"type":"paragraph","content":[{"text":"ONLY ask if CRITICALLY ambiguous:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Query is incomprehensible (e.g., \"analyze the thing\")","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Contradictory requirements (e.g., \"quick 50-source ultradeep analysis\")","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Critical compliance/regulatory scope unclear","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"When in doubt: PROCEED with standard mode. User will redirect if incorrect.","type":"text","marks":[{"type":"strong"}]}]},{"type":"paragraph","content":[{"text":"Default assumptions:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Company analysis -> Assume investor/analyst audience","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Sector query -> Assume comprehensive market view needed","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Valuation query -> Assume institutional-quality analysis","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Regulatory query -> Assume US jurisdiction unless specified","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Standard mode is default for most queries","type":"text"}]}]}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":3},"content":[{"text":"2. Plan","type":"text"}]},{"type":"paragraph","content":[{"text":"Mode selection criteria:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Quick","type":"text","marks":[{"type":"strong"}]},{"text":" (2-5 min): Market snapshot, earnings preview, quick check","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Standard","type":"text","marks":[{"type":"strong"}]},{"text":" (5-10 min): Most analysis, balanced depth/speed [DEFAULT]","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Deep","type":"text","marks":[{"type":"strong"}]},{"text":" (10-20 min): Investment decisions, detailed due diligence","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"UltraDeep","type":"text","marks":[{"type":"strong"}]},{"text":" (20-45 min): M&A due diligence, comprehensive sector analysis","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"Announce plan and execute:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Briefly state: selected mode, estimated time, number of sources","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Example: \"Starting standard mode financial research (5-10 min, 15-30 sources)\"","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Proceed without waiting for approval","type":"text"}]}]}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":3},"content":[{"text":"3. Act (Phase Execution)","type":"text"}]},{"type":"paragraph","content":[{"text":"All modes execute:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Phase 1: SCOPE - Define financial analysis boundaries (","type":"text"},{"text":"method","type":"text","marks":[{"type":"link","attrs":{"href":"./reference/methodology.md#phase-1-scope","title":null}}]},{"text":")","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Phase 3: RETRIEVE - Parallel financial data gathering (5-10 concurrent searches + agents) (","type":"text"},{"text":"method","type":"text","marks":[{"type":"link","attrs":{"href":"./reference/methodology.md#phase-3-retrieve---parallel-information-gathering","title":null}}]},{"text":")","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Phase 8: PACKAGE - Generate report using ","type":"text"},{"text":"template","type":"text","marks":[{"type":"link","attrs":{"href":"./templates/report_template.md","title":null}}]}]}]}]},{"type":"paragraph","content":[{"text":"Standard/Deep/UltraDeep execute:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Phase 2: PLAN - Financial research strategy formulation","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Phase 4: TRIANGULATE - Verify 3+ sources per financial claim","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Phase 4.5: OUTLINE REFINEMENT - Adapt structure based on evidence (WebWeaver 2025) (","type":"text"},{"text":"method","type":"text","marks":[{"type":"link","attrs":{"href":"./reference/methodology.md#phase-45-outline-refinement---dynamic-evolution-webweaver-2025","title":null}}]},{"text":")","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Phase 5: SYNTHESIZE - Generate investment insights","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"Deep/UltraDeep execute:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Phase 6: CRITIQUE - Risk analysis and bear case","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Phase 7: REFINE - Address gaps, strengthen thesis","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"Critical: Avoid \"Loss in the Middle\"","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Place key findings at START and END of sections, not buried","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Use explicit headers and markers","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Structure: Summary > Details > Conclusion (not Details sandwiched)","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"Progressive Context Loading:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Load ","type":"text"},{"text":"methodology","type":"text","marks":[{"type":"link","attrs":{"href":"./reference/methodology.md","title":null}}]},{"text":" sections on-demand","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Load ","type":"text"},{"text":"template","type":"text","marks":[{"type":"link","attrs":{"href":"./templates/report_template.md","title":null}}]},{"text":" only for Phase 8","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Do not inline everything - reference external files","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"Anti-Hallucination Protocol (CRITICAL for Financial Data):","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Source grounding","type":"text","marks":[{"type":"strong"}]},{"text":": Every financial claim MUST cite a specific source immediately [N]","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Clear boundaries","type":"text","marks":[{"type":"strong"}]},{"text":": Distinguish between FACTS (from filings/data) and ANALYSIS (your interpretation)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Explicit markers","type":"text","marks":[{"type":"strong"}]},{"text":": Use \"According to [1]...\" or \"[1] reports...\" for source-grounded statements","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"No speculation without labeling","type":"text","marks":[{"type":"strong"}]},{"text":": Mark inferences as \"This suggests...\" not \"Data shows...\"","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Verify before citing","type":"text","marks":[{"type":"strong"}]},{"text":": If unsure whether source actually says X, do NOT fabricate citation","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"When uncertain","type":"text","marks":[{"type":"strong"}]},{"text":": Say \"No sources found for X\" rather than inventing references","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Financial precision","type":"text","marks":[{"type":"strong"}]},{"text":": Always include specific numbers, dates, and currency when available","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"Parallel Execution Requirements (CRITICAL for Speed):","type":"text","marks":[{"type":"strong"}]}]},{"type":"paragraph","content":[{"text":"Phase 3 RETRIEVE - Mandatory Parallel Financial Search:","type":"text","marks":[{"type":"strong"}]}]},{"type":"ordered_list","attrs":{"order":1,"listStyle":"number"},"content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Decompose query","type":"text","marks":[{"type":"strong"}]},{"text":" into 5-10 independent search angles before ANY searches","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Launch ALL searches in single message","type":"text","marks":[{"type":"strong"}]},{"text":" with multiple tool calls (NOT sequential)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Quality threshold monitoring","type":"text","marks":[{"type":"strong"}]},{"text":" for FFS pattern:","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Track source count and avg credibility score","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Proceed when threshold reached (mode-specific, see methodology)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Continue background searches for additional depth","type":"text"}]}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Spawn 3-5 parallel agents","type":"text","marks":[{"type":"strong"}]},{"text":" using Task tool for deep-dive investigations","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"Financial Search Decomposition Strategy:","type":"text","marks":[{"type":"strong"}]}]},{"type":"code_block","attrs":{"wrap":false,"language":""},"content":[{"text":"[Single message with 8+ parallel tool calls]\nWebSearch #1: Company fundamentals + recent filings\nWebSearch #2: Earnings/financial performance\nWebSearch #3: Industry/sector analysis\nWebSearch #4: Competitive landscape\nWebSearch #5: Regulatory/compliance news\nWebSearch #6: Analyst ratings/price targets\nWebSearch #7: Risk factors/bear case\nWebSearch #8: Recent news + catalysts\nTask agent #1: SEC filing deep dive (10-K, 10-Q analysis)\nTask agent #2: Financial statement analysis\nTask agent #3: Industry comparison/benchmarking","type":"text"}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":3},"content":[{"text":"4. Verify (Always Execute)","type":"text"}]},{"type":"paragraph","content":[{"text":"Step 1: Citation Verification (Catches Fabricated Sources)","type":"text","marks":[{"type":"strong"}]}]},{"type":"code_block","attrs":{"wrap":false,"language":"bash"},"content":[{"text":"python scripts/verify_citations.py --report [path]","type":"text"}]},{"type":"paragraph","content":[{"text":"Financial-Specific Checks:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"SEC filing references (verify EDGAR links)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Financial data accuracy (cross-check key metrics)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Date accuracy (earnings dates, filing dates)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Flags suspicious entries (future financials, impossible metrics)","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"If suspicious citations found:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Review flagged entries manually","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Remove or replace fabricated sources","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Re-run until clean","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"Step 2: Structure & Quality Validation","type":"text","marks":[{"type":"strong"}]}]},{"type":"code_block","attrs":{"wrap":false,"language":"bash"},"content":[{"text":"python scripts/validate_report.py --report [path]","type":"text"}]},{"type":"paragraph","content":[{"text":"9 automated checks (financial-enhanced):","type":"text","marks":[{"type":"strong"}]}]},{"type":"ordered_list","attrs":{"order":1,"listStyle":"number"},"content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Executive summary length (50-250 words)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Required sections present (+ recommended: Risk Factors, Valuation)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Citations formatted [1], [2], [3]","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Bibliography matches citations","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"No placeholder text (TBD, TODO)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Word count reasonable (500-10000)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Minimum 10 sources","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"No broken internal links","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Financial data consistency (dates, currencies, units)","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"If fails:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Attempt 1: Auto-fix formatting/links","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Attempt 2: Manual review + correction","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"After 2 failures: ","type":"text"},{"text":"STOP","type":"text","marks":[{"type":"strong"}]},{"text":" > Report issues > Ask user","type":"text"}]}]}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":3},"content":[{"text":"5. Report","type":"text"}]},{"type":"paragraph","content":[{"text":"CRITICAL: Generate COMPREHENSIVE, DETAILED financial markdown reports","type":"text","marks":[{"type":"strong"}]}]},{"type":"paragraph","content":[{"text":"File Organization (CRITICAL - Clean Accessibility):","type":"text","marks":[{"type":"strong"}]}]},{"type":"paragraph","content":[{"text":"1. Create Organized Folder in /code:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"ALWAYS create dedicated folder: ","type":"text"},{"text":"/code/[TickerOrTopic]_Financial_Research_[YYYYMMDD]/","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Extract clean topic name from research question","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Examples:","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"\"AAPL investment analysis\" -> ","type":"text"},{"text":"/code/AAPL_Financial_Research_20251104/","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"\"compare cloud providers\" -> ","type":"text"},{"text":"/code/Cloud_Sector_Analysis_20251104/","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"\"fintech due diligence\" -> ","type":"text"},{"text":"/code/Fintech_Due_Diligence_20251104/","type":"text","marks":[{"type":"code_inline"}]}]}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"If folder exists, use it; if not, create it","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"This ensures clean organization and easy accessibility","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"2. Save All Formats to Same Folder:","type":"text","marks":[{"type":"strong"}]}]},{"type":"paragraph","content":[{"text":"Markdown (Primary Source):","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Save to: ","type":"text"},{"text":"[Documents folder]/financial_report_[YYYYMMDD]_[topic_slug].md","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Also save copy to: ","type":"text"},{"text":"/code/research_output/","type":"text","marks":[{"type":"code_inline"}]},{"text":" (internal tracking)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Full detailed report with all findings","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"HTML (McKinsey Style - ALWAYS GENERATE):","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Save to: ","type":"text"},{"text":"[Documents folder]/financial_report_[YYYYMMDD]_[topic_slug].html","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Use McKinsey template: ","type":"text"},{"text":"mckinsey_template","type":"text","marks":[{"type":"link","attrs":{"href":"./templates/mckinsey_report_template.html","title":null}}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Design principles: Sharp corners (NO border-radius), muted corporate colors (navy #003d5c, gray #f8f9fa), ultra-compact layout, info-first structure","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Place critical financial metrics dashboard at top (extract 3-4 key metrics: market cap, P/E, revenue growth, etc.)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Use data tables for dense financial information","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"14px base font, compact spacing, no decorative gradients or colors","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"OPEN in browser automatically after generation","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"PDF (Professional Print - ALWAYS GENERATE):","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Save to: ","type":"text"},{"text":"[Documents folder]/financial_report_[YYYYMMDD]_[topic_slug].pdf","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Use generating-pdf skill (via Task tool with general-purpose agent)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Professional formatting with headers, page numbers","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"OPEN in default PDF viewer after generation","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"3. File Naming Convention:","type":"text","marks":[{"type":"strong"}]},{"text":" All files use same base name for easy matching:","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"financial_report_20251104_aapl_analysis.md","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"financial_report_20251104_aapl_analysis.html","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"financial_report_20251104_aapl_analysis.pdf","type":"text","marks":[{"type":"code_inline"}]}]}]}]},{"type":"paragraph","content":[{"text":"Length Requirements (UNLIMITED with Progressive Assembly):","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Quick mode: 2,000+ words (baseline quality threshold)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Standard mode: 4,000+ words (comprehensive analysis)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Deep mode: 6,000+ words (thorough investigation)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"UltraDeep mode: 10,000-50,000+ words (NO UPPER LIMIT)","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"How Unlimited Length Works:","type":"text","marks":[{"type":"strong"}]},{"text":" Progressive file assembly allows ANY report length by generating section-by-section. Each section is written to file immediately (avoiding output token limits). Complex analyses with many findings? Generate 20, 30, 50+ findings - no constraint!","type":"text"}]},{"type":"paragraph","content":[{"text":"Content Requirements:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Use ","type":"text"},{"text":"template","type":"text","marks":[{"type":"link","attrs":{"href":"./templates/report_template.md","title":null}}]},{"text":" as exact structure","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Generate each section to APPROPRIATE depth (determined by evidence, not word targets)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Include specific financial data, statistics, dates, numbers","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Multiple paragraphs per finding with evidence","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Each section gets focused generation attention","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"DO NOT write summaries - write FULL analysis","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"Writing Standards (Financial Precision):","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Data-driven","type":"text","marks":[{"type":"strong"}]},{"text":": Every claim backed by specific numbers from sources","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Precision","type":"text","marks":[{"type":"strong"}]},{"text":": Exact figures with currency, dates, and units","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Economy","type":"text","marks":[{"type":"strong"}]},{"text":": No fluff, eliminate unnecessary modifiers","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Clarity","type":"text","marks":[{"type":"strong"}]},{"text":": Financial terminology used correctly and consistently","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Directness","type":"text","marks":[{"type":"strong"}]},{"text":": State findings without embellishment","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"High signal-to-noise","type":"text","marks":[{"type":"strong"}]},{"text":": Dense information, respect reader's time","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Examples","type":"text","marks":[{"type":"strong"}]},{"text":":","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Bad: \"revenue increased significantly\" -> Good: \"revenue grew 23% YoY to $94.8B in FY2024 [1]\"","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Bad: \"strong margins\" -> Good: \"gross margin of 43.2%, up 180bps YoY [2]\"","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Bad: \"expensive valuation\" -> Good: \"trades at 28x forward P/E vs sector median 22x [3]\"","type":"text"}]}]}]}]}]},{"type":"paragraph","content":[{"text":"Source Attribution Standards (Critical for Financial Research):","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Immediate citation","type":"text","marks":[{"type":"strong"}]},{"text":": Every financial claim followed by [N] citation in same sentence","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Quote sources directly","type":"text","marks":[{"type":"strong"}]},{"text":": Use \"According to [1]...\" or \"[1] reports...\" for factual statements","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Distinguish fact from analysis","type":"text","marks":[{"type":"strong"}]},{"text":":","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"GOOD: \"Q3 revenue was $24.9B, up 8% YoY [1].\"","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"BAD: \"Revenue grew strongly last quarter.\"","type":"text"}]}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"No vague attributions","type":"text","marks":[{"type":"strong"}]},{"text":":","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"NEVER: \"Analysts believe...\", \"Market expects...\", \"Sources indicate...\"","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"ALWAYS: \"Goldman Sachs estimates...\" [1], \"Per SEC 10-K filing...\" [2]","type":"text"}]}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Label speculation explicitly","type":"text","marks":[{"type":"strong"}]},{"text":":","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"GOOD: \"This suggests potential margin expansion...\" (analysis, not fact)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"BAD: \"Margins will expand...\" (presented as fact without citation)","type":"text"}]}]}]}]}]},{"type":"paragraph","content":[{"text":"Deliver to user:","type":"text","marks":[{"type":"strong"}]}]},{"type":"ordered_list","attrs":{"order":1,"listStyle":"number"},"content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Executive summary with key investment thesis (inline in chat)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Organized folder path (e.g., \"All files saved to: /code/AAPL_Financial_Research_20251104/\")","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Confirmation of all three formats generated:","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Markdown (source)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"HTML (McKinsey-style, opened in browser)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"PDF (professional print, opened in viewer)","type":"text"}]}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Source quality assessment summary (source count, regulatory vs news mix)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Key financial metrics summary","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Risk factors summary","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Next steps (if relevant)","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"Generation Workflow: Progressive File Assembly (Unlimited Length)","type":"text","marks":[{"type":"strong"}]}]},{"type":"paragraph","content":[{"text":"[Same progressive assembly workflow as base skill - see deep-research SKILL.md]","type":"text"}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"Financial Data Sources (Priority Order)","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Tier 1: Primary/Regulatory Sources (Highest Credibility)","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"SEC EDGAR","type":"text","marks":[{"type":"strong"}]},{"text":": 10-K, 10-Q, 8-K, proxy statements, insider filings","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Federal Reserve","type":"text","marks":[{"type":"strong"}]},{"text":": FRED data, monetary policy, banking data","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"FDIC/OCC","type":"text","marks":[{"type":"strong"}]},{"text":": Banking regulation, call reports","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Treasury","type":"text","marks":[{"type":"strong"}]},{"text":": Economic data, fiscal policy","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Company IR","type":"text","marks":[{"type":"strong"}]},{"text":": Investor relations, earnings calls, presentations","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Exchange Filings","type":"text","marks":[{"type":"strong"}]},{"text":": NYSE, NASDAQ company disclosures","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Tier 2: Financial Data Providers (High Credibility)","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Bloomberg","type":"text","marks":[{"type":"strong"}]},{"text":": Real-time data, analysis, news","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Reuters","type":"text","marks":[{"type":"strong"}]},{"text":": News, data, analysis","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"S&P Global","type":"text","marks":[{"type":"strong"}]},{"text":": Ratings, research, Capital IQ data","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Moody's/Fitch","type":"text","marks":[{"type":"strong"}]},{"text":": Credit ratings, research","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"FactSet","type":"text","marks":[{"type":"strong"}]},{"text":": Financial data, analytics","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Morningstar","type":"text","marks":[{"type":"strong"}]},{"text":": Fund data, equity research","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"PitchBook","type":"text","marks":[{"type":"strong"}]},{"text":": Private market data, VC/PE","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Tier 3: Financial News & Research (Moderate-High Credibility)","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Wall Street Journal","type":"text","marks":[{"type":"strong"}]},{"text":": Business news, analysis","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Financial Times","type":"text","marks":[{"type":"strong"}]},{"text":": Global finance news","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Barron's","type":"text","marks":[{"type":"strong"}]},{"text":": Investment analysis","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Institutional research","type":"text","marks":[{"type":"strong"}]},{"text":": Goldman, Morgan Stanley, JPM research","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Industry publications","type":"text","marks":[{"type":"strong"}]},{"text":": American Banker, Insurance Journal","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Tier 4: General Business Sources (Moderate Credibility)","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"CNBC, Yahoo Finance","type":"text","marks":[{"type":"strong"}]},{"text":": Market news (verify with primary sources)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Seeking Alpha","type":"text","marks":[{"type":"strong"}]},{"text":": Analysis (note: user-generated, verify claims)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Industry blogs","type":"text","marks":[{"type":"strong"}]},{"text":": Supplement only, not primary citation","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"Source Verification Requirements:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Tier 1 sources: Can cite directly, highest trust","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Tier 2 sources: Reliable, cross-check major claims","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Tier 3 sources: Good for analysis, verify data with Tier 1-2","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Tier 4 sources: Use sparingly, always verify with higher tiers","type":"text"}]}]}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"Output Contract","type":"text"}]},{"type":"paragraph","content":[{"text":"Format:","type":"text","marks":[{"type":"strong"}]},{"text":" Comprehensive financial markdown report following ","type":"text"},{"text":"template","type":"text","marks":[{"type":"link","attrs":{"href":"./templates/report_template.md","title":null}}]},{"text":" EXACTLY","type":"text"}]},{"type":"paragraph","content":[{"text":"Required sections (all must be detailed):","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Executive Summary with Investment Thesis (50-250 words)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Company/Topic Overview (background, business model)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Financial Analysis (revenue, margins, cash flow, balance sheet)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Valuation Analysis (multiples, DCF if applicable, peer comparison)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Competitive Position (market share, moat, competitive dynamics)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Risk Factors (business, financial, regulatory, market risks)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Investment Thesis / Recommendations","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Bibliography (CRITICAL - see rules below)","type":"text","marks":[{"type":"strong"}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Methodology Appendix","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"Financial-Specific Sections (include when relevant):","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Earnings Analysis (quarterly trends, guidance vs actual)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Management Assessment (track record, insider activity)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Regulatory Environment (compliance, pending regulation)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"ESG Considerations (if material to thesis)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Catalyst Timeline (upcoming events, catalysts)","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"Bibliography Requirements (ZERO TOLERANCE):","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"MUST include EVERY citation [N] used in report body","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Format: [N] Source (Date). \"Title\". Publication/Filing. URL (Retrieved: Date)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Each entry on its own line, complete with all metadata","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"NO placeholders, NO ranges, NO truncation","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Validation WILL FAIL if bibliography is incomplete","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"Strictly Prohibited:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Placeholder text (TBD, TODO, [citation needed])","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Uncited financial claims","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Forward-looking statements presented as facts","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Broken links","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Missing required sections","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Short summaries instead of detailed analysis","type":"text","marks":[{"type":"strong"}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Vague statements without specific data","type":"text","marks":[{"type":"strong"}]}]}]}]},{"type":"paragraph","content":[{"text":"Quality gates (enforced by validator):","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Minimum 2,000 words (standard mode)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Average credibility score >70/100 (higher bar for financial)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"3+ sources per major financial claim","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Clear facts vs. analysis distinction","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"All sections present and detailed","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Key financial metrics included with sources","type":"text"}]}]}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"Error Handling & Stop Rules","type":"text"}]},{"type":"paragraph","content":[{"text":"Stop immediately if:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"2 validation failures on same error > Pause, report, ask user","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"\u003c5 sources after exhaustive search > Report limitation, request direction","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Critical financial data unavailable > Note gap, proceed with caveats","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"User interrupts/changes scope > Confirm new direction","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"Graceful degradation:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"5-10 sources > Note in limitations, proceed with extra verification","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Missing recent filing > Note, use most recent available","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Private company (limited data) > Acknowledge, use available sources","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Time constraint reached > Package partial results, document gaps","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"Error format:","type":"text","marks":[{"type":"strong"}]}]},{"type":"code_block","attrs":{"wrap":false,"language":""},"content":[{"text":"Issue: [Description]\nContext: [What was attempted]\nTried: [Resolution attempts]\nOptions:\n 1. [Option 1]\n 2. [Option 2]\n 3. [Option 3]","type":"text"}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"Quality Standards (Always Enforce)","type":"text"}]},{"type":"paragraph","content":[{"text":"Every financial report must:","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"10+ sources (document if fewer)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"3+ sources per major financial claim","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Executive summary \u003c250 words with clear thesis","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Full citations with URLs to filings/sources","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Credibility assessment (source tier breakdown)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Risk factors section","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Methodology documented","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Key metrics with sources","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"No placeholders","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"Priority:","type":"text","marks":[{"type":"strong"}]},{"text":" Accuracy over speed. Financial data must be verified.","type":"text"}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"Inputs & Assumptions","type":"text"}]},{"type":"paragraph","content":[{"text":"Required:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Financial research question (string)","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"Optional:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Mode (quick/standard/deep/ultradeep)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Time constraints","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Specific data requirements (valuation focus, risk focus, etc.)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Output format preferences","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Jurisdiction (default: US)","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"Assumptions:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"User requires verified, citation-backed financial information","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Institutional-quality analysis expected","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"10-50 sources available on topic","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Time investment: 5-45 minutes","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"USD unless otherwise specified","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"US regulatory framework unless specified","type":"text"}]}]}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"When to Use / NOT Use","type":"text"}]},{"type":"paragraph","content":[{"text":"Use when:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Investment analysis (buy/sell/hold thesis)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Company due diligence","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Sector/industry deep dives","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"M&A analysis","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Competitive benchmarking","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Earnings analysis","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Regulatory impact assessment","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Financial modeling research","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"Do NOT use:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Simple stock quotes (use WebSearch)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Basic company lookups (use WebSearch)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Real-time trading decisions (need live data)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Personal financial advice (not qualified)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Tax/legal advice (not qualified)","type":"text"}]}]}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"Scripts (Offline, Python stdlib only)","type":"text"}]},{"type":"paragraph","content":[{"text":"Location:","type":"text","marks":[{"type":"strong"}]},{"text":" ","type":"text"},{"text":"./scripts/","type":"text","marks":[{"type":"code_inline"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"research_engine.py","type":"text","marks":[{"type":"strong"}]},{"text":" - Orchestration engine","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"validate_report.py","type":"text","marks":[{"type":"strong"}]},{"text":" - Quality validation (9 checks, financial-enhanced)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"citation_manager.py","type":"text","marks":[{"type":"strong"}]},{"text":" - Citation tracking","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"source_evaluator.py","type":"text","marks":[{"type":"strong"}]},{"text":" - Financial source credibility scoring (0-100)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"verify_citations.py","type":"text","marks":[{"type":"strong"}]},{"text":" - Citation verification with SEC filing checks","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"No external dependencies required.","type":"text","marks":[{"type":"strong"}]}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"Progressive References (Load On-Demand)","type":"text"}]},{"type":"paragraph","content":[{"text":"Do not inline these - reference only:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Complete Methodology","type":"text","marks":[{"type":"link","attrs":{"href":"./reference/methodology.md","title":null}}]},{"text":" - 8-phase details with financial focus","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Report Template","type":"text","marks":[{"type":"link","attrs":{"href":"./templates/report_template.md","title":null}}]},{"text":" - Financial output structure","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"README","type":"text","marks":[{"type":"link","attrs":{"href":"./README.md","title":null}}]},{"text":" - Usage docs","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"QUICK_START","type":"text","marks":[{"type":"link","attrs":{"href":"./QUICK_START.md","title":null}}]},{"text":" - Fast reference","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"Context Management:","type":"text","marks":[{"type":"strong"}]},{"text":" Load files on-demand for current phase only. Do not preload all content.","type":"text"}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"paragraph","content":[{"text":"\u003c!-- STATIC CONTEXT BLOCK END --> \u003c!-- Above content is cacheable (>1024 tokens, static) --> \u003c!-- Below: Dynamic content (user queries, retrieved data, generated reports) --> \u003c!-- This structure enables 85% latency reduction via prompt caching -->","type":"text"}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"Dynamic Execution Zone","type":"text"}]},{"type":"paragraph","content":[{"text":"User Query Processing:","type":"text","marks":[{"type":"strong"}]},{"text":" [User financial research question will be inserted here during execution]","type":"text"}]},{"type":"paragraph","content":[{"text":"Retrieved Information:","type":"text","marks":[{"type":"strong"}]},{"text":" [Search results and sources will be accumulated here]","type":"text"}]},{"type":"paragraph","content":[{"text":"Generated Analysis:","type":"text","marks":[{"type":"strong"}]},{"text":" [Findings, synthesis, and report content generated here]","type":"text"}]},{"type":"paragraph","content":[{"text":"Note:","type":"text","marks":[{"type":"strong"}]},{"text":" This section remains empty in the skill definition. Content populated during runtime only.","type":"text"}]}]},"metadata":{"date":"2026-11-02","name":"financial-deep-research","author":"@skillopedia","source":{"stars":18,"repo_name":"rebyte-skills","origin_url":"https://github.com/rebyteai-template/rebyte-skills/blob/HEAD/financial-deep-research/SKILL.md","repo_owner":"rebyteai-template","body_sha256":"118dbdcf485814031dc3baab59cb34759b921701990f259cffd596333497f958","cluster_key":"b096fc294bb931524c0f86fd12249da991813b77eff261121b74a18bda434e3e","clean_bundle":{"format":"clean-skill-bundle-v1","source":"rebyteai-template/rebyte-skills/financial-deep-research/SKILL.md","text_bytes":103400,"source_commit":"0062e44684f109fb580e67fe600f581e01fa7209","skills_sh_rank":13236,"attachment_count":11,"text_attachments":11,"attachment_storage":"skill_attachments","binary_attachments":0},"cluster_size":1,"skill_md_path":"financial-deep-research/SKILL.md","import_metadata":{"date":"2026-11-02","author":"@skillopedia","version":"v1","category":"finance-legal-compliance","category_label":"Finance"},"exact_dupes_collapsed_into_this":0},"version":"v1","category":"finance-legal-compliance","import_tag":"skills-sh-top20k-2026-11","description":"Conduct enterprise-grade financial research with multi-source synthesis, regulatory compliance tracking, and verified market analysis. Use when user needs comprehensive financial analysis requiring 10+ sources, verified claims, market comparisons, or investment research. Triggers include \"financial research\", \"market analysis\", \"investment analysis\", \"due diligence\", \"financial deep dive\", \"compare stocks/funds\", or \"analyze [company/sector]\". Do NOT use for simple stock quotes, basic company lookups, or questions answerable with 1-2 searches."}},"renderedAt":1793666513933}

Financial Deep Research <!-- STATIC CONTEXT BLOCK START - Optimized for prompt caching -- <!-- All static instructions, methodology, and templates below this line -- <!-- Dynamic content (user queries, results) added after this block -- Core System Instructions Purpose: Deliver citation-backed, verified financial research reports through 8-phase pipeline (Scope Plan Retrieve Triangulate Synthesize Critique Refine Package) with financial source credibility scoring, regulatory compliance tracking, and progressive context management. Financial Focus: This skill specializes in: - Market analysis…