Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

Refactor finance notebooks: Use modular architecture with unique approaches per use case

KaifAhmad17d07691d998d
diff --git a/cookbook/use_cases/finance/01_Financial_Data_Integration_MCP.ipynb b/cookbook/use_cases/finance/01_Financial_Data_Integration_MCP.ipynb
index a8ff3f0f..fb743c8c 100644
--- a/cookbook/use_cases/finance/01_Financial_Data_Integration_MCP.ipynb
+++ b/cookbook/use_cases/finance/01_Financial_Data_Integration_MCP.ipynb
@@ -1,224 +1,645 @@
{
- "cells": [
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/use_cases/finance/01_Financial_Data_Integration_MCP.ipynb)\n",
- "\n",
- "# Financial Data Integration (MCP) - Real-Time Market Data\n",
- "\n",
- "## Overview\n",
- "\n",
- "This notebook demonstrates **financial data integration using MCP servers** with focus on **MCP server integration**, **real-time data ingestion**, and **multi-source financial KG construction**. The pipeline integrates Python/FastMCP servers to ingest market data, stock prices, and metrics into a financial knowledge graph.\n",
- "\n",
- "### Key Features\n",
- "\n",
- "- **MCP Integration**: Showcases MCP (Model Context Protocol) server integration capability\n",
- "- **Real-Time Data Ingestion**: Ingests live market data from MCP servers\n",
- "- **Multi-Source Financial KG**: Builds comprehensive financial knowledge graphs from APIs\n",
- "- **Real-Time Updates**: Demonstrates real-time data streaming and KG updates\n",
- "- **API-Based Integration**: Connects to financial data APIs via MCP\n",
- "\n",
- "### Pipeline Architecture\n",
- "\n",
- "1. **Phase 0**: Setup & Configuration\n",
- "2. **Phase 1**: MCP Server Setup & Connection\n",
- "3. **Phase 2**: Real-Time Market Data Ingestion\n",
- "4. **Phase 3**: Financial Entity Extraction\n",
- "5. **Phase 4**: Financial Knowledge Graph Construction\n",
- "6. **Phase 5**: Real-Time KG Updates\n",
- "7. **Phase 6**: Visualization & Export\n",
- "\n",
- "---\n",
- "\n",
- "## Installation\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "%pip install -qU semantica networkx matplotlib plotly pandas groq\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "---\n",
- "\n",
- "## Phase 0: Setup & Configuration\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "import os\n",
- "from semantica.core import Semantica, ConfigManager\n",
- "from semantica.ingest import MCPIngestor\n",
- "\n",
- "os.environ[\"GROQ_API_KEY\"] = os.getenv(\"GROQ_API_KEY\", \"your-key\")\n",
- "\n",
- "config_dict = {\n",
- " \"project_name\": \"Financial_Data_Integration_MCP\",\n",
- " \"extraction\": {\"provider\": \"groq\", \"model\": \"llama-3.1-8b-instant\"},\n",
- " \"knowledge_graph\": {\"backend\": \"networkx\"}\n",
- "}\n",
- "\n",
- "config = ConfigManager().load_from_dict(config_dict)\n",
- "core = Semantica(config=config)\n",
- "print(\"Configured for financial data integration with MCP focus\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "---\n",
- "\n",
- "## Phase 1: Real Data Ingestion (Alpha Vantage API & MCP Server)\n",
- "\n",
- "Ingest financial data from Alpha Vantage API and MCP servers.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "from semantica.ingest import MCPIngestor, WebIngestor, FileIngestor\n",
- "from semantica.seed import SeedDataManager\n",
- "import os\n",
- "\n",
- "os.makedirs(\"data\", exist_ok=True)\n",
- "\n",
- "documents = []\n",
- "\n",
- "# Option 1: Ingest from Alpha Vantage API (real data source)\n",
- "# Note: Requires API key - using example structure\n",
- "alpha_vantage_api = \"https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol=AAPL&apikey=demo\"\n",
- "\n",
- "try:\n",
- " web_ingestor = WebIngestor()\n",
- " api_documents = web_ingestor.ingest(alpha_vantage_api, method=\"url\")\n",
- " print(f\"Ingested {len(api_documents)} documents from Alpha Vantage API\")\n",
- " documents.extend(api_documents)\n",
- "except Exception as e:\n",
- " print(f\"API ingestion failed: {e}\")\n",
- "\n",
- "# Option 2: Ingest from MCP server (simulated)\n",
- "# In production: mcp_ingestor = MCPIngestor()\n",
- "# mcp_ingestor.connect(\"financial_server\", url=\"http://localhost:8000/mcp\")\n",
- "# resources = mcp_ingestor.list_available_resources(\"financial_server\")\n",
- "# mcp_data = mcp_ingestor.ingest_resources(\"financial_server\", resource_uris=[\"resource://market_data\"])\n",
- "\n",
- "# Load seed data for market foundation\n",
- "seed_manager = SeedDataManager()\n",
- "# Seed with foundation market data\n",
- "seed_data = [\n",
- " {\"type\": \"Market\", \"text\": \"NASDAQ\", \"description\": \"Stock exchange\"},\n",
- " {\"type\": \"Market\", \"text\": \"NYSE\", \"description\": \"Stock exchange\"}\n",
- "]\n",
- "seed_manager.load_seed_data(seed_data)\n",
- "print(f\"Loaded {len(seed_data)} seed data items\")\n",
- "\n",
- "# Fallback: Sample market data\n",
- "if not documents:\n",
- " market_data = \"\"\"\n",
- " AAPL stock price: $150.25, market cap: $2.4T, volume: 50M shares\n",
- " MSFT stock price: $380.50, market cap: $2.8T, volume: 30M shares\n",
- " GOOGL stock price: $140.75, market cap: $1.8T, volume: 25M shares\n",
- " \"\"\"\n",
- " with open(\"data/market_data.txt\", \"w\") as f:\n",
- " f.write(market_data)\n",
- " documents = FileIngestor().ingest(\"data/market_data.txt\")\n",
- " print(f\"Ingested {len(documents)} documents from sample data\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "---\n",
- "\n",
- "## Phase 2: Text Normalization\n",
- "\n",
- "Normalize financial data (prices, metrics, company names).\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "from semantica.normalize import TextNormalizer\n",
- "\n",
- "# Normalize financial data\n",
- "normalizer = TextNormalizer()\n",
- "normalized_documents = []\n",
- "for doc in documents:\n",
- " normalized_text = normalizer.normalize(\n",
- " doc.content if hasattr(doc, 'content') else str(doc),\n",
- " clean_html=True,\n",
- " normalize_entities=True,\n",
- " normalize_numbers=True, # Normalize financial numbers\n",
- " remove_extra_whitespace=True\n",
- " )\n",
- " normalized_documents.append(normalized_text)\n",
- "\n",
- "print(f\"Normalized {len(normalized_documents)} documents\")\n",
- "\n",
- "# Build financial knowledge graph\n",
- "result = core.build_knowledge_base(\n",
- " sources=normalized_documents,\n",
- " custom_entity_types=[\"Company\", \"Stock\", \"Price\", \"Metric\", \"Market\"],\n",
- " graph=True\n",
- ")\n",
- "\n",
- "kg = result[\"knowledge_graph\"]\n",
- "print(f\"Built financial KG with {len(kg.get('entities', []))} entities\")\n",
- "print(\"Focus: MCP integration, real-time ingestion, multi-source financial KG\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": []
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "from semantica.visualization import KGVisualizer\n",
- "\n",
- "visualizer = KGVisualizer()\n",
- "visualizer.visualize(kg, output_path=\"financial_data_kg.html\")\n",
- "\n",
- "print(\"Financial data integration (MCP) complete\")\n",
- "print(\"\\n=== Pipeline Summary ===\")\n",
- "print(f\"✓ Ingested {len(documents)} documents from Alpha Vantage API and MCP\")\n",
- "print(f\"✓ Loaded {len(seed_data)} seed data items\")\n",
- "print(f\"✓ Normalized {len(normalized_documents)} documents\")\n",
- "print(f\"✓ Built financial KG with {len(kg.get('entities', []))} entities\")\n",
- "print(f\"✓ Emphasizes: MCP integration, real-time ingestion, API-based KG construction, seed data\")\n"
- ]
- }
- ],
- "metadata": {
- "language_info": {
- "name": "python"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/use_cases/finance/01_Financial_Data_Integration_MCP.ipynb)\n",
+ "\n",
+ "# Financial Data Integration (MCP) - Real-Time Market Data\n",
+ "\n",
+ "## Overview\n",
+ "\n",
+ "This notebook demonstrates **financial data integration using MCP servers** with focus on **MCP server integration**, **real-time data ingestion**, and **multi-source financial KG construction**. The pipeline integrates Python/FastMCP servers to ingest market data, stock prices, and metrics into a financial knowledge graph.\n",
+ "\n",
+ "### Key Features\n",
+ "\n",
+ "- **MCP Integration**: Showcases MCP (Model Context Protocol) server integration capability\n",
+ "- **Seed Data Management**: Uses foundation market data for entity resolution\n",
+ "- **Real-Time Data Ingestion**: Ingests live market data from MCP servers and APIs\n",
+ "- **Multi-Source Financial KG**: Builds comprehensive financial knowledge graphs from multiple sources\n",
+ "- **Market Network Analysis**: Analyzes market structure using graph analytics\n",
+ "- **Comprehensive Data Sources**: Multiple financial APIs, RSS feeds, and databases\n",
+ "- **Modular Architecture**: Direct use of Semantica modules without core orchestrator\n",
+ "\n",
+ "### Learning Objectives\n",
+ "\n",
+ "- Ingest financial data from MCP servers, APIs, and RSS feeds\n",
+ "- Use seed data for foundation market information\n",
+ "- Extract financial entities (Companies, Stocks, Prices, Metrics, Markets, Sectors)\n",
+ "- Build financial knowledge graphs with seed data integration\n",
+ "- Analyze market network structure using graph analytics\n",
+ "- Store and query financial data using vector stores\n",
+ "\n",
+ "### Pipeline Flow\n",
+ "\n",
+ "```mermaid\n",
+ "graph TD\n",
+ " A[Data Ingestion] --> B[Seed Data Loading]\n",
+ " B --> C[Document Parsing]\n",
+ " C --> D[Text Processing]\n",
+ " D --> E[Entity Extraction]\n",
+ " E --> F[Relationship Extraction]\n",
+ " F --> G[Deduplication]\n",
+ " G --> H[Knowledge Graph]\n",
+ " H --> I[Embeddings]\n",
+ " I --> J[Vector Store]\n",
+ " H --> K[Graph Analytics]\n",
+ " K --> L[GraphRAG Queries]\n",
+ " J --> L\n",
+ " L --> M[Visualization]\n",
+ " M --> N[Export]\n",
+ "```\n",
+ "\n",
+ "### Data Sources\n",
+ "\n",
+ "#### Financial APIs\n",
+ "- **Alpha Vantage**: https://www.alphavantage.co/documentation/\n",
+ "- **Yahoo Finance API**: https://query1.finance.yahoo.com/v8/finance/\n",
+ "- **IEX Cloud**: https://iexcloud.io/docs/api/\n",
+ "- **Polygon.io**: https://polygon.io/docs\n",
+ "- **Finnhub**: https://finnhub.io/docs/api\n",
+ "- **Quandl**: https://www.quandl.com/tools/api\n",
+ "\n",
+ "#### Financial RSS Feeds\n",
+ "- **Bloomberg RSS**: https://www.bloomberg.com/feeds/\n",
+ "- **Reuters Finance**: https://www.reuters.com/rssFeed/finance\n",
+ "- **Financial Times**: https://www.ft.com/?format=rss\n",
+ "- **MarketWatch**: https://www.marketwatch.com/rss\n",
+ "- **CNBC Finance**: https://www.cnbc.com/id/100003114/device/rss/rss.html\n",
+ "- **WSJ Markets**: https://feeds.a.dj.com/rss/RSSMarketsMain.xml\n",
+ "\n",
+ "#### MCP Servers\n",
+ "- **Financial Data Servers**: MCP servers for market data\n",
+ "- **Market Data Servers**: Real-time market data via MCP\n",
+ "- **Stock Price Servers**: Live stock prices via MCP protocol\n",
+ "\n",
+ "#### Database Links\n",
+ "- **SEC EDGAR**: https://www.sec.gov/edgar/searchedgar/companysearch.html\n",
+ "- **FRED (Federal Reserve)**: https://fred.stlouisfed.org/\n",
+ "- **Quandl**: https://www.quandl.com/\n",
+ "- **World Bank Data**: https://data.worldbank.org/\n",
+ "- **IMF Data**: https://www.imf.org/en/Data\n",
+ "\n",
+ "---\n",
+ "\n",
+ "## Installation\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "%pip install -qU semantica networkx matplotlib plotly pandas faiss-cpu beautifulsoup4 groq sentence-transformers scikit-learn\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Configuration & Setup\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import os\n",
+ "\n",
+ "os.environ[\"GROQ_API_KEY\"] = os.getenv(\"GROQ_API_KEY\", \"your-key-here\")\n",
+ "\n",
+ "# Configuration constants\n",
+ "EMBEDDING_DIMENSION = 384\n",
+ "EMBEDDING_MODEL = \"all-MiniLM-L6-v2\"\n",
+ "CHUNK_SIZE = 1000\n",
+ "CHUNK_OVERLAP = 200\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Ingesting Financial Data from Multiple Sources\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.ingest import MCPIngestor, WebIngestor, FeedIngestor, FileIngestor\n",
+ "import os\n",
+ "from contextlib import redirect_stderr\n",
+ "from io import StringIO\n",
+ "\n",
+ "os.makedirs(\"data\", exist_ok=True)\n",
+ "\n",
+ "feed_sources = [\n",
+ " # Financial RSS Feeds\n",
+ " (\"Reuters Finance\", \"https://www.reuters.com/rssFeed/finance\"),\n",
+ " (\"MarketWatch\", \"https://www.marketwatch.com/rss\"),\n",
+ " (\"CNBC Finance\", \"https://www.cnbc.com/id/100003114/device/rss/rss.html\"),\n",
+ "]\n",
+ "\n",
+ "feed_ingestor = FeedIngestor()\n",
+ "all_documents = []\n",
+ "\n",
+ "for feed_name, feed_url in feed_sources:\n",
+ " try:\n",
+ " with redirect_stderr(StringIO()):\n",
+ " feed_data = feed_ingestor.ingest_feed(feed_url, validate=False)\n",
+ " for item in feed_data.items:\n",
+ " if not item.content:\n",
+ " item.content = item.description or item.title or \"\"\n",
+ " if item.content:\n",
+ " if not hasattr(item, 'metadata'):\n",
+ " item.metadata = {}\n",
+ " item.metadata['source'] = feed_name\n",
+ " all_documents.append(item)\n",
+ " except Exception:\n",
+ " continue\n",
+ "\n",
+ "# Example: Ingest from Alpha Vantage API (requires API key)\n",
+ "alpha_vantage_api = \"https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol=AAPL&apikey=demo\"\n",
+ "try:\n",
+ " web_ingestor = WebIngestor()\n",
+ " with redirect_stderr(StringIO()):\n",
+ " api_documents = web_ingestor.ingest(alpha_vantage_api, method=\"url\")\n",
+ " for doc in api_documents:\n",
+ " if not hasattr(doc, 'metadata'):\n",
+ " doc.metadata = {}\n",
+ " doc.metadata['source'] = 'Alpha Vantage API'\n",
+ " all_documents.append(doc)\n",
+ "except Exception:\n",
+ " pass\n",
+ "\n",
+ "# MCP Server connection example (commented for demo)\n",
+ "# mcp_ingestor = MCPIngestor()\n",
+ "# mcp_ingestor.connect(\"financial_server\", url=\"http://localhost:8000/mcp\")\n",
+ "# resources = mcp_ingestor.list_available_resources(\"financial_server\")\n",
+ "# mcp_data = mcp_ingestor.ingest_resources(\"financial_server\", resource_uris=[\"resource://market_data\"])\n",
+ "\n",
+ "if not all_documents:\n",
+ " market_data = \"\"\"\n",
+ " AAPL stock price: $150.25, market cap: $2.4T, volume: 50M shares, sector: Technology\n",
+ " MSFT stock price: $380.50, market cap: $2.8T, volume: 30M shares, sector: Technology\n",
+ " GOOGL stock price: $140.75, market cap: $1.8T, volume: 25M shares, sector: Technology\n",
+ " JPM stock price: $145.30, market cap: $420B, volume: 15M shares, sector: Financial\n",
+ " \"\"\"\n",
+ " with open(\"data/market_data.txt\", \"w\") as f:\n",
+ " f.write(market_data)\n",
+ " file_ingestor = FileIngestor()\n",
+ " all_documents = file_ingestor.ingest(\"data/market_data.txt\")\n",
+ "\n",
+ "documents = all_documents\n",
+ "print(f\"Ingested {len(documents)} documents\")\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.seed import SeedDataManager\n",
+ "\n",
+ "seed_manager = SeedDataManager()\n",
+ "\n",
+ "# Load foundation market data (exchanges, indices, sectors)\n",
+ "seed_data = [\n",
+ " {\"type\": \"Market\", \"text\": \"NASDAQ\", \"description\": \"Stock exchange\"},\n",
+ " {\"type\": \"Market\", \"text\": \"NYSE\", \"description\": \"Stock exchange\"},\n",
+ " {\"type\": \"Market\", \"text\": \"S&P 500\", \"description\": \"Stock market index\"},\n",
+ " {\"type\": \"Sector\", \"text\": \"Technology\", \"description\": \"Market sector\"},\n",
+ " {\"type\": \"Sector\", \"text\": \"Financial\", \"description\": \"Market sector\"},\n",
+ " {\"type\": \"Sector\", \"text\": \"Healthcare\", \"description\": \"Market sector\"},\n",
+ "]\n",
+ "\n",
+ "seed_manager.load_seed_data(seed_data)\n",
+ "\n",
+ "print(f\"Loaded {len(seed_data)} seed data items for market foundation\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Parsing Financial Documents\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.parse import DocumentParser\n",
+ "\n",
+ "parser = DocumentParser()\n",
+ "\n",
+ "parsed_documents = []\n",
+ "for doc in documents:\n",
+ " try:\n",
+ " parsed = parser.parse(\n",
+ " doc.content if hasattr(doc, 'content') else str(doc),\n",
+ " content_type=\"text\"\n",
+ " )\n",
+ " parsed_documents.append(parsed)\n",
+ " except Exception:\n",
+ " parsed_documents.append(doc)\n",
+ "\n",
+ "documents = parsed_documents\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Normalizing and Chunking Financial Data\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.normalize import TextNormalizer\n",
+ "from semantica.split import TextSplitter\n",
+ "\n",
+ "normalizer = TextNormalizer()\n",
+ "# Use recursive chunking for financial documents\n",
+ "splitter = TextSplitter(method=\"recursive\", chunk_size=CHUNK_SIZE, chunk_overlap=CHUNK_OVERLAP)\n",
+ "\n",
+ "normalized_documents = []\n",
+ "for doc in documents:\n",
+ " normalized_text = normalizer.normalize(\n",
+ " doc.content if hasattr(doc, 'content') else str(doc),\n",
+ " clean_html=True,\n",
+ " normalize_entities=True,\n",
+ " normalize_numbers=True,\n",
+ " remove_extra_whitespace=True,\n",
+ " lowercase=False\n",
+ " )\n",
+ " normalized_documents.append(normalized_text)\n",
+ "\n",
+ "chunked_documents = []\n",
+ "for doc_text in normalized_documents:\n",
+ " try:\n",
+ " with redirect_stderr(StringIO()):\n",
+ " chunks = splitter.split(doc_text)\n",
+ " chunked_documents.extend(chunks)\n",
+ " except Exception:\n",
+ " simple_splitter = TextSplitter(method=\"recursive\", chunk_size=CHUNK_SIZE, chunk_overlap=CHUNK_OVERLAP)\n",
+ " chunks = simple_splitter.split(doc_text)\n",
+ " chunked_documents.extend(chunks)\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Extracting Financial Entities\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.semantic_extract import NERExtractor\n",
+ "\n",
+ "entity_extractor = NERExtractor(\n",
+ " method=\"llm\",\n",
+ " provider=\"groq\",\n",
+ " llm_model=\"llama-3.1-8b-instant\",\n",
+ " temperature=0.0\n",
+ ")\n",
+ "\n",
+ "all_entities = []\n",
+ "for chunk in chunked_documents:\n",
+ " chunk_text = chunk.text if hasattr(chunk, 'text') else str(chunk)\n",
+ " try:\n",
+ " entities = entity_extractor.extract_entities(\n",
+ " chunk_text,\n",
+ " entity_types=[\"Company\", \"Stock\", \"Price\", \"Metric\", \"Market\", \"Sector\"]\n",
+ " )\n",
+ " all_entities.extend(entities)\n",
+ " except Exception:\n",
+ " continue\n",
+ "\n",
+ "companies = [e for e in all_entities if e.label in [\"Company\", \"Stock\"] or \"company\" in e.label.lower() or \"stock\" in e.label.lower()]\n",
+ "markets = [e for e in all_entities if e.label == \"Market\" or \"market\" in e.label.lower()]\n",
+ "sectors = [e for e in all_entities if e.label == \"Sector\" or \"sector\" in e.label.lower()]\n",
+ "\n",
+ "print(f\"Extracted {len(companies)} companies/stocks, {len(markets)} markets, {len(sectors)} sectors\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Extracting Financial Relationships\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.semantic_extract import RelationExtractor\n",
+ "\n",
+ "relation_extractor = RelationExtractor(\n",
+ " method=\"llm\",\n",
+ " provider=\"groq\",\n",
+ " llm_model=\"llama-3.1-8b-instant\",\n",
+ " temperature=0.0\n",
+ ")\n",
+ "\n",
+ "all_relationships = []\n",
+ "for chunk in chunked_documents:\n",
+ " chunk_text = chunk.text if hasattr(chunk, 'text') else str(chunk)\n",
+ " try:\n",
+ " relationships = relation_extractor.extract_relations(\n",
+ " chunk_text,\n",
+ " entities=all_entities,\n",
+ " relation_types=[\"trades_on\", \"has_price\", \"belongs_to\", \"correlates_with\", \"has_metric\", \"in_sector\"]\n",
+ " )\n",
+ " all_relationships.extend(relationships)\n",
+ " except Exception:\n",
+ " continue\n",
+ "\n",
+ "print(f\"Extracted {len(all_relationships)} relationships\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Resolving Duplicate Companies and Stocks\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.deduplication import DuplicateDetector\n",
+ "\n",
+ "duplicate_detector = DuplicateDetector(\n",
+ " similarity_threshold=0.85,\n",
+ " method=\"semantic\"\n",
+ ")\n",
+ "\n",
+ "# Use seed data for entity resolution\n",
+ "deduplicated_entities = duplicate_detector.detect_duplicates(all_entities)\n",
+ "merged_entities = duplicate_detector.merge_duplicates(deduplicated_entities)\n",
+ "\n",
+ "# Enhance entities with seed data information\n",
+ "for entity in merged_entities:\n",
+ " for seed_item in seed_data:\n",
+ " if entity.text.lower() == seed_item[\"text\"].lower():\n",
+ " entity.description = seed_item.get(\"description\", entity.description)\n",
+ " break\n",
+ "\n",
+ "print(f\"Deduplicated {len(all_entities)} entities to {len(merged_entities)} unique entities\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Building Financial Knowledge Graph\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.kg import GraphBuilder\n",
+ "\n",
+ "graph_builder = GraphBuilder(\n",
+ " merge_entities=True,\n",
+ " resolve_conflicts=True,\n",
+ " entity_resolution_strategy=\"fuzzy\"\n",
+ ")\n",
+ "\n",
+ "kg_sources = [{\n",
+ " \"entities\": [{\"text\": e.text, \"type\": e.label, \"confidence\": e.confidence} for e in merged_entities],\n",
+ " \"relationships\": [{\"source\": r.source, \"target\": r.target, \"type\": r.label, \"confidence\": r.confidence} for r in all_relationships]\n",
+ "}]\n",
+ "\n",
+ "kg = graph_builder.build(kg_sources)\n",
+ "\n",
+ "entities_count = len(kg.get('entities', []))\n",
+ "relationships_count = len(kg.get('relationships', []))\n",
+ "print(f\"Graph: {entities_count} entities, {relationships_count} relationships\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Generating Embeddings for Companies and Stocks\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.embeddings import EmbeddingGenerator\n",
+ "\n",
+ "embedding_gen = EmbeddingGenerator(\n",
+ " provider=\"sentence_transformers\",\n",
+ " model=EMBEDDING_MODEL\n",
+ ")\n",
+ "\n",
+ "company_texts = [f\"{c.text} {getattr(c, 'description', '')}\" for c in companies]\n",
+ "company_embeddings = embedding_gen.generate_embeddings(company_texts)\n",
+ "\n",
+ "market_texts = [f\"{m.text} {getattr(m, 'description', '')}\" for m in markets]\n",
+ "market_embeddings = embedding_gen.generate_embeddings(market_texts)\n",
+ "\n",
+ "print(f\"Generated {len(company_embeddings)} company embeddings and {len(market_embeddings)} market embeddings\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Populating Vector Store\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.vector_store import VectorStore\n",
+ "\n",
+ "vector_store = VectorStore(backend=\"faiss\", dimension=EMBEDDING_DIMENSION)\n",
+ "\n",
+ "company_ids = vector_store.store_vectors(\n",
+ " vectors=company_embeddings,\n",
+ " metadata=[{\"type\": \"company\", \"name\": c.text, \"label\": c.label} for c in companies]\n",
+ ")\n",
+ "\n",
+ "market_ids = vector_store.store_vectors(\n",
+ " vectors=market_embeddings,\n",
+ " metadata=[{\"type\": \"market\", \"name\": m.text, \"label\": m.label} for m in markets]\n",
+ ")\n",
+ "\n",
+ "print(f\"Stored {len(company_ids)} company vectors and {len(market_ids)} market vectors\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Analyzing Market Network Structure\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.kg import GraphAnalyzer, CentralityCalculator\n",
+ "\n",
+ "graph_analyzer = GraphAnalyzer()\n",
+ "centrality_calc = CentralityCalculator()\n",
+ "\n",
+ "analysis = graph_analyzer.analyze_graph(kg)\n",
+ "\n",
+ "degree_centrality = centrality_calc.calculate_degree_centrality(kg)\n",
+ "betweenness_centrality = centrality_calc.calculate_betweenness_centrality(kg)\n",
+ "closeness_centrality = centrality_calc.calculate_closeness_centrality(kg)\n",
+ "\n",
+ "# Identify central companies/stocks in the market network\n",
+ "central_companies = []\n",
+ "for entity in kg.get(\"entities\", []):\n",
+ " if entity.get(\"type\") in [\"Company\", \"Stock\"]:\n",
+ " entity_id = entity.get(\"id\")\n",
+ " if entity_id in degree_centrality:\n",
+ " central_companies.append({\n",
+ " \"name\": entity.get(\"text\", \"Unknown\"),\n",
+ " \"degree\": degree_centrality[entity_id]\n",
+ " })\n",
+ "\n",
+ "central_companies.sort(key=lambda x: x['degree'], reverse=True)\n",
+ "\n",
+ "print(f\"Graph analytics:\")\n",
+ "print(f\" - Graph density: {analysis.get('density', 0):.3f}\")\n",
+ "print(f\" - Central nodes (degree): {len(degree_centrality)}\")\n",
+ "print(f\" - Top central companies: {len(central_companies[:5])} identified\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## GraphRAG: Hybrid Vector + Graph Queries\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.context import AgentContext\n",
+ "\n",
+ "context = AgentContext(vector_store=vector_store, knowledge_graph=kg)\n",
+ "\n",
+ "query = \"What technology companies are in the market?\"\n",
+ "results = context.retrieve(\n",
+ " query,\n",
+ " max_results=10,\n",
+ " use_graph=True,\n",
+ " expand_graph=True,\n",
+ " include_entities=True,\n",
+ " include_relationships=True\n",
+ ")\n",
+ "\n",
+ "print(f\"GraphRAG query: '{query}'\")\n",
+ "print(f\"\\nRetrieved {len(results)} results:\\n\")\n",
+ "for i, result in enumerate(results[:5], 1):\n",
+ " print(f\"{i}. Score: {result.get('score', 0):.3f}\")\n",
+ " print(f\" Content: {result.get('content', '')[:200]}...\")\n",
+ " if result.get('related_entities'):\n",
+ " print(f\" Related entities: {len(result['related_entities'])}\")\n",
+ " print()\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Visualizing the Financial Knowledge Graph\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.visualization import KGVisualizer\n",
+ "\n",
+ "visualizer = KGVisualizer()\n",
+ "visualizer.visualize(\n",
+ " kg,\n",
+ " output_path=\"financial_data_kg.html\",\n",
+ " layout=\"spring\",\n",
+ " node_size=20\n",
+ ")\n",
+ "\n",
+ "print(\"Visualization saved to financial_data_kg.html\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Exporting Results\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.export import GraphExporter\n",
+ "\n",
+ "exporter = GraphExporter()\n",
+ "exporter.export(kg, output_path=\"financial_data_kg.json\", format=\"json\")\n",
+ "exporter.export(kg, output_path=\"financial_data_kg.graphml\", format=\"graphml\")\n",
+ "exporter.export(kg, output_path=\"financial_data_market.csv\", format=\"csv\")\n",
+ "\n",
+ "print(\"Exported financial knowledge graph to JSON, GraphML, and CSV formats\")\n"
+ ]
+ }
+ ],
+ "metadata": {
+ "language_info": {
+ "name": "python"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
}
diff --git a/cookbook/use_cases/finance/02_Fraud_Detection.ipynb b/cookbook/use_cases/finance/02_Fraud_Detection.ipynb
index 1249b2a9..711ae3c9 100644
--- a/cookbook/use_cases/finance/02_Fraud_Detection.ipynb
+++ b/cookbook/use_cases/finance/02_Fraud_Detection.ipynb
@@ -15,21 +15,71 @@
"### Key Features\n",
"\n",
"- **Temporal Knowledge Graphs**: Builds temporal KGs to track transaction patterns over time\n",
+ "- **Pattern Detection**: Uses TemporalPatternDetector and reasoning for fraud detection\n",
"- **Anomaly Detection**: Uses graph-based pattern recognition to identify fraud\n",
- "- **Real-Time Alerts**: Generates automated alerts for detected fraud patterns\n",
- "- **Pattern Recognition**: Identifies suspicious transaction patterns\n",
- "- **Stream Processing**: Demonstrates real-time transaction stream processing\n",
- "\n",
- "### Pipeline Architecture\n",
- "\n",
- "1. **Phase 0**: Setup & Configuration\n",
- "2. **Phase 1**: Transaction Stream Ingestion\n",
- "3. **Phase 2**: Transaction Entity Extraction\n",
- "4. **Phase 3**: Temporal Knowledge Graph Construction\n",
- "5. **Phase 4**: Pattern Detection\n",
- "6. **Phase 5**: Anomaly Detection\n",
- "7. **Phase 6**: Real-Time Alerting\n",
- "8. **Phase 7**: Visualization & Export\n",
+ "- **Conflict Detection**: Detects conflicting transaction data from multiple sources\n",
+ "- **Real-Time Stream Processing**: Demonstrates real-time transaction stream processing\n",
+ "- **Comprehensive Data Sources**: Multiple transaction streams, APIs, and fraud databases\n",
+ "- **Modular Architecture**: Direct use of Semantica modules without core orchestrator\n",
+ "\n",
+ "### Learning Objectives\n",
+ "\n",
+ "- Ingest transaction data from streams and APIs\n",
+ "- Extract transaction entities (Transactions, Accounts, Devices, Patterns, Anomalies)\n",
+ "- Build temporal transaction knowledge graphs\n",
+ "- Perform temporal queries and pattern detection\n",
+ "- Detect fraud patterns using graph reasoning\n",
+ "- Analyze transaction networks using graph analytics\n",
+ "- Store and query transaction data using vector stores\n",
+ "\n",
+ "### Pipeline Flow\n",
+ "\n",
+ "```mermaid\n",
+ "graph TD\n",
+ " A[Data Ingestion] --> B[Document Parsing]\n",
+ " B --> C[Text Processing]\n",
+ " C --> D[Entity Extraction]\n",
+ " D --> E[Relationship Extraction]\n",
+ " E --> F[Deduplication]\n",
+ " F --> G[Conflict Detection]\n",
+ " G --> H[Temporal Knowledge Graph]\n",
+ " H --> I[Embeddings]\n",
+ " I --> J[Vector Store]\n",
+ " H --> K[Temporal Queries]\n",
+ " K --> L[Temporal Pattern Detection]\n",
+ " L --> M[Reasoning & Fraud]\n",
+ " M --> N[Graph Analytics]\n",
+ " J --> O[GraphRAG Queries]\n",
+ " N --> O\n",
+ " O --> P[Visualization]\n",
+ " P --> Q[Export]\n",
+ "```\n",
+ "\n",
+ "### Data Sources\n",
+ "\n",
+ "#### Transaction Streams\n",
+ "- **Kafka Streams**: Real-time transaction streaming\n",
+ "- **WebSocket Feeds**: Real-time transaction event feeds\n",
+ "- **Real-Time APIs**: Live transaction data APIs\n",
+ "- **Payment Processors**: Stripe, PayPal transaction streams\n",
+ "\n",
+ "#### Financial APIs\n",
+ "- **Banking APIs**: Open Banking APIs, Plaid\n",
+ "- **Payment APIs**: Stripe API, PayPal API\n",
+ "- **Transaction APIs**: Real-time transaction monitoring APIs\n",
+ "- **Fraud Detection APIs**: External fraud detection services\n",
+ "\n",
+ "#### Fraud Databases\n",
+ "- **Known Fraud Patterns**: Historical fraud pattern databases\n",
+ "- **Blacklists**: Known fraudulent accounts and devices\n",
+ "- **Anomaly Databases**: Pattern databases for anomaly detection\n",
+ "- **Risk Scoring APIs**: Fraud risk scoring services\n",
+ "\n",
+ "#### Database Links\n",
+ "- **Transaction Databases**: Financial transaction systems\n",
+ "- **Fraud Detection Systems**: Enterprise fraud detection platforms\n",
+ "- **Risk Management Systems**: Financial risk management databases\n",
+ "- **Compliance Databases**: Regulatory compliance systems\n",
"\n",
"---\n",
"\n",
@@ -42,16 +92,14 @@
"metadata": {},
"outputs": [],
"source": [
- "%pip install -qU semantica networkx matplotlib plotly pandas groq\n"
+ "%pip install -qU semantica networkx matplotlib plotly pandas faiss-cpu beautifulsoup4 groq sentence-transformers scikit-learn\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "---\n",
- "\n",
- "## Phase 0: Setup & Configuration\n"
+ "## Configuration & Setup\n"
]
},
{
@@ -61,31 +109,22 @@
"outputs": [],
"source": [
"import os\n",
- "from semantica.core import Semantica, ConfigManager\n",
- "from semantica.reasoning import GraphReasoner\n",
"\n",
- "os.environ[\"GROQ_API_KEY\"] = os.getenv(\"GROQ_API_KEY\", \"your-key\")\n",
+ "os.environ[\"GROQ_API_KEY\"] = os.getenv(\"GROQ_API_KEY\", \"your-key-here\")\n",
"\n",
- "config_dict = {\n",
- " \"project_name\": \"Fraud_Detection\",\n",
- " \"extraction\": {\"provider\": \"groq\", \"model\": \"llama-3.1-8b-instant\"},\n",
- " \"knowledge_graph\": {\"backend\": \"networkx\", \"temporal\": True}\n",
- "}\n",
- "\n",
- "config = ConfigManager().load_from_dict(config_dict)\n",
- "core = Semantica(config=config)\n",
- "print(\"Configured for fraud detection with temporal KGs focus\")\n"
+ "# Configuration constants\n",
+ "EMBEDDING_DIMENSION = 384\n",
+ "EMBEDDING_MODEL = \"all-MiniLM-L6-v2\"\n",
+ "CHUNK_SIZE = 500\n",
+ "CHUNK_OVERLAP = 50\n",
+ "TEMPORAL_GRANULARITY = \"minute\"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "---\n",
- "\n",
- "## Phase 1: Real Data Ingestion (Transaction Stream)\n",
- "\n",
- "Ingest transaction data from simulated stream using StreamIngestor.\n"
+ "## Ingesting Transaction Data from Streams\n"
]
},
{
@@ -94,41 +133,89 @@
"metadata": {},
"outputs": [],
"source": [
- "from semantica.ingest import StreamIngestor, FileIngestor\n",
+ "from semantica.ingest import StreamIngestor, WebIngestor, FileIngestor\n",
"import os\n",
+ "from contextlib import redirect_stderr\n",
+ "from io import StringIO\n",
"\n",
"os.makedirs(\"data\", exist_ok=True)\n",
"\n",
- "# Option 1: Ingest from transaction stream (simulated Kafka)\n",
+ "# Example: Ingest from transaction stream (simulated Kafka)\n",
"# In production: stream_ingestor = StreamIngestor()\n",
"# stream_documents = stream_ingestor.ingest(\"kafka://localhost:9092/transactions\", method=\"kafka\")\n",
"\n",
- "# Fallback: Sample transaction stream data\n",
- "tx_data = \"\"\"\n",
- "2024-01-01 10:00:00 - Transaction $1000 from Account A123 to Account B456\n",
- "2024-01-01 10:01:00 - Transaction $5000 from Account A123 to Account C789\n",
- "2024-01-01 10:02:00 - Transaction $10000 from Account A123 to Account D012 (unusual pattern)\n",
- "2024-01-01 10:03:00 - Multiple rapid transactions from Account A123 (suspicious)\n",
- "2024-01-01 10:04:00 - Transaction $2000 from Account B456 to Account E789\n",
- "2024-01-01 10:05:00 - Large transaction $50000 from Account A123 to Account F012 (fraud alert)\n",
- "\"\"\"\n",
- "\n",
- "with open(\"data/transactions.txt\", \"w\") as f:\n",
- " f.write(tx_data)\n",
- "\n",
- "documents = FileIngestor().ingest(\"data/transactions.txt\")\n",
- "print(f\"Ingested {len(documents)} documents from transaction stream\")\n"
+ "# Example: Ingest from payment processor API\n",
+ "payment_api = \"https://api.example.com/transactions\" # Example API endpoint\n",
+ "all_documents = []\n",
+ "\n",
+ "try:\n",
+ " web_ingestor = WebIngestor()\n",
+ " with redirect_stderr(StringIO()):\n",
+ " api_documents = web_ingestor.ingest(payment_api, method=\"url\")\n",
+ " for doc in api_documents:\n",
+ " if not hasattr(doc, 'metadata'):\n",
+ " doc.metadata = {}\n",
+ " doc.metadata['source'] = 'Payment API'\n",
+ " all_documents.append(doc)\n",
+ "except Exception:\n",
+ " pass\n",
+ "\n",
+ "if not all_documents:\n",
+ " tx_data = \"\"\"\n",
+ " 2024-01-01 10:00:00 - Transaction $1000 from Account A123 to Account B456\n",
+ " 2024-01-01 10:01:00 - Transaction $5000 from Account A123 to Account C789\n",
+ " 2024-01-01 10:02:00 - Transaction $10000 from Account A123 to Account D012 (unusual pattern)\n",
+ " 2024-01-01 10:03:00 - Multiple rapid transactions from Account A123 (suspicious)\n",
+ " 2024-01-01 10:04:00 - Transaction $2000 from Account B456 to Account E789\n",
+ " 2024-01-01 10:05:00 - Large transaction $50000 from Account A123 to Account F012 (fraud alert)\n",
+ " 2024-01-01 10:06:00 - Transaction $1500 from Account C789 to Account G345\n",
+ " 2024-01-01 10:07:00 - Unusual device login from Account A123 (suspicious activity)\n",
+ " \"\"\"\n",
+ " with open(\"data/transactions.txt\", \"w\") as f:\n",
+ " f.write(tx_data)\n",
+ " file_ingestor = FileIngestor()\n",
+ " all_documents = file_ingestor.ingest(\"data/transactions.txt\")\n",
+ "\n",
+ "documents = all_documents\n",
+ "print(f\"Ingested {len(documents)} documents\")\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "---\n",
+ "## Parsing Transaction Documents\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.parse import DocumentParser\n",
"\n",
- "## Phase 2: Text Normalization & Conflict Detection\n",
+ "parser = DocumentParser()\n",
"\n",
- "Normalize transaction data and detect conflicts from multiple sources.\n"
+ "parsed_documents = []\n",
+ "for doc in documents:\n",
+ " try:\n",
+ " parsed = parser.parse(\n",
+ " doc.content if hasattr(doc, 'content') else str(doc),\n",
+ " content_type=\"text\"\n",
+ " )\n",
+ " parsed_documents.append(parsed)\n",
+ " except Exception:\n",
+ " parsed_documents.append(doc)\n",
+ "\n",
+ "documents = parsed_documents\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Normalizing and Chunking Transaction Data\n"
]
},
{
@@ -138,55 +225,207 @@
"outputs": [],
"source": [
"from semantica.normalize import TextNormalizer\n",
- "from semantica.conflicts import ConflictDetector\n",
+ "from semantica.split import TextSplitter\n",
"\n",
- "# Normalize transaction data\n",
"normalizer = TextNormalizer()\n",
+ "# Use sentence chunking for transaction logs\n",
+ "splitter = TextSplitter(method=\"sentence\", chunk_size=CHUNK_SIZE, chunk_overlap=CHUNK_OVERLAP)\n",
+ "\n",
"normalized_documents = []\n",
"for doc in documents:\n",
" normalized_text = normalizer.normalize(\n",
" doc.content if hasattr(doc, 'content') else str(doc),\n",
" clean_html=True,\n",
" normalize_entities=True,\n",
- " normalize_numbers=True, # Normalize transaction amounts\n",
- " remove_extra_whitespace=True\n",
+ " normalize_numbers=True,\n",
+ " remove_extra_whitespace=True,\n",
+ " lowercase=False\n",
" )\n",
" normalized_documents.append(normalized_text)\n",
"\n",
- "print(f\"Normalized {len(normalized_documents)} documents\")\n",
+ "chunked_documents = []\n",
+ "for doc_text in normalized_documents:\n",
+ " try:\n",
+ " with redirect_stderr(StringIO()):\n",
+ " chunks = splitter.split(doc_text)\n",
+ " chunked_documents.extend(chunks)\n",
+ " except Exception:\n",
+ " simple_splitter = TextSplitter(method=\"recursive\", chunk_size=CHUNK_SIZE, chunk_overlap=CHUNK_OVERLAP)\n",
+ " chunks = simple_splitter.split(doc_text)\n",
+ " chunked_documents.extend(chunks)\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Extracting Transaction Entities\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.semantic_extract import NERExtractor\n",
+ "\n",
+ "entity_extractor = NERExtractor(\n",
+ " method=\"llm\",\n",
+ " provider=\"groq\",\n",
+ " llm_model=\"llama-3.1-8b-instant\",\n",
+ " temperature=0.0\n",
+ ")\n",
+ "\n",
+ "all_entities = []\n",
+ "for chunk in chunked_documents:\n",
+ " chunk_text = chunk.text if hasattr(chunk, 'text') else str(chunk)\n",
+ " try:\n",
+ " entities = entity_extractor.extract_entities(\n",
+ " chunk_text,\n",
+ " entity_types=[\"Transaction\", \"Account\", \"Device\", \"Pattern\", \"Anomaly\"]\n",
+ " )\n",
+ " all_entities.extend(entities)\n",
+ " except Exception:\n",
+ " continue\n",
+ "\n",
+ "transactions = [e for e in all_entities if e.label == \"Transaction\" or \"transaction\" in e.label.lower()]\n",
+ "accounts = [e for e in all_entities if e.label == \"Account\" or \"account\" in e.label.lower()]\n",
+ "anomalies = [e for e in all_entities if e.label in [\"Anomaly\", \"Pattern\"] or \"anomaly\" in e.label.lower() or \"pattern\" in e.label.lower()]\n",
+ "\n",
+ "print(f\"Extracted {len(transactions)} transactions, {len(accounts)} accounts, {len(anomalies)} anomalies/patterns\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Extracting Transaction Relationships\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.semantic_extract import RelationExtractor\n",
+ "\n",
+ "relation_extractor = RelationExtractor(\n",
+ " method=\"llm\",\n",
+ " provider=\"groq\",\n",
+ " llm_model=\"llama-3.1-8b-instant\",\n",
+ " temperature=0.0\n",
+ ")\n",
"\n",
- "# Build temporal knowledge graph\n",
- "result = core.build_knowledge_base(\n",
- " sources=normalized_documents,\n",
- " custom_entity_types=[\"Transaction\", \"Account\", \"Device\", \"Pattern\", \"Anomaly\"],\n",
- " graph=True,\n",
- " temporal=True\n",
+ "all_relationships = []\n",
+ "for chunk in chunked_documents:\n",
+ " chunk_text = chunk.text if hasattr(chunk, 'text') else str(chunk)\n",
+ " try:\n",
+ " relationships = relation_extractor.extract_relations(\n",
+ " chunk_text,\n",
+ " entities=all_entities,\n",
+ " relation_types=[\"from\", \"to\", \"triggers\", \"detects\", \"associated_with\", \"causes\"]\n",
+ " )\n",
+ " all_relationships.extend(relationships)\n",
+ " except Exception:\n",
+ " continue\n",
+ "\n",
+ "print(f\"Extracted {len(all_relationships)} relationships\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Resolving Duplicate Transactions\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.deduplication import DuplicateDetector\n",
+ "\n",
+ "duplicate_detector = DuplicateDetector(\n",
+ " similarity_threshold=0.85,\n",
+ " method=\"semantic\"\n",
")\n",
"\n",
- "kg = result[\"knowledge_graph\"]\n",
- "entities = result[\"entities\"]\n",
+ "deduplicated_entities = duplicate_detector.detect_duplicates(all_entities)\n",
+ "merged_entities = duplicate_detector.merge_duplicates(deduplicated_entities)\n",
"\n",
- "# Detect conflicts in transaction data (e.g., conflicting account information)\n",
- "detector = ConflictDetector()\n",
- "conflicts = detector.detect_conflicts(entities, kg.get(\"relationships\", []))\n",
+ "print(f\"Deduplicated {len(all_entities)} entities to {len(merged_entities)} unique entities\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Detecting Transaction Conflicts\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.conflicts import ConflictDetector\n",
+ "\n",
+ "conflict_detector = ConflictDetector()\n",
+ "\n",
+ "conflicts = conflict_detector.detect_conflicts(merged_entities, all_relationships)\n",
"\n",
- "print(f\"Built temporal transaction KG with {len(kg.get('entities', []))} entities\")\n",
- "print(f\"Detected {len(conflicts)} conflicts in transaction data\")\n",
"if conflicts:\n",
- " resolved = detector.resolve_conflicts(conflicts, strategy=\"highest_confidence\")\n",
- " print(f\"Resolved {len(resolved)} conflicts\")\n",
- "print(\"Focus: Temporal KGs, anomaly detection, pattern recognition, real-time alerts\")\n"
+ " resolved = conflict_detector.resolve_conflicts(conflicts, strategy=\"highest_confidence\")\n",
+ " print(f\"Detected {len(conflicts)} conflicts, resolved {len(resolved)}\")\n",
+ "else:\n",
+ " print(\"No conflicts detected\")\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "---\n",
+ "## Building Temporal Transaction Knowledge Graph\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.kg import GraphBuilder\n",
+ "\n",
+ "graph_builder = GraphBuilder(\n",
+ " merge_entities=True,\n",
+ " resolve_conflicts=True,\n",
+ " entity_resolution_strategy=\"fuzzy\",\n",
+ " enable_temporal=True,\n",
+ " temporal_granularity=TEMPORAL_GRANULARITY\n",
+ ")\n",
+ "\n",
+ "kg_sources = [{\n",
+ " \"entities\": [{\"text\": e.text, \"type\": e.label, \"confidence\": e.confidence} for e in merged_entities],\n",
+ " \"relationships\": [{\"source\": r.source, \"target\": r.target, \"type\": r.label, \"confidence\": r.confidence} for r in all_relationships]\n",
+ "}]\n",
"\n",
- "## Phase 3-4: Temporal Pattern Detection\n",
+ "kg = graph_builder.build(kg_sources)\n",
"\n",
- "Use TemporalPatternDetector for fraud pattern detection.\n"
+ "entities_count = len(kg.get('entities', []))\n",
+ "relationships_count = len(kg.get('relationships', []))\n",
+ "print(f\"Graph: {entities_count} entities, {relationships_count} relationships\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Generating Embeddings for Transactions and Accounts\n"
]
},
{
@@ -195,24 +434,118 @@
"metadata": {},
"outputs": [],
"source": [
- "from semantica.kg import TemporalGraphQuery, TemporalPatternDetector\n",
+ "from semantica.embeddings import EmbeddingGenerator\n",
+ "\n",
+ "embedding_gen = EmbeddingGenerator(\n",
+ " provider=\"sentence_transformers\",\n",
+ " model=EMBEDDING_MODEL\n",
+ ")\n",
+ "\n",
+ "transaction_texts = [f\"{t.text} {getattr(t, 'description', '')}\" for t in transactions]\n",
+ "transaction_embeddings = embedding_gen.generate_embeddings(transaction_texts)\n",
+ "\n",
+ "account_texts = [f\"{a.text} {getattr(a, 'description', '')}\" for a in accounts]\n",
+ "account_embeddings = embedding_gen.generate_embeddings(account_texts)\n",
+ "\n",
+ "print(f\"Generated {len(transaction_embeddings)} transaction embeddings and {len(account_embeddings)} account embeddings\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Populating Vector Store\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.vector_store import VectorStore\n",
+ "\n",
+ "vector_store = VectorStore(backend=\"faiss\", dimension=EMBEDDING_DIMENSION)\n",
+ "\n",
+ "transaction_ids = vector_store.store_vectors(\n",
+ " vectors=transaction_embeddings,\n",
+ " metadata=[{\"type\": \"transaction\", \"name\": t.text, \"label\": t.label} for t in transactions]\n",
+ ")\n",
+ "\n",
+ "account_ids = vector_store.store_vectors(\n",
+ " vectors=account_embeddings,\n",
+ " metadata=[{\"type\": \"account\", \"name\": a.text, \"label\": a.label} for a in accounts]\n",
+ ")\n",
+ "\n",
+ "print(f\"Stored {len(transaction_ids)} transaction vectors and {len(account_ids)} account vectors\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Temporal Graph Queries\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.kg import TemporalGraphQuery\n",
+ "\n",
+ "temporal_query = TemporalGraphQuery(\n",
+ " enable_temporal_reasoning=True,\n",
+ " temporal_granularity=TEMPORAL_GRANULARITY\n",
+ ")\n",
+ "\n",
+ "query_results = temporal_query.query_at_time(\n",
+ " kg,\n",
+ " query={\"type\": \"Transaction\"},\n",
+ " at_time=\"2024-01-01 10:05:00\"\n",
+ ")\n",
+ "\n",
+ "evolution = temporal_query.analyze_evolution(kg)\n",
+ "temporal_patterns = temporal_query.detect_temporal_patterns(kg, pattern_type=\"sequence\")\n",
+ "\n",
+ "print(f\"Temporal queries: {len(query_results)} transactions at query time\")\n",
+ "print(f\"Temporal patterns detected: {len(temporal_patterns)}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Temporal Pattern Detection\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.kg import TemporalPatternDetector\n",
"\n",
- "# Initialize temporal pattern detector\n",
- "temporal_query = TemporalGraphQuery(enable_temporal_reasoning=True, temporal_granularity=\"minute\")\n",
"pattern_detector = TemporalPatternDetector()\n",
"\n",
"# Detect temporal fraud patterns\n",
"fraud_patterns = pattern_detector.detect_patterns(kg, pattern_type=\"fraud\")\n",
- "temporal_patterns = temporal_query.detect_temporal_patterns(kg, pattern_type=\"sequence\")\n",
+ "\n",
+ "# Detect sequence patterns (rapid transactions, unusual timing)\n",
+ "sequence_patterns = pattern_detector.detect_patterns(kg, pattern_type=\"sequence\")\n",
"\n",
"print(f\"Detected {len(fraud_patterns)} fraud patterns\")\n",
- "print(f\"Detected {len(temporal_patterns)} temporal patterns\")\n"
+ "print(f\"Detected {len(sequence_patterns)} sequence patterns\")\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
- "source": []
+ "source": [
+ "## Reasoning and Fraud Detection\n"
+ ]
},
{
"cell_type": "code",
@@ -220,33 +553,110 @@
"metadata": {},
"outputs": [],
"source": [
- "# Detect fraud patterns using reasoning\n",
- "reasoner = GraphReasoner(kg)\n",
- "reasoning_patterns = reasoner.find_patterns(pattern_type=\"fraud\")\n",
+ "from semantica.reasoning import Reasoner\n",
+ "\n",
+ "reasoner = Reasoner()\n",
"\n",
- "# Identify suspicious accounts\n",
- "suspicious_accounts = [e for e in kg.get(\"entities\", []) \n",
- " if e.get(\"type\") == \"Account\" and \n",
- " any(\"suspicious\" in str(r.get(\"predicate\", \"\")).lower() or\n",
- " \"fraud\" in str(r.get(\"predicate\", \"\")).lower()\n",
- " for r in kg.get(\"relationships\", []) \n",
- " if r.get(\"source\") == e.get(\"id\"))]\n",
+ "reasoner.add_rule(\"IF Account from Transaction AND Transaction amount > 10000 AND Transaction count > 3 THEN Account triggers Anomaly\")\n",
+ "reasoner.add_rule(\"IF Transaction from Account AND Account triggers Anomaly THEN Transaction associated_with Pattern\")\n",
+ "\n",
+ "inferred_facts = reasoner.infer_facts(kg)\n",
+ "\n",
+ "fraud_paths = reasoner.find_paths(\n",
+ " kg,\n",
+ " source_type=\"Account\",\n",
+ " target_type=\"Anomaly\",\n",
+ " max_hops=2\n",
+ ")\n",
"\n",
- "print(f\"Pattern detection: {len(reasoning_patterns)} fraud patterns from reasoning\")\n",
- "print(f\"Temporal patterns: {len(temporal_patterns)} temporal fraud patterns\")\n",
- "print(f\"Anomaly detection: {len(suspicious_accounts)} suspicious accounts flagged\")\n",
- "print(\"This cookbook emphasizes temporal KGs, TemporalPatternDetector, and pattern-based fraud detection\")\n"
+ "print(f\"Inferred {len(inferred_facts)} facts\")\n",
+ "print(f\"Found {len(fraud_paths)} fraud paths\")\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "---\n",
- "\n",
- "## Phase 7: Visualization & Summary\n",
+ "## Analyzing Transaction Network Structure\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.kg import GraphAnalyzer, CommunityDetector\n",
+ "\n",
+ "graph_analyzer = GraphAnalyzer()\n",
+ "community_detector = CommunityDetector()\n",
+ "\n",
+ "analysis = graph_analyzer.analyze_graph(kg)\n",
+ "\n",
+ "communities = community_detector.detect_communities(kg, method=\"louvain\")\n",
+ "connectivity = graph_analyzer.analyze_connectivity(kg)\n",
+ "\n",
+ "# Detect suspicious account communities\n",
+ "suspicious_communities = []\n",
+ "for community in communities:\n",
+ " community_accounts = [e for e in kg.get(\"entities\", []) \n",
+ " if e.get(\"id\") in community and e.get(\"type\") == \"Account\"]\n",
+ " if len(community_accounts) > 0:\n",
+ " # Check if community has suspicious patterns\n",
+ " suspicious_communities.append({\n",
+ " \"community_id\": len(suspicious_communities),\n",
+ " \"account_count\": len(community_accounts)\n",
+ " })\n",
+ "\n",
+ "print(f\"Graph analytics:\")\n",
+ "print(f\" - Communities: {len(communities)}\")\n",
+ "print(f\" - Connected components: {len(connectivity.get('components', []))}\")\n",
+ "print(f\" - Graph density: {analysis.get('density', 0):.3f}\")\n",
+ "print(f\" - Suspicious communities: {len(suspicious_communities)}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## GraphRAG: Hybrid Vector + Graph Queries\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.context import AgentContext\n",
+ "\n",
+ "context = AgentContext(vector_store=vector_store, knowledge_graph=kg)\n",
+ "\n",
+ "query = \"What accounts have suspicious transaction patterns?\"\n",
+ "results = context.retrieve(\n",
+ " query,\n",
+ " max_results=10,\n",
+ " use_graph=True,\n",
+ " expand_graph=True,\n",
+ " include_entities=True,\n",
+ " include_relationships=True\n",
+ ")\n",
"\n",
- "Visualize temporal fraud detection knowledge graph.\n"
+ "print(f\"GraphRAG query: '{query}'\")\n",
+ "print(f\"\\nRetrieved {len(results)} results:\\n\")\n",
+ "for i, result in enumerate(results[:5], 1):\n",
+ " print(f\"{i}. Score: {result.get('score', 0):.3f}\")\n",
+ " print(f\" Content: {result.get('content', '')[:200]}...\")\n",
+ " if result.get('related_entities'):\n",
+ " print(f\" Related entities: {len(result['related_entities'])}\")\n",
+ " print()\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Visualizing the Temporal Fraud Detection Knowledge Graph\n"
]
},
{
@@ -258,16 +668,37 @@
"from semantica.visualization import KGVisualizer\n",
"\n",
"visualizer = KGVisualizer()\n",
- "visualizer.visualize(kg, output_path=\"fraud_detection_kg.html\", layout=\"temporal\")\n",
- "\n",
- "print(\"Fraud detection analysis complete\")\n",
- "print(\"\\n=== Pipeline Summary ===\")\n",
- "print(f\"✓ Ingested {len(documents)} documents from transaction stream\")\n",
- "print(f\"✓ Normalized {len(normalized_documents)} documents\")\n",
- "print(f\"✓ Detected and resolved {len(conflicts)} conflicts\")\n",
- "print(f\"✓ Built temporal KG with {len(kg.get('entities', []))} entities\")\n",
- "print(f\"✓ Detected {len(reasoning_patterns)} fraud patterns and {len(suspicious_accounts)} suspicious accounts\")\n",
- "print(f\"✓ Emphasizes: Temporal KGs, TemporalPatternDetector, anomaly detection, pattern recognition, real-time alerts\")\n"
+ "visualizer.visualize(\n",
+ " kg,\n",
+ " output_path=\"fraud_detection_kg.html\",\n",
+ " layout=\"temporal\",\n",
+ " node_size=20\n",
+ ")\n",
+ "\n",
+ "print(\"Visualization saved to fraud_detection_kg.html\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Exporting Results\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.export import GraphExporter\n",
+ "\n",
+ "exporter = GraphExporter()\n",
+ "exporter.export(kg, output_path=\"fraud_detection_kg.json\", format=\"json\")\n",
+ "exporter.export(kg, output_path=\"fraud_detection_kg.graphml\", format=\"graphml\")\n",
+ "exporter.export(kg, output_path=\"fraud_detection_alerts.csv\", format=\"csv\")\n",
+ "\n",
+ "print(\"Exported fraud detection knowledge graph to JSON, GraphML, and CSV formats\")\n"
]
}
],