{"id":4156,"date":"2025-06-01T17:35:00","date_gmt":"2025-06-01T12:05:00","guid":{"rendered":"https:\/\/navveenbalani.dev\/?p=4156"},"modified":"2025-06-16T17:38:26","modified_gmt":"2025-06-16T12:08:26","slug":"autonomous-portfolio-analysis-with-google-adk-zerodha-mcp-and-llms","status":"publish","type":"post","link":"https:\/\/navveenbalani.dev\/index.php\/articles\/artificial-intelligence\/agentic-ai\/autonomous-portfolio-analysis-with-google-adk-zerodha-mcp-and-llms\/","title":{"rendered":"Autonomous Portfolio Analysis with Google ADK, Zerodha MCP, and LLMs"},"content":{"rendered":"\n<p>Modern financial analysis is rapidly moving toward automation and agentic workflows. Integrating large language models (LLMs) with real-time financial data unlocks not just powerful insights but also entirely new ways of interacting with portfolio data.<\/p>\n\n\n\n<p>This post walks through a practical, autonomous solution using <a class=\"\" href=\"https:\/\/google.github.io\/adk-docs\/\">Google ADK<\/a>, Zerodha\u2019s <a class=\"\" href=\"https:\/\/github.com\/zerodha\/kite-mcp-server\">Kite MCP<\/a> protocol, and an LLM for actionable portfolio analytics. The full workflow and code are available <a class=\"\" href=\"https:\/\/github.com\/navveenb\/agentic-ai-worfklows\/tree\/main\/google-adk-zerodha\">on GitHub<\/a>.<\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2>Why This Stack?<\/h2>\n\n\n\n<ul><li><strong>Google ADK:<\/strong> Enables LLM agents to interact with live tools, APIs, and event streams in a repeatable, testable way.<\/li><li><strong>Zerodha MCP (Model Control Protocol):<\/strong> Provides a secure, real-time API to portfolio holdings using Server-Sent Events (SSE).<\/li><li><strong>LLMs (Gemini\/GPT-4o):<\/strong> Analyze portfolio data, highlight concentration risk, and offer actionable recommendations.<\/li><\/ul>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2>Architecture Overview<\/h2>\n\n\n\n<p>The workflow has three main steps:<\/p>\n\n\n\n<ol><li><strong>User authenticates<\/strong> with Zerodha using an OAuth browser flow.<\/li><li><strong>The agent retrieves live holdings<\/strong> via the MCP <code>get_holdings<\/code> tool.<\/li><li><strong>The LLM agent analyzes<\/strong> the raw data for risk and performance insights.<\/li><\/ol>\n\n\n\n<p>All API keys and connection details are managed through environment variables for security and reproducibility.<\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2>Key Code Snippets<\/h2>\n\n\n\n<h3>1. Environment and Dependency Setup<\/h3>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>import os\nfrom dotenv import load_dotenv\n\n# Load API keys and config from .env\nload_dotenv('.env')\nos.environ[\"GOOGLE_API_KEY\"] = os.environ[\"GOOGLE_API_KEY\"]\nos.environ[\"GOOGLE_GENAI_USE_VERTEXAI\"] = \"False\"\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h3>2. ADK Agent and Toolset Initialization<\/h3>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>from google.adk.agents.llm_agent import LlmAgent\nfrom google.adk.tools.mcp_tool.mcp_toolset import MCPToolset, SseServerParams\n\nMCP_SSE_URL = os.environ.get(\"MCP_SSE_URL\", \"https:\/\/mcp.kite.trade\/sse\")\n\ntoolset = MCPToolset(\n    connection_params=SseServerParams(url=MCP_SSE_URL, headers={})\n)\n\nroot_agent = LlmAgent(\n    model='gemini-2.0-flash',\n    name='zerodha_portfolio_assistant',\n    instruction=(\n        \"You are an expert Zerodha portfolio assistant. \"\n        \"Use the 'login' tool to authenticate, and the 'get_holdings' tool to fetch stock holdings. \"\n        \"When given portfolio data, analyze for concentration risk and best\/worst performers.\"\n    ),\n    tools=[toolset]\n)\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h3>3. Orchestrating the Workflow<\/h3>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>from google.adk.sessions import InMemorySessionService\nfrom google.adk.artifacts.in_memory_artifact_service import InMemoryArtifactService\nfrom google.adk.runners import Runner\nfrom google.genai import types\n\nimport asyncio\n\nasync def run_workflow():\n    session_service = InMemorySessionService()\n    artifacts_service = InMemoryArtifactService()\n    session = await session_service.create_session(\n        state={}, app_name='zerodha_portfolio_app', user_id='user1'\n    )\n\n    runner = Runner(\n        app_name='zerodha_portfolio_app',\n        agent=root_agent,\n        artifact_service=artifacts_service,\n        session_service=session_service,\n    )\n\n    # 1. Login Step\n    login_query = \"Authenticate and provide the login URL for Zerodha.\"\n    content = types.Content(role='user', parts=[types.Part(text=login_query)])\n    login_url = None\n    async for event in runner.run_async(session_id=session.id, user_id=session.user_id, new_message=content):\n        if event.is_final_response():\n            import re\n            match = re.search(r'(https?:\/\/[^\\s)]+)', getattr(event.content.parts[0], \"text\", \"\"))\n            if match:\n                login_url = match.group(1)\n    if not login_url:\n        print(\"No login URL found. Exiting.\")\n        return\n    print(f\"Open this URL in your browser to authenticate:\\n{login_url}\")\n    import webbrowser; webbrowser.open(login_url)\n    input(\"Press Enter after completing login...\")\n\n    # 2. Fetch Holdings\n    holdings_query = \"Show my current stock holdings.\"\n    content = types.Content(role='user', parts=[types.Part(text=holdings_query)])\n    holdings_raw = None\n    async for event in runner.run_async(session_id=session.id, user_id=session.user_id, new_message=content):\n        if event.is_final_response():\n            holdings_raw = getattr(event.content.parts[0], \"text\", None)\n    if not holdings_raw:\n        print(\"No holdings data found.\")\n        return\n\n    # 3. Analysis\n    analysis_prompt = f\"\"\"\nYou are a senior portfolio analyst.\n\nGiven only the raw stock holdings listed below, do not invent or assume any other holdings.\n\n1. **Concentration Risk**: Identify if a significant percentage of the total portfolio is allocated to a single stock or sector. Quantify the largest exposures, explain why this matters, and suggest specific diversification improvements.\n\n2. **Performance Standouts**: Clearly identify the best and worst performing stocks in the portfolio (by absolute and percentage P&amp;L), and give actionable recommendations.\n\nRaw holdings:\n\n{holdings_raw}\n\nUse only the provided data.\n\"\"\"\n    content = types.Content(role='user', parts=[types.Part(text=analysis_prompt)])\n    async for event in runner.run_async(session_id=session.id, user_id=session.user_id, new_message=content):\n        if event.is_final_response():\n            print(\"\\n=== Portfolio Analysis Report ===\\n\")\n            print(getattr(event.content.parts[0], \"text\", \"\"))\n\nasyncio.run(run_workflow())\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2>Security and Environment Configuration<\/h2>\n\n\n\n<p>All API keys and MCP endpoints are managed via environment variables or a <code>.env<\/code> file.<br>Never hardcode sensitive information in code.<\/p>\n\n\n\n<p><strong>Example <code>.env<\/code> file:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>GOOGLE_API_KEY=your_google_gemini_api_key\nMCP_SSE_URL=https:\/\/mcp.kite.trade\/sse\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2>What This Enables<\/h2>\n\n\n\n<ul><li><strong>Reproducible automation:<\/strong> Agents can authenticate, retrieve, and analyze portfolios with minimal human input.<\/li><li><strong>Extensibility:<\/strong> Easily add more tools (orders, margins, etc.) or more advanced analytic prompts.<\/li><li><strong>Separation of concerns:<\/strong> Business logic, security, and agent workflow are all clearly separated.<\/li><\/ul>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2>Repository<\/h2>\n\n\n\n<p>Full working code and documentation:<br><a class=\"\" href=\"https:\/\/github.com\/navveenb\/agentic-ai-worfklows\/tree\/main\/google-adk-zerodha\">https:\/\/github.com\/navveenb\/agentic-ai-worfklows\/tree\/main\/google-adk-zerodha<\/a><\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<p><em>This workflow is for educational and portfolio analysis purposes only. Not investment advice.<\/em><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Modern financial analysis is rapidly moving toward automation and agentic workflows. Integrating large language models (LLMs) with real-time financial data unlocks not just powerful insights but also entirely new ways of interacting with portfolio data. This post walks through a practical, autonomous solution using Google ADK, Zerodha\u2019s Kite MCP protocol, and an LLM for actionable [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":3093,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[394,3,267,10],"tags":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v16.0.2 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Autonomous Portfolio Analysis with Google ADK, Zerodha MCP, and LLMs - Current and Future Technology Trends by Navveen Balani<\/title>\n<meta name=\"description\" content=\"Autonomous Portfolio Analysis with Google ADK, Zerodha MCP, and LLMs - Agentic AI\" \/>\n<link rel=\"canonical\" href=\"https:\/\/navveenbalani.dev\/index.php\/articles\/artificial-intelligence\/agentic-ai\/autonomous-portfolio-analysis-with-google-adk-zerodha-mcp-and-llms\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Autonomous Portfolio Analysis with Google ADK, Zerodha MCP, and LLMs - Current and Future Technology Trends by Navveen Balani\" \/>\n<meta property=\"og:description\" content=\"Autonomous Portfolio Analysis with Google ADK, Zerodha MCP, and LLMs - Agentic AI\" \/>\n<meta property=\"og:url\" content=\"https:\/\/navveenbalani.dev\/index.php\/articles\/artificial-intelligence\/agentic-ai\/autonomous-portfolio-analysis-with-google-adk-zerodha-mcp-and-llms\/\" \/>\n<meta property=\"og:site_name\" content=\"Current and Future Technology Trends by Navveen Balani\" \/>\n<meta property=\"article:published_time\" content=\"2025-06-01T12:05:00+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2025-06-16T12:08:26+00:00\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:image\" content=\"https:\/\/navveenbalani.dev\/wp-content\/uploads\/2021\/03\/abstract-cloud.jpg\" \/>\n<meta name=\"twitter:label1\" content=\"Est. reading time\">\n\t<meta name=\"twitter:data1\" content=\"3 minutes\">\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebSite\",\"@id\":\"https:\/\/navveenbalani.dev\/#website\",\"url\":\"https:\/\/navveenbalani.dev\/\",\"name\":\"Current and Future Technology Trends by Navveen Balani\",\"description\":\"Current and Future Technology Trends by Navveen Balani\",\"publisher\":{\"@id\":\"https:\/\/navveenbalani.dev\/#\/schema\/person\/51f7ab14b20611d95e3c7fd4ea0950bf\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":\"https:\/\/navveenbalani.dev\/?s={search_term_string}\",\"query-input\":\"required name=search_term_string\"}],\"inLanguage\":\"en-US\"},{\"@type\":\"ImageObject\",\"@id\":\"https:\/\/navveenbalani.dev\/index.php\/articles\/artificial-intelligence\/agentic-ai\/autonomous-portfolio-analysis-with-google-adk-zerodha-mcp-and-llms\/#primaryimage\",\"inLanguage\":\"en-US\",\"url\":\"https:\/\/navveenbalani.dev\/wp-content\/uploads\/2021\/03\/abstract-cloud.jpg\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/navveenbalani.dev\/index.php\/articles\/artificial-intelligence\/agentic-ai\/autonomous-portfolio-analysis-with-google-adk-zerodha-mcp-and-llms\/#webpage\",\"url\":\"https:\/\/navveenbalani.dev\/index.php\/articles\/artificial-intelligence\/agentic-ai\/autonomous-portfolio-analysis-with-google-adk-zerodha-mcp-and-llms\/\",\"name\":\"Autonomous Portfolio Analysis with Google ADK, Zerodha MCP, and LLMs - Current and Future Technology Trends by Navveen Balani\",\"isPartOf\":{\"@id\":\"https:\/\/navveenbalani.dev\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/navveenbalani.dev\/index.php\/articles\/artificial-intelligence\/agentic-ai\/autonomous-portfolio-analysis-with-google-adk-zerodha-mcp-and-llms\/#primaryimage\"},\"datePublished\":\"2025-06-01T12:05:00+00:00\",\"dateModified\":\"2025-06-16T12:08:26+00:00\",\"description\":\"Autonomous Portfolio Analysis with Google ADK, Zerodha MCP, and LLMs - Agentic AI\",\"breadcrumb\":{\"@id\":\"https:\/\/navveenbalani.dev\/index.php\/articles\/artificial-intelligence\/agentic-ai\/autonomous-portfolio-analysis-with-google-adk-zerodha-mcp-and-llms\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/navveenbalani.dev\/index.php\/articles\/artificial-intelligence\/agentic-ai\/autonomous-portfolio-analysis-with-google-adk-zerodha-mcp-and-llms\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/navveenbalani.dev\/index.php\/articles\/artificial-intelligence\/agentic-ai\/autonomous-portfolio-analysis-with-google-adk-zerodha-mcp-and-llms\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"item\":{\"@type\":\"WebPage\",\"@id\":\"https:\/\/navveenbalani.dev\/\",\"url\":\"https:\/\/navveenbalani.dev\/\",\"name\":\"Home\"}},{\"@type\":\"ListItem\",\"position\":2,\"item\":{\"@type\":\"WebPage\",\"@id\":\"https:\/\/navveenbalani.dev\/index.php\/articles\/artificial-intelligence\/agentic-ai\/autonomous-portfolio-analysis-with-google-adk-zerodha-mcp-and-llms\/\",\"url\":\"https:\/\/navveenbalani.dev\/index.php\/articles\/artificial-intelligence\/agentic-ai\/autonomous-portfolio-analysis-with-google-adk-zerodha-mcp-and-llms\/\",\"name\":\"Autonomous Portfolio Analysis with Google ADK, Zerodha MCP, and LLMs\"}}]},{\"@type\":\"Article\",\"@id\":\"https:\/\/navveenbalani.dev\/index.php\/articles\/artificial-intelligence\/agentic-ai\/autonomous-portfolio-analysis-with-google-adk-zerodha-mcp-and-llms\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/navveenbalani.dev\/index.php\/articles\/artificial-intelligence\/agentic-ai\/autonomous-portfolio-analysis-with-google-adk-zerodha-mcp-and-llms\/#webpage\"},\"author\":{\"@id\":\"https:\/\/navveenbalani.dev\/#\/schema\/person\/51f7ab14b20611d95e3c7fd4ea0950bf\"},\"headline\":\"Autonomous Portfolio Analysis with Google ADK, Zerodha MCP, and LLMs\",\"datePublished\":\"2025-06-01T12:05:00+00:00\",\"dateModified\":\"2025-06-16T12:08:26+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/navveenbalani.dev\/index.php\/articles\/artificial-intelligence\/agentic-ai\/autonomous-portfolio-analysis-with-google-adk-zerodha-mcp-and-llms\/#webpage\"},\"publisher\":{\"@id\":\"https:\/\/navveenbalani.dev\/#\/schema\/person\/51f7ab14b20611d95e3c7fd4ea0950bf\"},\"image\":{\"@id\":\"https:\/\/navveenbalani.dev\/index.php\/articles\/artificial-intelligence\/agentic-ai\/autonomous-portfolio-analysis-with-google-adk-zerodha-mcp-and-llms\/#primaryimage\"},\"articleSection\":\"Agentic AI,Articles,Artificial Intelligence,Featured\",\"inLanguage\":\"en-US\"},{\"@type\":[\"Person\",\"Organization\"],\"@id\":\"https:\/\/navveenbalani.dev\/#\/schema\/person\/51f7ab14b20611d95e3c7fd4ea0950bf\",\"name\":\"Navveen\",\"image\":{\"@type\":\"ImageObject\",\"@id\":\"https:\/\/navveenbalani.dev\/#personlogo\",\"inLanguage\":\"en-US\",\"url\":\"https:\/\/navveenbalani.dev\/wp-content\/uploads\/2019\/07\/navveen_balani.jpeg\",\"width\":200,\"height\":200,\"caption\":\"Navveen\"},\"logo\":{\"@id\":\"https:\/\/navveenbalani.dev\/#personlogo\"},\"sameAs\":[\"http:\/\/naveenbalani.com\"]}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","_links":{"self":[{"href":"https:\/\/navveenbalani.dev\/index.php\/wp-json\/wp\/v2\/posts\/4156"}],"collection":[{"href":"https:\/\/navveenbalani.dev\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/navveenbalani.dev\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/navveenbalani.dev\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/navveenbalani.dev\/index.php\/wp-json\/wp\/v2\/comments?post=4156"}],"version-history":[{"count":2,"href":"https:\/\/navveenbalani.dev\/index.php\/wp-json\/wp\/v2\/posts\/4156\/revisions"}],"predecessor-version":[{"id":4158,"href":"https:\/\/navveenbalani.dev\/index.php\/wp-json\/wp\/v2\/posts\/4156\/revisions\/4158"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/navveenbalani.dev\/index.php\/wp-json\/wp\/v2\/media\/3093"}],"wp:attachment":[{"href":"https:\/\/navveenbalani.dev\/index.php\/wp-json\/wp\/v2\/media?parent=4156"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/navveenbalani.dev\/index.php\/wp-json\/wp\/v2\/categories?post=4156"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/navveenbalani.dev\/index.php\/wp-json\/wp\/v2\/tags?post=4156"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}