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

Upload 12 files

Browse files
.env ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ SWARMS_API_KEY=sk-f763a9c6f898aa3ec74bf49047736a0201c293eefc36d5a04be8af647b93b711
2
+ # NEWS_API_KEY=6d6fd49d048547b7be0c9ece576e24f3
app/__init__.py ADDED
File without changes
app/api/__init__.py ADDED
File without changes
app/api/endpoints.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+ from fastapi.responses import StreamingResponse
3
+ from datetime import datetime
4
+ from fastapi import APIRouter, HTTPException
5
+ from app.core.data_provider import IndianDataProvider
6
+ from app.core.swarms_client import create_indian_compliance_swarm
7
+ from app.models.schemas import (
8
+ StockDataRequest, StockDataResponse,
9
+ ComplianceAnalysisRequest, ComplianceAnalysisResponse, GenerateCSVRequest
10
+ )
11
+ from app.utils.helpers import create_comprehensive_csv_data
12
+
13
+ router = APIRouter()
14
+ data_provider = IndianDataProvider()
15
+
16
+ @router.post("/stock-data", response_model=StockDataResponse)
17
+ async def get_stock_data(request: StockDataRequest):
18
+ """Fetch NSE stock data for a given symbol"""
19
+ try:
20
+ stock_data = data_provider.get_nse_stock_data(request.symbol)
21
+
22
+ if not stock_data.get('success'):
23
+ return StockDataResponse(
24
+ success=False,
25
+ error=stock_data.get('error', 'Unknown error')
26
+ )
27
+
28
+ formatted_data = data_provider.format_stock_data_for_analysis(stock_data)
29
+
30
+ return StockDataResponse(
31
+ success=True,
32
+ data=stock_data,
33
+ formatted_data=formatted_data
34
+ )
35
+ except Exception as e:
36
+ raise HTTPException(status_code=500, detail=f"Error fetching stock data: {str(e)}")
37
+
38
+ @router.post("/compliance-analysis", response_model=ComplianceAnalysisResponse)
39
+ async def run_compliance_analysis(request: ComplianceAnalysisRequest):
40
+ """Run compliance analysis on financial data"""
41
+ try:
42
+ result = create_indian_compliance_swarm(
43
+ request.financial_data,
44
+ request.company_info
45
+ )
46
+
47
+ if "error" in result:
48
+ return ComplianceAnalysisResponse(
49
+ success=False,
50
+ error=result["error"]
51
+ )
52
+
53
+ return ComplianceAnalysisResponse(
54
+ success=True,
55
+ result=result
56
+ )
57
+ except Exception as e:
58
+ raise HTTPException(status_code=500, detail=f"Error running compliance analysis: {str(e)}")
59
+
60
+ # Update the generate-csv endpoint
61
+ @router.post("/generate-csv")
62
+ async def generate_csv_report(request: GenerateCSVRequest):
63
+ """Generate CSV report for compliance analysis and return as downloadable file"""
64
+ try:
65
+ df = create_comprehensive_csv_data(
66
+ request.data_source,
67
+ request.company_info,
68
+ request.accounting_standards,
69
+ request.regulatory_frameworks,
70
+ request.result
71
+ )
72
+
73
+ # Create a stream for the CSV data
74
+ stream = io.StringIO()
75
+ df.to_csv(stream, index=False)
76
+
77
+ # Create a response that will download the CSV file
78
+ response = StreamingResponse(
79
+ iter([stream.getvalue()]),
80
+ media_type="text/csv",
81
+ headers={
82
+ "Content-Disposition": f"attachment; filename=compliance_report_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv"
83
+ }
84
+ )
85
+
86
+ return response
87
+
88
+ except Exception as e:
89
+ raise HTTPException(status_code=500, detail=f"Error generating CSV: {str(e)}")
90
+
91
+ @router.get("/popular-stocks")
92
+ async def get_popular_stocks():
93
+ """Get list of popular NSE stocks"""
94
+ popular_stocks = [
95
+ 'ADANIENT', 'ADANIPORTS', 'APOLLOHOSP', 'ASIANPAINT',
96
+ 'AXISBANK', 'BAJAJ-AUTO', 'BAJFINANCE', 'BAJAJFINSV',
97
+ 'BEL', 'BHARTIARTL', 'CIPL', 'COALINDIA', 'DRREDDY',
98
+ 'EICHERMOT', 'GRASIM', 'HCLTECH', 'HDFCBANK', 'HDFCLIFE',
99
+ 'HINDALCO', 'HINDUNILVR', 'ICICIBANK', 'INFY', 'ITC',
100
+ 'JIOFIN', 'JSWSTEEL', 'KOTAKBANK', 'LT', 'M&M', 'MARUTI',
101
+ 'MAXHEALTH', 'NESTLEIND', 'NTPC', 'ONGC', 'POWERGRID',
102
+ 'RELIANCE', 'SBILIFE', 'SBIN', 'SHRIRAMFIN', 'SUNPHARMA',
103
+ 'TATACONSUM', 'TCS', 'TATAMOTORS', 'TATASTEEL', 'TECHM',
104
+ 'TITAN', 'TRENT', 'ULTRACEMCO', 'WIPRO', 'INDIGO','ETERNAL',
105
+ 'HINDPETRO', 'TATAPOWER', 'BAJAJHLDNG', 'HEROMOTOCO', 'INDUSINDBK'
106
+ ]
107
+
108
+ return {"stocks": popular_stocks}
app/core/__init__.py ADDED
File without changes
app/core/config.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from dotenv import load_dotenv
3
+
4
+ load_dotenv()
5
+
6
+ class Settings:
7
+ API_KEY = os.getenv("SWARMS_API_KEY")
8
+ BASE_URL = "https://api.swarms.world"
9
+
10
+ # Headers for all requests
11
+ HEADERS = {
12
+ "x-api-key": API_KEY,
13
+ "Content-Type": "application/json"
14
+ }
15
+
16
+ settings = Settings()
app/core/data_provider.py ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import yfinance as yf
2
+ from typing import Dict, Any
3
+ from datetime import datetime
4
+
5
+ class IndianDataProvider:
6
+ """Handles integration with Indian financial data APIs"""
7
+
8
+ def __init__(self):
9
+ pass
10
+
11
+ def get_nse_stock_data(self, symbol: str) -> Dict[str, Any]:
12
+ """Get NSE stock data using Yahoo Finance with direct metric extraction"""
13
+ try:
14
+ # Create ticker with NSE suffix
15
+ ticker = yf.Ticker(f"{symbol}.NS")
16
+ info = ticker.info
17
+ financials = ticker.financials
18
+ balance_sheet = ticker.balance_sheet
19
+ cash_flow = ticker.cashflow
20
+
21
+ # Extract key metrics directly from info
22
+ current_price = info.get("currentPrice")
23
+ total_revenue = info.get("totalRevenue")
24
+ net_income = info.get("netIncomeToCommon")
25
+ total_debt = info.get("totalDebt")
26
+
27
+ # Convert to dict and extract only the first timestamp entry
28
+ def extract_first_entry(df):
29
+ df_dict = df.to_dict()
30
+ if df_dict:
31
+ first_key = sorted(df_dict.keys())[len(df_dict)-1]
32
+ return {first_key: df_dict[first_key]}
33
+ return {}
34
+
35
+ return {
36
+ 'success': True,
37
+ 'info': info,
38
+ 'financials': extract_first_entry(financials) if not financials.empty else {},
39
+ 'balance_sheet': extract_first_entry(balance_sheet) if not balance_sheet.empty else {},
40
+ 'cash_flow': extract_first_entry(cash_flow) if not cash_flow.empty else {},
41
+ 'current_price': current_price,
42
+ 'total_revenue': total_revenue,
43
+ 'net_income': net_income,
44
+ 'total_debt': total_debt,
45
+ 'price_source': 'Yahoo Finance'
46
+ }
47
+ except Exception as e:
48
+ return {"success": False, "error": str(e)}
49
+
50
+ def format_stock_data_for_analysis(self, stock_data: Dict[str, Any]) -> str:
51
+ """Format NSE stock data for compliance analysis"""
52
+ if not stock_data.get('success'):
53
+ return f"Error fetching stock data: {stock_data.get('error', 'Unknown error')}"
54
+
55
+ try:
56
+ info = stock_data['info']
57
+ financials = stock_data['financials']
58
+ balance_sheet = stock_data['balance_sheet']
59
+
60
+ # Use directly extracted metrics
61
+ current_price = stock_data.get('current_price')
62
+ total_revenue = stock_data.get('total_revenue')
63
+ net_income = stock_data.get('net_income')
64
+ total_debt = stock_data.get('total_debt')
65
+
66
+ # Format currency values
67
+ def format_currency(value):
68
+ if value is None:
69
+ return "N/A"
70
+ return f"₹{value:,.2f}"
71
+
72
+ def get_total_liabilities(balance_sheet: dict) -> float:
73
+ for timestamp, financials in balance_sheet.items():
74
+ if 'Total Liabilities Net Minority Interest' in financials:
75
+ return financials['Total Liabilities Net Minority Interest']
76
+ return None
77
+
78
+ def get_total_assets(balance_sheet: dict) -> float:
79
+ for timestamp, financials in balance_sheet.items():
80
+ if 'Total Assets' in financials:
81
+ return financials['Total Assets']
82
+ return None
83
+
84
+ total_assets = get_total_assets(balance_sheet)
85
+ total_liabilities = get_total_liabilities(balance_sheet)
86
+ shareholders_equity = total_assets - total_liabilities if total_assets and total_liabilities else None
87
+
88
+ def get_ebitda(financials: dict) -> float:
89
+ for timestamp, data in financials.items():
90
+ if 'EBITDA' in data:
91
+ return data['EBITDA']
92
+ return None
93
+
94
+ symbol_ebitda = get_ebitda(financials)
95
+
96
+ def get_gross_profit(financials: dict) -> float:
97
+ for timestamp, data in financials.items():
98
+ if 'Gross Profit' in data:
99
+ return data['Gross Profit']
100
+ return None
101
+
102
+ gross_profit = get_gross_profit(financials)
103
+
104
+ def get_operating_income(financials: dict) -> float:
105
+ for timestamp, data in financials.items():
106
+ if 'Operating Income' in data:
107
+ return data['Operating Income']
108
+ return None
109
+
110
+ operating_income = get_operating_income(financials)
111
+
112
+ def get_operating_revenue(financials: dict) -> float:
113
+ for timestamp, data in financials.items():
114
+ if 'Operating Revenue' in data:
115
+ return data['Operating Revenue']
116
+ return None
117
+
118
+ operating_revenue = get_operating_revenue(financials)
119
+
120
+ def get_total_equity(balance_sheet: dict) -> float:
121
+ for timestamp, data in balance_sheet.items():
122
+ if 'Total Equity Gross Minority Interest' in data:
123
+ return data['Total Equity Gross Minority Interest']
124
+ return None
125
+
126
+ total_equity = get_total_equity(balance_sheet)
127
+ debt_to_equity = (total_debt / total_equity) if total_debt and total_equity else None
128
+
129
+ formatted_data = f"""
130
+ COMPANY INFORMATION:
131
+ Company Name: {info.get('longName', 'N/A')}
132
+ Symbol: {info.get('symbol', 'N/A')}
133
+ Sector: {info.get('sector', 'N/A')}
134
+ Industry: {info.get('industry', 'N/A')}
135
+ Market Cap: {format_currency(info.get('marketCap'))}
136
+ Employees: {info.get('fullTimeEmployees', 'N/A')}
137
+
138
+ CURRENT PRICE: {format_currency(current_price)} (Source: Yahoo Finance)
139
+
140
+ FINANCIAL HIGHLIGHTS:
141
+ 52 Week High: {format_currency(info.get('fiftyTwoWeekHigh'))}
142
+ 52 Week Low: {format_currency(info.get('fiftyTwoWeekLow'))}
143
+ P/E Ratio: {info.get('trailingPE', 'N/A')}
144
+ Book Value: {format_currency(info.get('bookValue'))}
145
+ Dividend Yield: {info.get('dividendYield', 'N/A')}%
146
+
147
+ FINANCIAL STATEMENTS:
148
+ Revenue (Latest): {format_currency(total_revenue)}
149
+ Net Income (Latest): {format_currency(net_income)}
150
+ Total Assets (Latest): {format_currency(total_assets)}
151
+ Total Debt (Latest): {format_currency(total_debt)}
152
+ Total Equity (Latest): {format_currency(total_equity)}
153
+ Debt to Equity Ratio: {(f"{debt_to_equity:.2f}" if debt_to_equity else "N/A")}
154
+ Total Liabilities: {format_currency(total_liabilities)}
155
+ Shareholders Equity: {format_currency(shareholders_equity)}
156
+ EBITDA: {(format_currency(symbol_ebitda) if symbol_ebitda else "N/A")}
157
+ Gross Profit: {format_currency(gross_profit)}
158
+ Operating Income: {format_currency(operating_income)}
159
+ Operating Revenue: {format_currency(operating_revenue)}
160
+
161
+ BUSINESS SUMMARY:
162
+ {info.get('longBusinessSummary', 'N/A')}
163
+
164
+ GOVERNANCE:
165
+ Board Members: {len(info.get('companyOfficers', []))} officers listed
166
+ Audit Risk: {info.get('auditRisk', 'N/A')}
167
+ Board Risk: {info.get('boardRisk', 'N/A')}
168
+ Compensation Risk: {info.get('compensationRisk', 'N/A')}
169
+ Shareholder Rights Risk: {info.get('shareHolderRightsRisk', 'N/A')}
170
+ Overall Risk: {info.get('overallRisk', 'N/A')}
171
+ """
172
+
173
+ return formatted_data.strip()
174
+
175
+ except Exception as e:
176
+ return f"Error formatting stock data: {str(e)}"
app/core/swarms_client.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ from typing import Dict, Any
3
+ from app.core.config import settings
4
+
5
+ def run_swarm(swarm_config: Dict[str, Any]) -> Dict[str, Any]:
6
+ """Execute a swarm with the provided configuration."""
7
+ try:
8
+ response = requests.post(
9
+ f"{settings.BASE_URL}/v1/swarm/completions",
10
+ headers=settings.HEADERS,
11
+ json=swarm_config
12
+ )
13
+ return response.json()
14
+ except Exception as e:
15
+ return {"error": str(e)}
16
+
17
+ def create_indian_compliance_swarm(financial_data: str, company_info: str) -> Dict[str, Any]:
18
+ """Create a swarm for Indian financial compliance assistance."""
19
+
20
+ DOCUMENTATION_ANALYZER_PROMPT = """
21
+ You are a financial documentation specialist with expertise in Indian financial reporting standards and regulations.
22
+ Your role is to analyze financial statements and disclosures for compliance with Indian requirements.
23
+ Your tasks include:
24
+ 1. Reviewing financial statements for completeness under Indian Accounting Standards (Ind AS) or AS
25
+ 2. Analyzing annual reports and board reports for mandatory disclosures
26
+ 3. Checking compliance with Companies Act 2013 disclosure requirements
27
+ 4. Verifying CSR reporting and ESG disclosures as per Indian regulations
28
+ 5. Ensuring proper disclosure of related party transactions under Indian law
29
+ 6. Reviewing audit reports and internal financial control assessments
30
+ 7. Checking compliance with SEBI disclosure norms (for listed companies)
31
+ 8. Analyzing tax provisions and deferred tax disclosures under Indian tax laws
32
+
33
+ Focus on Indian regulatory framework and provide findings specific to Indian compliance requirements.
34
+ """
35
+
36
+ ACCOUNTING_STANDARDS_PROMPT = """
37
+ You are an expert in Indian Accounting Standards (Ind AS) and legacy Accounting Standards (AS) with deep knowledge of Indian GAAP requirements.
38
+ Your responsibility is to ensure financial statements comply with applicable Indian accounting frameworks.
39
+ Your tasks include:
40
+ 1. Analyzing compliance with applicable Ind AS or AS standards
41
+ 2. Reviewing revenue recognition under Ind AS 115 or AS 9
42
+ 3. Checking financial instrument accounting under Ind AS 109 or AS 30/31/32
43
+ 4. Evaluating lease accounting under Ind AS 116 or AS 19
44
+ 5. Reviewing impairment assessments under Ind AS 36 or AS 28
45
+ 6. Analyzing consolidation requirements under Ind AS 110/111 or AS 21/23/27
46
+ 7. Checking fair value measurements and disclosures under Ind AS 113
47
+ 8. Ensuring proper segment reporting under Ind AS 108 or AS 17
48
+ 9. Reviewing first-time adoption issues for Ind AS transition
49
+
50
+ Reference specific Indian accounting standards and consider MCA notifications and clarifications.
51
+ """
52
+
53
+ REGULATORY_COMPLIANCE_PROMPT = """
54
+ You are a senior regulatory compliance expert specializing in Indian financial regulations and corporate law.
55
+ Your expertise covers Companies Act 2013, SEBI regulations, RBI guidelines, and other Indian regulatory frameworks.
56
+ Your responsibilities include:
57
+ 1. Ensuring compliance with Companies Act 2013 provisions and rules
58
+ 2. Verifying SEBI LODR (Listing Obligations and Disclosure Requirements) compliance
59
+ 3. Checking RBI guidelines compliance (for applicable sectors)
60
+ 4. Reviewing corporate governance disclosures as per Indian regulations
61
+ 5. Analyzing CSR compliance and reporting under Section 135 of Companies Act
62
+ 6. Verifying board composition and audit committee requirements
63
+ 7. Checking compliance with insider trading regulations (SEBI PIT)
64
+ 8. Reviewing related party transaction approvals and disclosures
65
+ 9. Ensuring proper filing requirements with MCA and SEBI
66
+ 10. Analyzing compliance with sectoral regulations (banking, insurance, etc.)
67
+
68
+ Focus on Indian regulatory environment and recent updates to regulations and compliance requirements.
69
+ """
70
+
71
+ swarm_config = {
72
+ "name": "Indian Financial Compliance Assistant",
73
+ "description": "A specialized swarm for Indian financial regulatory compliance",
74
+ "agents": [
75
+ {
76
+ "agent_name": "Indian Documentation Analyzer",
77
+ "description": "Reviews financial statements for Indian compliance requirements",
78
+ "system_prompt": DOCUMENTATION_ANALYZER_PROMPT,
79
+ "model_name": "gpt-4o",
80
+ "role": "worker",
81
+ "max_loops": 1,
82
+ "max_tokens": 4096,
83
+ "temperature": 0.5,
84
+ "auto_generate_prompt": False,
85
+ },
86
+ {
87
+ "agent_name": "Indian Accounting Standards Expert",
88
+ "description": "Evaluates compliance with Ind AS/AS requirements",
89
+ "system_prompt": ACCOUNTING_STANDARDS_PROMPT,
90
+ "model_name": "gpt-4o",
91
+ "role": "worker",
92
+ "max_loops": 1,
93
+ "max_tokens": 4096,
94
+ "temperature": 0.5,
95
+ "auto_generate_prompt": False,
96
+ },
97
+ {
98
+ "agent_name": "Indian Regulatory Compliance Specialist",
99
+ "description": "Assesses adherence to Indian regulatory frameworks",
100
+ "system_prompt": REGULATORY_COMPLIANCE_PROMPT,
101
+ "model_name": "gpt-4o",
102
+ "role": "worker",
103
+ "max_loops": 1,
104
+ "max_tokens": 4096,
105
+ "temperature": 0.5,
106
+ "auto_generate_prompt": False,
107
+ }
108
+ ],
109
+ "max_loops": 1,
110
+ "swarm_type": "SequentialWorkflow",
111
+ "task": f"""
112
+ Analyze the following financial information for an Indian company ({company_info}) and provide a comprehensive compliance assessment according to Indian regulations:
113
+
114
+ {financial_data}
115
+
116
+ For your compliance evaluation, provide:
117
+ 1. Assessment of compliance with Indian Accounting Standards (Ind AS/AS)
118
+ 2. Analysis of Companies Act 2013 compliance requirements
119
+ 3. Review of SEBI regulations compliance (if applicable)
120
+ 4. Evaluation of corporate governance and disclosure requirements
121
+ 5. Assessment of CSR and ESG reporting compliance
122
+ 6. Identification of potential compliance risks specific to Indian regulations
123
+ 7. Recommendations for improving compliance with Indian standards
124
+
125
+ Focus specifically on Indian regulatory framework and recent regulatory updates.
126
+ """
127
+ }
128
+
129
+ return run_swarm(swarm_config)
app/models/__init__.py ADDED
File without changes
app/models/schemas.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pydantic import BaseModel
2
+ from typing import Optional, List, Dict, Any
3
+ from datetime import datetime
4
+
5
+ class StockDataRequest(BaseModel):
6
+ symbol: str
7
+
8
+ class ComplianceAnalysisRequest(BaseModel):
9
+ financial_data: str
10
+ company_info: str
11
+ data_source: str
12
+ accounting_standards: str
13
+ regulatory_frameworks: List[str]
14
+
15
+ class StockDataResponse(BaseModel):
16
+ success: bool
17
+ data: Optional[Dict[str, Any]] = None
18
+ formatted_data: Optional[str] = None
19
+ error: Optional[str] = None
20
+
21
+ class ComplianceAnalysisResponse(BaseModel):
22
+ success: bool
23
+ result: Optional[Dict[str, Any]] = None
24
+ error: Optional[str] = None
25
+
26
+ class AnalysisHistoryItem(BaseModel):
27
+ timestamp: datetime
28
+ data_source: str
29
+ company_info: str
30
+ status: str
31
+
32
+ class RiskAssessment(BaseModel):
33
+ risk_area: str
34
+ risk_level: str
35
+ impact_score: int
36
+ likelihood_score: int
37
+
38
+ # Add this new schema for CSV generation
39
+ class GenerateCSVRequest(BaseModel):
40
+ data_source: str
41
+ company_info: str
42
+ accounting_standards: str
43
+ regulatory_frameworks: List[str]
44
+ result: Dict[str, Any]
app/utils/__init__.py ADDED
File without changes
app/utils/helpers.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ from datetime import datetime
3
+ from typing import Dict, Any, List
4
+
5
+ def create_comprehensive_csv_data(data_source: str, company_info: str, accounting_standards: str,
6
+ regulatory_frameworks: List[str], result: Dict[str, Any]) -> pd.DataFrame:
7
+ """Create comprehensive CSV data with all analysis information"""
8
+
9
+ # Extract company information
10
+ company_parts = company_info.split(" in the ")
11
+ company_type = company_parts[0] if len(company_parts) > 0 else "N/A"
12
+ industry_sector = company_parts[1].split(", classified as")[0] if len(company_parts) > 1 else "N/A"
13
+ company_size = company_parts[1].split("classified as ")[1].split(", for")[0] if len(company_parts) > 1 else "N/A"
14
+ financial_year = company_parts[1].split("for ")[-1] if len(company_parts) > 1 else "N/A"
15
+
16
+ # Create comprehensive data structure
17
+ comprehensive_data = []
18
+
19
+ # 1. Basic Information
20
+ comprehensive_data.append({
21
+ 'Category': 'Basic Information',
22
+ 'Field': 'Analysis Timestamp',
23
+ 'Value': datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
24
+ 'Details': 'Time when analysis was performed',
25
+ 'Priority': '',
26
+ 'Timeline': '',
27
+ 'Regulation': ''
28
+ })
29
+
30
+ comprehensive_data.append({
31
+ 'Category': 'Basic Information',
32
+ 'Field': 'Data Source',
33
+ 'Value': data_source,
34
+ 'Details': 'Source of financial data used for analysis',
35
+ 'Priority': '',
36
+ 'Timeline': '',
37
+ 'Regulation': ''
38
+ })
39
+
40
+ comprehensive_data.append({
41
+ 'Category': 'Basic Information',
42
+ 'Field': 'Company Type',
43
+ 'Value': company_type,
44
+ 'Details': 'Legal structure of the company',
45
+ 'Priority': '',
46
+ 'Timeline': '',
47
+ 'Regulation': ''
48
+ })
49
+
50
+ comprehensive_data.append({
51
+ 'Category': 'Basic Information',
52
+ 'Field': 'Industry Sector',
53
+ 'Value': industry_sector,
54
+ 'Details': 'Primary business sector',
55
+ 'Priority': '',
56
+ 'Timeline': '',
57
+ 'Regulation': ''
58
+ })
59
+
60
+ comprehensive_data.append({
61
+ 'Category': 'Basic Information',
62
+ 'Field': 'Company Size',
63
+ 'Value': company_size,
64
+ 'Details': 'Classification based on turnover and capital',
65
+ 'Priority': '',
66
+ 'Timeline': '',
67
+ 'Regulation': ''
68
+ })
69
+
70
+ comprehensive_data.append({
71
+ 'Category': 'Basic Information',
72
+ 'Field': 'Financial Year',
73
+ 'Value': financial_year,
74
+ 'Details': 'Reporting period under analysis',
75
+ 'Priority': '',
76
+ 'Timeline': '',
77
+ 'Regulation': ''
78
+ })
79
+
80
+ comprehensive_data.append({
81
+ 'Category': 'Basic Information',
82
+ 'Field': 'Accounting Standards',
83
+ 'Value': accounting_standards,
84
+ 'Details': 'Applicable accounting framework',
85
+ 'Priority': '',
86
+ 'Timeline': '',
87
+ 'Regulation': ''
88
+ })
89
+
90
+ comprehensive_data.append({
91
+ 'Category': 'Basic Information',
92
+ 'Field': 'Regulatory Frameworks',
93
+ 'Value': ', '.join(regulatory_frameworks),
94
+ 'Details': 'Applicable regulatory requirements',
95
+ 'Priority': '',
96
+ 'Timeline': '',
97
+ 'Regulation': ''
98
+ })
99
+
100
+ # 2. AI Analysis Results (if available)
101
+ if isinstance(result, dict) and 'response' in result:
102
+ comprehensive_data.append({
103
+ 'Category': 'AI Analysis Results',
104
+ 'Field': 'Full Analysis Response',
105
+ 'Value': 'AI Generated Compliance Analysis',
106
+ 'Details': result['response'][:1000] + '...' if len(result['response']) > 1000 else result['response'],
107
+ 'Priority': '',
108
+ 'Timeline': '',
109
+ 'Regulation': ''
110
+ })
111
+
112
+ return pd.DataFrame(comprehensive_data)