lucifer7210 commited on
Commit
820abda
·
verified ·
1 Parent(s): 4b46b44

Upload 2 files

Browse files
Files changed (2) hide show
  1. USEME.MD +214 -0
  2. streamlit_app.py +936 -0
USEME.MD ADDED
@@ -0,0 +1,214 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Indian Financial Compliance System - Usage Guide
2
+
3
+ ## Overview
4
+ The Indian Financial Compliance System is a comprehensive tool for analyzing financial data of Indian companies against regulatory compliance requirements. It consists of a FastAPI backend and a Streamlit frontend.
5
+
6
+ ## Prerequisites
7
+ - Python 3.8+
8
+ - API key for Swarms API (set in environment variables)
9
+
10
+ ## Setup Instructions
11
+
12
+ ### 1. Clone the Repository
13
+ ```bash
14
+ git clone <repository-url>
15
+ cd indian-compliance-system
16
+ ```
17
+
18
+ ### 2. Install Dependencies
19
+ ```bash
20
+ # Create virtual environment
21
+ python -m venv venv
22
+
23
+ # Activate virtual environment (Windows)
24
+ venv\Scripts\activate
25
+
26
+ # Activate virtual environment (Linux/Mac)
27
+ source venv/bin/activate
28
+
29
+ # Install dependencies
30
+ pip install -r requirements.txt
31
+ ```
32
+
33
+ ### 3. Environment Configuration
34
+ Create a `.env` file in the root directory:
35
+ ```env
36
+ SWARMS_API_KEY=your_swarms_api_key_here
37
+ ```
38
+
39
+ ### 4. Run the Backend (FastAPI)
40
+ ```bash
41
+ uvicorn app.main:app --reload --host 0.0.0.0 --port 8000
42
+ ```
43
+ The API will be available at `http://localhost:8000` with documentation at `http://localhost:8000/docs`.
44
+
45
+ ### 5. Run the Frontend (Streamlit)
46
+ ```bash
47
+ streamlit run streamlit_app.py
48
+ ```
49
+ The Streamlit app will be available at `http://localhost:8501`.
50
+
51
+ ## API Endpoints
52
+
53
+ ### 1. Get Stock Data
54
+ **Endpoint:** `POST /api/v1/stock-data`
55
+
56
+ **Request Body:**
57
+ ```json
58
+ {
59
+ "symbol": "RELIANCE"
60
+ }
61
+ ```
62
+
63
+ **Response:**
64
+ ```json
65
+ {
66
+ "success": true,
67
+ "data": { ... },
68
+ "formatted_data": "COMPANY INFORMATION: ..."
69
+ }
70
+ ```
71
+
72
+ ### 2. Run Compliance Analysis
73
+ **Endpoint:** `POST /api/v1/compliance-analysis`
74
+
75
+ **Request Body:**
76
+ ```json
77
+ {
78
+ "financial_data": "Balance Sheet as at 31st March 2023: ...",
79
+ "company_info": "Public Limited Company in the Oil & Gas sector...",
80
+ "data_source": "NSE Listed Company (Live Data)",
81
+ "accounting_standards": "Indian Accounting Standards (Ind AS)",
82
+ "regulatory_frameworks": [
83
+ "Companies Act 2013",
84
+ "SEBI LODR Regulations"
85
+ ]
86
+ }
87
+ ```
88
+
89
+ **Response:**
90
+ ```json
91
+ {
92
+ "success": true,
93
+ "result": {
94
+ "response": "Compliance analysis completed successfully...",
95
+ "analysis_details": { ... }
96
+ }
97
+ }
98
+ ```
99
+
100
+ ### 3. Generate CSV Report
101
+ **Endpoint:** `POST /api/v1/generate-csv`
102
+
103
+ **Request Body:**
104
+ ```json
105
+ {
106
+ "data_source": "NSE Listed Company (Live Data)",
107
+ "company_info": "Public Limited Company in the Oil & Gas sector...",
108
+ "accounting_standards": "Indian Accounting Standards (Ind AS)",
109
+ "regulatory_frameworks": [
110
+ "Companies Act 2013",
111
+ "SEBI LODR Regulations"
112
+ ],
113
+ "result": {
114
+ "response": "Compliance analysis completed successfully...",
115
+ "analysis_details": { ... }
116
+ }
117
+ }
118
+ ```
119
+
120
+ **Response:** Returns a downloadable CSV file.
121
+
122
+ ### 4. Get Popular Stocks
123
+ **Endpoint:** `GET /api/v1/popular-stocks`
124
+
125
+ **Response:**
126
+ ```json
127
+ {
128
+ "stocks": ["RELIANCE", "TATA", "INFY", ...]
129
+ }
130
+ ```
131
+
132
+ ## Example Usage
133
+
134
+ ### Using curl to Test Endpoints
135
+
136
+ 1. **Get Stock Data:**
137
+ ```bash
138
+ curl -X POST "http://localhost:8000/api/v1/stock-data" \
139
+ -H "Content-Type: application/json" \
140
+ -d '{"symbol": "RELIANCE"}'
141
+ ```
142
+
143
+ 2. **Run Compliance Analysis:**
144
+ ```bash
145
+ curl -X POST "http://localhost:8000/api/v1/compliance-analysis" \
146
+ -H "Content-Type: application/json" \
147
+ -d '{
148
+ "financial_data": "Balance Sheet as at 31st March 2023: ...",
149
+ "company_info": "Public Limited Company in the Oil & Gas sector...",
150
+ "data_source": "NSE Listed Company (Live Data)",
151
+ "accounting_standards": "Indian Accounting Standards (Ind AS)",
152
+ "regulatory_frameworks": ["Companies Act 2013", "SEBI LODR Regulations"]
153
+ }'
154
+ ```
155
+
156
+ 3. **Generate CSV Report:**
157
+ ```bash
158
+ curl -X POST "http://localhost:8000/api/v1/generate-csv" \
159
+ -H "Content-Type: application/json" \
160
+ -d '{
161
+ "data_source": "NSE Listed Company (Live Data)",
162
+ "company_info": "Public Limited Company in the Oil & Gas sector...",
163
+ "accounting_standards": "Indian Accounting Standards (Ind AS)",
164
+ "regulatory_frameworks": ["Companies Act 2013", "SEBI LODR Regulations"],
165
+ "result": {
166
+ "response": "Compliance analysis completed successfully...",
167
+ "analysis_details": { ... }
168
+ }
169
+ }' \
170
+ --output compliance_report.csv
171
+ ```
172
+
173
+ ## Features
174
+
175
+ 1. **Live NSE Data Fetching:** Get real-time financial data for Indian companies listed on NSE
176
+ 2. **Multi-Agent Analysis:** Three specialized AI agents analyze different aspects of compliance:
177
+ - Documentation Analyzer
178
+ - Accounting Standards Expert
179
+ - Regulatory Compliance Specialist
180
+ 3. **Comprehensive Reporting:** Generate detailed compliance reports in CSV format
181
+ 4. **Risk Assessment:** Visualize and assess regulatory risks specific to Indian companies
182
+ 5. **Historical Analysis:** Track and compare compliance analyses over time
183
+
184
+ ## Supported Regulations
185
+
186
+ - Indian Accounting Standards (Ind AS)
187
+ - Companies Act 2013
188
+ - SEBI LODR Regulations
189
+ - SEBI ICDR Regulations
190
+ - RBI Guidelines
191
+ - FEMA Regulations
192
+ - Income Tax Act 1961
193
+ - GST Regulations
194
+ - RERA (Real Estate)
195
+ - Insurance Regulatory Act
196
+ - Banking Regulation Act
197
+
198
+ ## Troubleshooting
199
+
200
+ 1. **API Key Issues:** Ensure your SWARMS_API_KEY is correctly set in the .env file
201
+ 2. **Port Conflicts:** Change ports if 8000 or 8501 are already in use
202
+ 3. **Dependency Issues:** Reinstall requirements if facing module import errors
203
+ 4. **Data Fetching Errors:** Check internet connection and stock symbol validity
204
+
205
+ ## Support
206
+
207
+ For issues or questions:
208
+ 1. Check the API documentation at `http://localhost:8000/docs`
209
+ 2. Verify environment variables are correctly set
210
+ 3. Ensure all dependencies are installed
211
+
212
+ ## License
213
+
214
+ This project is for educational and demonstration purposes. Ensure you comply with the terms of service of the Swarms API and any data providers when using this system in production.
streamlit_app.py ADDED
@@ -0,0 +1,936 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # streamlit_indian_compliance_app.py
2
+ import streamlit as st
3
+ import json
4
+ import os
5
+ import requests
6
+ from dotenv import load_dotenv
7
+ import pandas as pd
8
+ from datetime import datetime
9
+ import plotly.express as px
10
+ import yfinance as yf
11
+ import time
12
+ from typing import Optional, Dict, Any, List
13
+
14
+ # Load environment variables
15
+ load_dotenv()
16
+
17
+ # Configuration
18
+ API_KEY = os.getenv("SWARMS_API_KEY")
19
+ BASE_URL = "https://api.swarms.world"
20
+
21
+ # Standard headers for all requests
22
+ headers = {
23
+ "x-api-key": API_KEY,
24
+ "Content-Type": "application/json"
25
+ }
26
+
27
+ class IndianDataProvider:
28
+ """Handles integration with Indian financial data APIs"""
29
+
30
+ def __init__(self):
31
+ pass
32
+
33
+ def get_nse_stock_data(self, symbol: str) -> Dict[str, Any]:
34
+ """Get NSE stock data using Yahoo Finance with direct metric extraction"""
35
+ try:
36
+ # Create ticker with NSE suffix
37
+ ticker = yf.Ticker(f"{symbol}.NS")
38
+ info = ticker.info
39
+ financials = ticker.financials
40
+ balance_sheet = ticker.balance_sheet
41
+ cash_flow = ticker.cashflow
42
+
43
+ # Extract key metrics directly from info
44
+ current_price = info.get("currentPrice")
45
+ total_revenue = info.get("totalRevenue")
46
+ net_income = info.get("netIncomeToCommon")
47
+ total_debt = info.get("totalDebt")
48
+
49
+ return {
50
+ 'success': True,
51
+ 'info': info,
52
+ 'financials': financials.to_dict() if not financials.empty else {},
53
+ 'balance_sheet': balance_sheet.to_dict() if not balance_sheet.empty else {},
54
+ 'cash_flow': cash_flow.to_dict() if not cash_flow.empty else {},
55
+ 'current_price': current_price,
56
+ 'total_revenue': total_revenue,
57
+ 'net_income': net_income,
58
+ 'total_debt': total_debt,
59
+ 'price_source': 'Yahoo Finance'
60
+ }
61
+ except Exception as e:
62
+ return {"success": False, "error": str(e)}
63
+
64
+ def format_stock_data_for_analysis(self, stock_data: Dict[str, Any]) -> str:
65
+ """Format NSE stock data for compliance analysis"""
66
+ if not stock_data.get('success'):
67
+ return f"Error fetching stock data: {stock_data.get('error', 'Unknown error')}"
68
+
69
+ try:
70
+ info = stock_data['info']
71
+ financials = stock_data['financials']
72
+ balance_sheet = stock_data['balance_sheet']
73
+
74
+ # Use directly extracted metrics
75
+ current_price = stock_data.get('current_price')
76
+ total_revenue = stock_data.get('total_revenue')
77
+ net_income = stock_data.get('net_income')
78
+ total_debt = stock_data.get('total_debt')
79
+
80
+ # Format currency values
81
+ def format_currency(value):
82
+ if value is None:
83
+ return "N/A"
84
+ return f"₹{value:,.2f}"
85
+
86
+ def get_total_liabilities(balance_sheet: dict) -> float:
87
+ for timestamp, financials in balance_sheet.items():
88
+ if 'Total Liabilities Net Minority Interest' in financials:
89
+ return financials['Total Liabilities Net Minority Interest']
90
+ return None
91
+
92
+ def get_total_assets(balance_sheet: dict) -> float:
93
+ for timestamp, financials in balance_sheet.items():
94
+ if 'Total Assets' in financials:
95
+ return financials['Total Assets']
96
+ return None
97
+
98
+ total_assets = get_total_assets(balance_sheet)
99
+ total_liabilities = get_total_liabilities(balance_sheet)
100
+ shareholders_equity = total_assets - total_liabilities if total_assets and total_liabilities else None
101
+
102
+ def get_ebitda(financials: dict) -> float:
103
+ for timestamp, data in financials.items():
104
+ if 'EBITDA' in data:
105
+ return data['EBITDA']
106
+ return None
107
+
108
+ symbol_ebitda = get_ebitda(financials)
109
+
110
+ def get_gross_profit(financials: dict) -> float:
111
+ for timestamp, data in financials.items():
112
+ if 'Gross Profit' in data:
113
+ return data['Gross Profit']
114
+ return None
115
+
116
+ gross_profit = get_gross_profit(financials)
117
+
118
+ def get_operating_income(financials: dict) -> float:
119
+ for timestamp, data in financials.items():
120
+ if 'Operating Income' in data:
121
+ return data['Operating Income']
122
+ return None
123
+
124
+ operating_income = get_operating_income(financials)
125
+
126
+ def get_operating_revenue(financials: dict) -> float:
127
+ for timestamp, data in financials.items():
128
+ if 'Operating Revenue' in data:
129
+ return data['Operating Revenue']
130
+ return None
131
+
132
+ operating_revenue = get_operating_revenue(financials)
133
+
134
+ def get_total_equity(balance_sheet: dict) -> float:
135
+ for timestamp, data in balance_sheet.items():
136
+ if 'Total Equity Gross Minority Interest' in data:
137
+ return data['Total Equity Gross Minority Interest']
138
+ return None
139
+
140
+ total_equity = get_total_equity(balance_sheet)
141
+ debt_to_equity = (total_debt / total_equity) if total_debt and total_equity else None
142
+
143
+ formatted_data = f"""
144
+ COMPANY INFORMATION:
145
+ Company Name: {info.get('longName', 'N/A')}
146
+ Symbol: {info.get('symbol', 'N/A')}
147
+ Sector: {info.get('sector', 'N/A')}
148
+ Industry: {info.get('industry', 'N/A')}
149
+ Market Cap: {format_currency(info.get('marketCap'))}
150
+ Employees: {info.get('fullTimeEmployees', 'N/A')}
151
+
152
+ CURRENT PRICE: {format_currency(current_price)} (Source: Yahoo Finance)
153
+
154
+ FINANCIAL HIGHLIGHTS:
155
+ 52 Week High: {format_currency(info.get('fiftyTwoWeekHigh'))}
156
+ 52 Week Low: {format_currency(info.get('fiftyTwoWeekLow'))}
157
+ P/E Ratio: {info.get('trailingPE', 'N/A')}
158
+ Book Value: {format_currency(info.get('bookValue'))}
159
+ Dividend Yield: {info.get('dividendYield', 'N/A')}%
160
+
161
+ FINANCIAL STATEMENTS:
162
+ Revenue (Latest): {format_currency(total_revenue)}
163
+ Net Income (Latest): {format_currency(net_income)}
164
+ Total Assets (Latest): {format_currency(total_assets)}
165
+ Total Debt (Latest): {format_currency(total_debt)}
166
+ Total Equity (Latest): {format_currency(total_equity)}
167
+ Debt to Equity Ratio: {(f"{debt_to_equity:.2f}" if debt_to_equity else "N/A")}
168
+ Total Liabilities: {format_currency(total_liabilities)}
169
+ Shareholders Equity: {format_currency(shareholders_equity)}
170
+ EBITDA: {(format_currency(symbol_ebitda) if symbol_ebitda else "N/A")}
171
+ Gross Profit: {format_currency(gross_profit)}
172
+ Operating Income: {format_currency(operating_income)}
173
+ Operating Revenue: {format_currency(operating_revenue)}
174
+
175
+ BUSINESS SUMMARY:
176
+ {info.get('longBusinessSummary', 'N/A')}
177
+
178
+ GOVERNANCE:
179
+ Board Members: {len(info.get('companyOfficers', []))} officers listed
180
+ Audit Risk: {info.get('auditRisk', 'N/A')}
181
+ Board Risk: {info.get('boardRisk', 'N/A')}
182
+ Compensation Risk: {info.get('compensationRisk', 'N/A')}
183
+ Shareholder Rights Risk: {info.get('shareHolderRightsRisk', 'N/A')}
184
+ Overall Risk: {info.get('overallRisk', 'N/A')}
185
+ """
186
+
187
+ return formatted_data.strip()
188
+
189
+ except Exception as e:
190
+ return f"Error formatting stock data: {str(e)}"
191
+
192
+ def run_swarm(swarm_config):
193
+ """Execute a swarm with the provided configuration."""
194
+ try:
195
+ response = requests.post(
196
+ f"{BASE_URL}/v1/swarm/completions",
197
+ headers=headers,
198
+ json=swarm_config
199
+ )
200
+ return response.json()
201
+ except Exception as e:
202
+ return {"error": str(e)}
203
+
204
+ def create_indian_compliance_swarm(financial_data, company_info):
205
+ """Create a swarm for Indian financial compliance assistance."""
206
+
207
+ DOCUMENTATION_ANALYZER_PROMPT = """
208
+ You are a financial documentation specialist with expertise in Indian financial reporting standards and regulations.
209
+ Your role is to analyze financial statements and disclosures for compliance with Indian requirements.
210
+ Your tasks include:
211
+ 1. Reviewing financial statements for completeness under Indian Accounting Standards (Ind AS) or AS
212
+ 2. Analyzing annual reports and board reports for mandatory disclosures
213
+ 3. Checking compliance with Companies Act 2013 disclosure requirements
214
+ 4. Verifying CSR reporting and ESG disclosures as per Indian regulations
215
+ 5. Ensuring proper disclosure of related party transactions under Indian law
216
+ 6. Reviewing audit reports and internal financial control assessments
217
+ 7. Checking compliance with SEBI disclosure norms (for listed companies)
218
+ 8. Analyzing tax provisions and deferred tax disclosures under Indian tax laws
219
+
220
+ Focus on Indian regulatory framework and provide findings specific to Indian compliance requirements.
221
+ """
222
+
223
+ ACCOUNTING_STANDARDS_PROMPT = """
224
+ You are an expert in Indian Accounting Standards (Ind AS) and legacy Accounting Standards (AS) with deep knowledge of Indian GAAP requirements.
225
+ Your responsibility is to ensure financial statements comply with applicable Indian accounting frameworks.
226
+ Your tasks include:
227
+ 1. Analyzing compliance with applicable Ind AS or AS standards
228
+ 2. Reviewing revenue recognition under Ind AS 115 or AS 9
229
+ 3. Checking financial instrument accounting under Ind AS 109 or AS 30/31/32
230
+ 4. Evaluating lease accounting under Ind AS 116 or AS 19
231
+ 5. Reviewing impairment assessments under Ind AS 36 or AS 28
232
+ 6. Analyzing consolidation requirements under Ind AS 110/111 or AS 21/23/27
233
+ 7. Checking fair value measurements and disclosures under Ind AS 113
234
+ 8. Ensuring proper segment reporting under Ind AS 108 or AS 17
235
+ 9. Reviewing first-time adoption issues for Ind AS transition
236
+
237
+ Reference specific Indian accounting standards and consider MCA notifications and clarifications.
238
+ """
239
+
240
+ REGULATORY_COMPLIANCE_PROMPT = """
241
+ You are a senior regulatory compliance expert specializing in Indian financial regulations and corporate law.
242
+ Your expertise covers Companies Act 2013, SEBI regulations, RBI guidelines, and other Indian regulatory frameworks.
243
+ Your responsibilities include:
244
+ 1. Ensuring compliance with Companies Act 2013 provisions and rules
245
+ 2. Verifying SEBI LODR (Listing Obligations and Disclosure Requirements) compliance
246
+ 3. Checking RBI guidelines compliance (for applicable sectors)
247
+ 4. Reviewing corporate governance disclosures as per Indian regulations
248
+ 5. Analyzing CSR compliance and reporting under Section 135 of Companies Act
249
+ 6. Verifying board composition and audit committee requirements
250
+ 7. Checking compliance with insider trading regulations (SEBI PIT)
251
+ 8. Reviewing related party transaction approvals and disclosures
252
+ 9. Ensuring proper filing requirements with MCA and SEBI
253
+ 10. Analyzing compliance with sectoral regulations (banking, insurance, etc.)
254
+
255
+ Focus on Indian regulatory environment and recent updates to regulations and compliance requirements.
256
+ """
257
+
258
+ swarm_config = {
259
+ "name": "Indian Financial Compliance Assistant",
260
+ "description": "A specialized swarm for Indian financial regulatory compliance",
261
+ "agents": [
262
+ {
263
+ "agent_name": "Indian Documentation Analyzer",
264
+ "description": "Reviews financial statements for Indian compliance requirements",
265
+ "system_prompt": DOCUMENTATION_ANALYZER_PROMPT,
266
+ "model_name": "gpt-4o",
267
+ "role": "worker",
268
+ "max_loops": 1,
269
+ "max_tokens": 4096,
270
+ "temperature": 0.5,
271
+ "auto_generate_prompt": False,
272
+ },
273
+ {
274
+ "agent_name": "Indian Accounting Standards Expert",
275
+ "description": "Evaluates compliance with Ind AS/AS requirements",
276
+ "system_prompt": ACCOUNTING_STANDARDS_PROMPT,
277
+ "model_name": "gpt-4o",
278
+ "role": "worker",
279
+ "max_loops": 1,
280
+ "max_tokens": 4096,
281
+ "temperature": 0.5,
282
+ "auto_generate_prompt": False,
283
+ },
284
+ {
285
+ "agent_name": "Indian Regulatory Compliance Specialist",
286
+ "description": "Assesses adherence to Indian regulatory frameworks",
287
+ "system_prompt": REGULATORY_COMPLIANCE_PROMPT,
288
+ "model_name": "gpt-4o",
289
+ "role": "worker",
290
+ "max_loops": 1,
291
+ "max_tokens": 4096,
292
+ "temperature": 0.5,
293
+ "auto_generate_prompt": False,
294
+ }
295
+ ],
296
+ "max_loops": 1,
297
+ "swarm_type": "SequentialWorkflow",
298
+ "task": f"""
299
+ Analyze the following financial information for an Indian company ({company_info}) and provide a comprehensive compliance assessment according to Indian regulations:
300
+
301
+ {financial_data}
302
+
303
+ For your compliance evaluation, provide:
304
+ 1. Assessment of compliance with Indian Accounting Standards (Ind AS/AS)
305
+ 2. Analysis of Companies Act 2013 compliance requirements
306
+ 3. Review of SEBI regulations compliance (if applicable)
307
+ 4. Evaluation of corporate governance and disclosure requirements
308
+ 5. Assessment of CSR and ESG reporting compliance
309
+ 6. Identification of potential compliance risks specific to Indian regulations
310
+ 7. Recommendations for improving compliance with Indian standards
311
+
312
+ Focus specifically on Indian regulatory framework and recent regulatory updates.
313
+ """
314
+ }
315
+
316
+ return run_swarm(swarm_config)
317
+
318
+ def create_comprehensive_csv_data(data_source, company_info, accounting_standards, regulatory_frameworks, result):
319
+ """Create comprehensive CSV data with all analysis information"""
320
+
321
+ # Extract company information
322
+ company_parts = company_info.split(" in the ")
323
+ company_type = company_parts[0] if len(company_parts) > 0 else "N/A"
324
+ industry_sector = company_parts[1].split(", classified as")[0] if len(company_parts) > 1 else "N/A"
325
+ company_size = company_parts[1].split("classified as ")[1].split(", for")[0] if len(company_parts) > 1 else "N/A"
326
+ financial_year = company_parts[1].split("for ")[-1] if len(company_parts) > 1 else "N/A"
327
+
328
+ # Create comprehensive data structure
329
+ comprehensive_data = []
330
+
331
+ # 1. Basic Information
332
+ comprehensive_data.append({
333
+ 'Category': 'Basic Information',
334
+ 'Field': 'Analysis Timestamp',
335
+ 'Value': datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
336
+ 'Details': 'Time when analysis was performed',
337
+ 'Priority': '',
338
+ 'Timeline': '',
339
+ 'Regulation': ''
340
+ })
341
+
342
+ comprehensive_data.append({
343
+ 'Category': 'Basic Information',
344
+ 'Field': 'Data Source',
345
+ 'Value': data_source,
346
+ 'Details': 'Source of financial data used for analysis',
347
+ 'Priority': '',
348
+ 'Timeline': '',
349
+ 'Regulation': ''
350
+ })
351
+
352
+ comprehensive_data.append({
353
+ 'Category': 'Basic Information',
354
+ 'Field': 'Company Type',
355
+ 'Value': company_type,
356
+ 'Details': 'Legal structure of the company',
357
+ 'Priority': '',
358
+ 'Timeline': '',
359
+ 'Regulation': ''
360
+ })
361
+
362
+ comprehensive_data.append({
363
+ 'Category': 'Basic Information',
364
+ 'Field': 'Industry Sector',
365
+ 'Value': industry_sector,
366
+ 'Details': 'Primary business sector',
367
+ 'Priority': '',
368
+ 'Timeline': '',
369
+ 'Regulation': ''
370
+ })
371
+
372
+ comprehensive_data.append({
373
+ 'Category': 'Basic Information',
374
+ 'Field': 'Company Size',
375
+ 'Value': company_size,
376
+ 'Details': 'Classification based on turnover and capital',
377
+ 'Priority': '',
378
+ 'Timeline': '',
379
+ 'Regulation': ''
380
+ })
381
+
382
+ comprehensive_data.append({
383
+ 'Category': 'Basic Information',
384
+ 'Field': 'Financial Year',
385
+ 'Value': financial_year,
386
+ 'Details': 'Reporting period under analysis',
387
+ 'Priority': '',
388
+ 'Timeline': '',
389
+ 'Regulation': ''
390
+ })
391
+
392
+ comprehensive_data.append({
393
+ 'Category': 'Basic Information',
394
+ 'Field': 'Accounting Standards',
395
+ 'Value': accounting_standards,
396
+ 'Details': 'Applicable accounting framework',
397
+ 'Priority': '',
398
+ 'Timeline': '',
399
+ 'Regulation': ''
400
+ })
401
+
402
+ comprehensive_data.append({
403
+ 'Category': 'Basic Information',
404
+ 'Field': 'Regulatory Frameworks',
405
+ 'Value': ', '.join(regulatory_frameworks),
406
+ 'Details': 'Applicable regulatory requirements',
407
+ 'Priority': '',
408
+ 'Timeline': '',
409
+ 'Regulation': ''
410
+ })
411
+
412
+ # 2. AI Analysis Results (if available)
413
+ if isinstance(result, dict) and 'response' in result:
414
+ comprehensive_data.append({
415
+ 'Category': 'AI Analysis Results',
416
+ 'Field': 'Full Analysis Response',
417
+ 'Value': 'AI Generated Compliance Analysis',
418
+ 'Details': result['response'][:1000] + '...' if len(result['response']) > 1000 else result['response'],
419
+ 'Priority': '',
420
+ 'Timeline': '',
421
+ 'Regulation': ''
422
+ })
423
+
424
+ return pd.DataFrame(comprehensive_data)
425
+
426
+ def main():
427
+ st.set_page_config(
428
+ page_title="Indian Financial Compliance System",
429
+ page_icon="🇮🇳",
430
+ layout="wide",
431
+ initial_sidebar_state="expanded"
432
+ )
433
+
434
+ # Initialize data provider
435
+ if 'data_provider' not in st.session_state:
436
+ st.session_state.data_provider = IndianDataProvider()
437
+
438
+ # Header
439
+ st.title("🇮🇳 Indian Financial Compliance & Regulatory System")
440
+ st.markdown("AI-Powered Multi-Agent Financial Compliance Analysis for Indian Companies")
441
+
442
+ # Sidebar Configuration
443
+ with st.sidebar:
444
+ st.header("Configuration")
445
+
446
+ # API Key Check
447
+ if not API_KEY:
448
+ st.error("SWARMS_API_KEY not found in environment variables")
449
+ st.info("Please set your API key in the .env file")
450
+ return
451
+ else:
452
+ st.success("API Key configured")
453
+
454
+ st.divider()
455
+
456
+ # Data Source Selection
457
+ st.subheader("📊 Data Source")
458
+ data_source = st.selectbox(
459
+ "Choose Data Source",
460
+ [
461
+ "Manual Input",
462
+ "NSE Listed Company (Live Data)"
463
+ ],
464
+ help="Select how you want to input financial data"
465
+ )
466
+
467
+ financial_data = ""
468
+ company_info_auto = ""
469
+
470
+ # Handle different data sources
471
+ if data_source == "NSE Listed Company (Live Data)":
472
+ st.subheader("🔍 NSE Stock Data")
473
+
474
+ # Popular Indian stocks for quick selection
475
+ popular_stocks = [
476
+ 'ADANIENT', 'ADANIPORTS', 'APOLLOHOSP', 'ASIANPAINT',
477
+ 'AXISBANK', 'BAJAJ-AUTO', 'BAJFINANCE', 'BAJAJFINSV',
478
+ 'BEL', 'BHARTIARTL', 'CIPL', 'COALINDIA', 'DRREDDY',
479
+ 'EICHERMOT', 'GRASIM', 'HCLTECH', 'HDFCBANK', 'HDFCLIFE',
480
+ 'HEROMOTOCO', 'HINDALCO', 'HINDUNILVR', 'ICICIBANK',
481
+ 'INDUSINDBK', 'INFY', 'ITC', 'JIOFIN', 'JSWSTEEL',
482
+ 'KOTAKBANK', 'LT', 'M&M', 'MARUTI', 'NESTLEIND',
483
+ 'NTPC', 'ONGC', 'POWERGRID', 'RELIANCE', 'SBILIFE',
484
+ 'SHRIRAMFIN', 'SBIN', 'SUNPHARMA', 'TATACONSUM', 'TCS',
485
+ 'TATAMOTORS', 'TATASTEEL', 'TECHM', 'TITAN', 'TRENT',
486
+ 'ULTRACEMCO', 'WIPRO'
487
+ ]
488
+
489
+ col1, col2 = st.columns(2)
490
+ with col1:
491
+ stock_symbol = st.selectbox(
492
+ "Popular NSE Stocks",
493
+ [""] + popular_stocks,
494
+ help="Select from popular stocks"
495
+ )
496
+
497
+ with col2:
498
+ custom_symbol = st.text_input(
499
+ "Enter Custom Symbol",
500
+ placeholder="e.g., WIPRO",
501
+ help="Enter NSE stock symbol"
502
+ )
503
+
504
+ # Use custom symbol if provided, otherwise use selected
505
+ symbol_to_fetch = custom_symbol.upper() if custom_symbol else stock_symbol
506
+
507
+ if symbol_to_fetch and st.button("🚀 Fetch Live NSE Data", type="primary"):
508
+ with st.spinner(f"Fetching live data for {symbol_to_fetch}..."):
509
+ stock_data = st.session_state.data_provider.get_nse_stock_data(symbol_to_fetch)
510
+
511
+ if stock_data.get('success'):
512
+ st.success(f"✅ Successfully fetched data for {symbol_to_fetch}")
513
+ financial_data = st.session_state.data_provider.format_stock_data_for_analysis(stock_data)
514
+ company_info_auto = f"NSE Listed Company - {stock_data['info'].get('longName', symbol_to_fetch)} in {stock_data['info'].get('sector', 'Unknown')} sector"
515
+
516
+ # Display quick preview with directly extracted metrics
517
+ with st.expander("📋 Data Preview"):
518
+ col_prev1, col_prev2 = st.columns(2)
519
+ with col_prev1:
520
+ st.metric("Market Cap", f"₹{stock_data['info'].get('marketCap', 0):,}")
521
+ st.metric("Current Price", f"₹{stock_data.get('current_price', 0):,.2f}")
522
+ with col_prev2:
523
+ st.metric("Revenue", f"₹{stock_data.get('total_revenue', 0):,.2f}")
524
+ st.metric("Net Income", f"₹{stock_data.get('net_income', 0):,.2f}")
525
+
526
+ # Show data source info
527
+ st.info(f"📊 Data Source: {stock_data.get('price_source', 'Unknown')}")
528
+
529
+ else:
530
+ st.error(f"❌ Failed to fetch data: {stock_data.get('error', 'Unknown error')}")
531
+
532
+ st.divider()
533
+
534
+ # Company Information (Auto-filled or Manual)
535
+ st.subheader("🏢 Company Information")
536
+
537
+ if company_info_auto:
538
+ st.info(f"Auto-detected: {company_info_auto}")
539
+ company_info = company_info_auto
540
+ else:
541
+ company_type = st.selectbox(
542
+ "Company Type",
543
+ [
544
+ "Public Limited Company",
545
+ "Private Limited Company",
546
+ "Listed Company",
547
+ "Unlisted Public Company",
548
+ "Small Company",
549
+ "One Person Company (OPC)",
550
+ "Section 8 Company (Non-Profit)",
551
+ "Government Company",
552
+ "Foreign Company"
553
+ ]
554
+ )
555
+
556
+ industry = st.selectbox(
557
+ "Industry Sector",
558
+ [
559
+ "Information Technology",
560
+ "Banking & Financial Services",
561
+ "Pharmaceuticals",
562
+ "Automobile",
563
+ "Textiles",
564
+ "Steel & Metal",
565
+ "Oil & Gas",
566
+ "Telecommunications",
567
+ "Real Estate",
568
+ "Infrastructure",
569
+ "Consumer Goods",
570
+ "Healthcare",
571
+ "Education",
572
+ "Agriculture",
573
+ "Other"
574
+ ]
575
+ )
576
+
577
+ company_size = st.selectbox(
578
+ "Company Size",
579
+ [
580
+ "Small Company (Turnover ≤ ₹20 Cr, Paid-up Capital ≤ ₹2 Cr)",
581
+ "Medium Company",
582
+ "Large Company",
583
+ "Listed Company",
584
+ "Multinational Company"
585
+ ]
586
+ )
587
+
588
+ financial_year = st.selectbox(
589
+ "Financial Year",
590
+ ["FY 2024-25", "FY 2023-24", "FY 2022-23", "FY 2021-22"]
591
+ )
592
+
593
+ company_info = f"{company_type} in the {industry} sector, classified as {company_size}, for {financial_year}"
594
+
595
+ # Applicable Standards
596
+ st.subheader("📋 Standards & Regulations")
597
+
598
+ accounting_standards = st.selectbox(
599
+ "Accounting Standards",
600
+ [
601
+ "Indian Accounting Standards (Ind AS)",
602
+ "Accounting Standards (AS) - Old GAAP",
603
+ "Both Ind AS and AS (Transition period)"
604
+ ]
605
+ )
606
+
607
+ regulatory_frameworks = st.multiselect(
608
+ "Applicable Regulations",
609
+ [
610
+ "Companies Act 2013",
611
+ "SEBI LODR Regulations",
612
+ "SEBI ICDR Regulations",
613
+ "RBI Guidelines",
614
+ "FEMA Regulations",
615
+ "Income Tax Act 1961",
616
+ "GST Regulations",
617
+ "RERA (Real Estate)",
618
+ "Insurance Regulatory Act",
619
+ "Banking Regulation Act"
620
+ ],
621
+ default=["Companies Act 2013"]
622
+ )
623
+
624
+ # Main Content Area
625
+ col1, col2 = st.columns([2, 1])
626
+
627
+ with col1:
628
+ st.subheader("📄 Financial Data Input")
629
+
630
+ if data_source == "Manual Input" or not financial_data:
631
+ # Manual input tabs
632
+ tab1, tab2 = st.tabs(["✍️ Text Input", "📁 File Upload"])
633
+
634
+ with tab1:
635
+ financial_data = st.text_area(
636
+ "Enter Financial Statements and Related Information",
637
+ value=financial_data,
638
+ height=400,
639
+ placeholder="""Enter your Indian financial data here, such as:
640
+ • Balance Sheet as per Schedule III of Companies Act 2013
641
+ • Statement of Profit & Loss
642
+ • Cash Flow Statement
643
+ • Statement of Changes in Equity
644
+ • Notes to Financial Statements
645
+ • Board's Report
646
+ • Management Discussion & Analysis (MD&A)
647
+ • Corporate Governance Report
648
+ • CSR Report
649
+ • Auditor's Report
650
+ • Internal Financial Control Report
651
+ • Related Party Transactions
652
+ • Segment Reporting (if applicable)
653
+ • Subsidiary/Associate company details"""
654
+ )
655
+
656
+ with tab2:
657
+ uploaded_file = st.file_uploader(
658
+ "Upload Financial Document",
659
+ type=['txt'],
660
+ help="Upload annual reports, financial statements, or compliance documents"
661
+ )
662
+
663
+ if uploaded_file is not None:
664
+ if uploaded_file.type == "text/plain":
665
+ financial_data = str(uploaded_file.read(), "utf-8")
666
+ st.success(f"✅ File uploaded: {uploaded_file.name}")
667
+ else:
668
+ # Display auto-fetched data with option to edit
669
+ with st.expander("📊 Auto-Fetched Financial Data (Click to view/edit)", expanded=False):
670
+ financial_data = st.text_area(
671
+ "Financial Data (Auto-fetched - you can edit if needed)",
672
+ value=financial_data,
673
+ height=300
674
+ )
675
+
676
+ st.info(f"✅ Using data from: {data_source}")
677
+
678
+ with col2:
679
+ st.subheader("📊 Analysis Dashboard")
680
+
681
+ # Quick metrics
682
+ if 'compliance_result' in st.session_state:
683
+ st.metric("Compliance Status", "Analyzed", "✓")
684
+ st.metric("Data Source", data_source)
685
+ st.metric("Analysis Count", len(st.session_state.get('analysis_history', [])))
686
+ else:
687
+ st.info("Analysis metrics will appear after running compliance check")
688
+
689
+ # Data source info
690
+ st.subheader("ℹ️ Current Configuration")
691
+ st.write(f"**Data Source:** {data_source}")
692
+ st.write(f"**Accounting Standards:** {accounting_standards}")
693
+ st.write(f"**Regulations:** {', '.join(regulatory_frameworks[:2])}{'...' if len(regulatory_frameworks) > 2 else ''}")
694
+
695
+ # Analysis History
696
+ st.subheader("📚 Recent Analyses")
697
+ if 'analysis_history' not in st.session_state:
698
+ st.session_state.analysis_history = []
699
+
700
+ if st.session_state.analysis_history:
701
+ for i, analysis in enumerate(st.session_state.analysis_history[-3:]):
702
+ with st.expander(f"Analysis {len(st.session_state.analysis_history) - i}"):
703
+ st.text(f"Date: {analysis['timestamp']}")
704
+ st.text(f"Source: {analysis['data_source']}")
705
+ st.text(f"Company: {analysis['company_info'][:50]}...")
706
+ st.text(f"Status: {analysis['status']}")
707
+ else:
708
+ st.info("No previous analyses")
709
+
710
+ # Analysis Controls
711
+ st.divider()
712
+
713
+ col_run, col_options = st.columns([1, 2])
714
+
715
+ with col_run:
716
+ run_analysis = st.button(
717
+ "🚀 Run Indian Compliance Analysis",
718
+ type="primary",
719
+ use_container_width=True,
720
+ disabled=not bool(financial_data.strip())
721
+ )
722
+
723
+ with col_options:
724
+ with st.expander("⚙️ Advanced Options"):
725
+ col_adv1, col_adv2 = st.columns(2)
726
+ with col_adv1:
727
+ focus_areas = st.multiselect(
728
+ "Focus Areas",
729
+ [
730
+ "Revenue Recognition (Ind AS 115)",
731
+ "Related Party Transactions",
732
+ "Corporate Social Responsibility",
733
+ "Board Governance",
734
+ "Audit Committee Compliance",
735
+ "Segment Reporting",
736
+ "Consolidation Requirements"
737
+ ]
738
+ )
739
+ with col_adv2:
740
+ analysis_depth = st.selectbox(
741
+ "Analysis Depth",
742
+ ["Standard", "Detailed", "Comprehensive"]
743
+ )
744
+
745
+ # Run Analysis
746
+ if run_analysis:
747
+ if not financial_data.strip():
748
+ st.error("⚠️ Please provide financial data to analyze")
749
+ return
750
+
751
+ with st.spinner("🔄 Running multi-agent Indian compliance analysis..."):
752
+ # Progress tracking
753
+ progress_bar = st.progress(0)
754
+ status_text = st.empty()
755
+
756
+ status_text.text("🤖 Initializing Indian compliance agents...")
757
+ progress_bar.progress(20)
758
+ time.sleep(1)
759
+
760
+ status_text.text("📋 Analyzing documentation compliance...")
761
+ progress_bar.progress(40)
762
+ time.sleep(1)
763
+
764
+ status_text.text("📊 Evaluating Indian accounting standards...")
765
+ progress_bar.progress(60)
766
+ time.sleep(1)
767
+
768
+ status_text.text("⚖️ Checking regulatory compliance...")
769
+ progress_bar.progress(80)
770
+ time.sleep(1)
771
+
772
+ # Run the analysis
773
+ result = create_indian_compliance_swarm(financial_data, company_info)
774
+
775
+ progress_bar.progress(100)
776
+ status_text.text("✅ Analysis complete!")
777
+ time.sleep(1)
778
+
779
+ # Clear progress indicators
780
+ progress_bar.empty()
781
+ status_text.empty()
782
+
783
+ # Store results
784
+ st.session_state.compliance_result = result
785
+
786
+ # Add to history
787
+ st.session_state.analysis_history.append({
788
+ 'timestamp': datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
789
+ 'data_source': data_source,
790
+ 'company_info': company_info,
791
+ 'status': 'Completed'
792
+ })
793
+
794
+ # Display Results
795
+ if 'compliance_result' in st.session_state:
796
+ st.divider()
797
+ st.header("📊 Indian Compliance Analysis Results")
798
+
799
+ result = st.session_state.compliance_result
800
+
801
+ if "error" in result:
802
+ st.error(f"❌ Analysis failed: {result['error']}")
803
+ return
804
+
805
+ # Results tabs
806
+ tab1, tab2, tab3 = st.tabs([
807
+ "📋 Executive Summary",
808
+ "🔍 Detailed Analysis",
809
+ "⚖️ Risk Assessment"
810
+ ])
811
+
812
+ with tab1:
813
+ st.subheader("Executive Summary")
814
+
815
+ # Display actual API results
816
+ st.subheader("🤖 AI Analysis Output")
817
+ if isinstance(result, dict) and 'response' in result:
818
+ with st.container():
819
+ st.markdown("---")
820
+ st.write(result['response'])
821
+ else:
822
+ with st.expander("Raw API Response"):
823
+ st.json(result)
824
+
825
+ with tab2:
826
+ st.subheader("🔍 Detailed Agent Analysis")
827
+
828
+ agents = [
829
+ ("📋", "Indian Documentation Analyzer", "Documentation compliance assessment"),
830
+ ("📊", "Indian Accounting Standards Expert", "Accounting standards evaluation"),
831
+ ("⚖️", "Indian Regulatory Compliance Specialist", "Regulatory compliance review")
832
+ ]
833
+
834
+ for icon, agent, description in agents:
835
+ with st.expander(f"{icon} {agent} Results"):
836
+ st.write(f"**Agent:** {agent}")
837
+ st.write(f"**Focus:** {description}")
838
+
839
+ if "Documentation" in agent:
840
+ st.write("**Key Areas Reviewed:**")
841
+ st.write("• Annual report completeness assessment")
842
+ st.write("• Board report adequacy review")
843
+ st.write("• Mandatory disclosure verification")
844
+ st.write("• CSR reporting compliance")
845
+ elif "Accounting" in agent:
846
+ st.write("**Standards Evaluated:**")
847
+ st.write("• Ind AS/AS compliance evaluation")
848
+ st.write("• Revenue recognition analysis")
849
+ st.write("• Financial instrument accounting review")
850
+ st.write("• Consolidation requirements check")
851
+ else:
852
+ st.write("**Regulations Assessed:**")
853
+ st.write("• Companies Act 2013 compliance")
854
+ st.write("• SEBI regulation adherence")
855
+ st.write("• Corporate governance assessment")
856
+ st.write("• Filing requirements validation")
857
+
858
+ with tab3:
859
+ st.subheader("⚖️ Indian Regulatory Risk Assessment")
860
+
861
+ # Risk categories specific to Indian context
862
+ risk_data = {
863
+ 'Risk Area': [
864
+ 'Companies Act Compliance',
865
+ 'Ind AS Implementation',
866
+ 'SEBI Regulations',
867
+ 'CSR Compliance',
868
+ 'Corporate Governance',
869
+ 'Tax Compliance'
870
+ ],
871
+ 'Risk Level': ['Medium', 'Low', 'Medium', 'High', 'Low', 'Medium'],
872
+ 'Impact Score': [7, 4, 6, 9, 3, 5],
873
+ 'Likelihood Score': [5, 3, 6, 8, 2, 4]
874
+ }
875
+
876
+ df_risk = pd.DataFrame(risk_data)
877
+
878
+ # Risk matrix visualization
879
+ fig = px.scatter(
880
+ df_risk,
881
+ x='Impact Score',
882
+ y='Likelihood Score',
883
+ color='Risk Level',
884
+ size='Impact Score',
885
+ hover_data=['Risk Area'],
886
+ title="Indian Regulatory Risk Matrix",
887
+ color_discrete_map={'High': '#FF6B6B', 'Medium': '#FFD93D', 'Low': '#6BCF7F'},
888
+ labels={'Impact Score': 'Impact →', 'Likelihood Score': 'Likelihood →'}
889
+ )
890
+
891
+ fig.update_layout(
892
+ xaxis_range=[0, 10],
893
+ yaxis_range=[0, 10],
894
+ height=500
895
+ )
896
+
897
+ st.plotly_chart(fig, use_container_width=True)
898
+
899
+ st.subheader("📊 Risk Summary Table")
900
+ st.dataframe(df_risk, use_container_width=True)
901
+
902
+ # Export functionality
903
+ st.divider()
904
+ st.subheader("📤 Export Results")
905
+
906
+ col_exp1, col_exp2 = st.columns(2)
907
+
908
+ with col_exp1:
909
+ # Create comprehensive CSV data
910
+ comprehensive_df = create_comprehensive_csv_data(
911
+ data_source, company_info, accounting_standards, regulatory_frameworks, result
912
+ )
913
+ csv_data = comprehensive_df.to_csv(index=False)
914
+
915
+ st.download_button(
916
+ "📋 Download Analysis CSV",
917
+ data=csv_data,
918
+ file_name=f"compliance_analysis_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv",
919
+ mime="text/csv"
920
+ )
921
+
922
+ # Show preview of CSV data
923
+ with st.expander("📊 CSV Data Preview"):
924
+ st.dataframe(comprehensive_df, use_container_width=True, height=300)
925
+
926
+ with col_exp2:
927
+ json_result = json.dumps(result, indent=2)
928
+ st.download_button(
929
+ "💾 Download JSON",
930
+ data=json_result,
931
+ file_name=f"indian_compliance_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json",
932
+ mime="application/json"
933
+ )
934
+
935
+ if __name__ == "__main__":
936
+ main()