Spaces:
Sleeping
Sleeping
Delete financial-ai-analyzer.txt
Browse files- financial-ai-analyzer.txt +0 -126
financial-ai-analyzer.txt
DELETED
@@ -1,126 +0,0 @@
|
|
1 |
-
# Financial AI Analyzer.ipynb
|
2 |
-
|
3 |
-
import torch
|
4 |
-
from transformers import (
|
5 |
-
AutoTokenizer,
|
6 |
-
AutoModelForCausalLM,
|
7 |
-
AutoModelForSequenceClassification
|
8 |
-
)
|
9 |
-
import gradio as gr
|
10 |
-
from financial_metrics_calculator import FinancialMetricsCalculator # Import from first notebook
|
11 |
-
|
12 |
-
class FinancialAIAnalyzer:
|
13 |
-
def __init__(self):
|
14 |
-
print("Initializing AI Models...")
|
15 |
-
self.metrics_calculator = FinancialMetricsCalculator()
|
16 |
-
self.initialize_models()
|
17 |
-
self.last_metrics = {}
|
18 |
-
print("Initialization complete!")
|
19 |
-
|
20 |
-
def initialize_models(self):
|
21 |
-
"""Initialize both TinyLlama and FinBERT models"""
|
22 |
-
try:
|
23 |
-
# Initialize TinyLlama
|
24 |
-
self.llama_tokenizer = AutoTokenizer.from_pretrained("TinyLlama/TinyLlama-1.1B-Chat-v1.0")
|
25 |
-
self.llama_model = AutoModelForCausalLM.from_pretrained("TinyLlama/TinyLlama-1.1B-Chat-v1.0")
|
26 |
-
self.llama_model.eval()
|
27 |
-
|
28 |
-
# Initialize FinBERT
|
29 |
-
self.finbert_tokenizer = AutoTokenizer.from_pretrained("ProsusAI/finbert")
|
30 |
-
self.finbert_model = AutoModelForSequenceClassification.from_pretrained("ProsusAI/finbert")
|
31 |
-
self.finbert_model.eval()
|
32 |
-
|
33 |
-
print("Models loaded successfully!")
|
34 |
-
except Exception as e:
|
35 |
-
print(f"Error initializing models: {str(e)}")
|
36 |
-
raise
|
37 |
-
|
38 |
-
def get_sentiment_analysis(self, metrics):
|
39 |
-
"""Get financial sentiment analysis using FinBERT"""
|
40 |
-
try:
|
41 |
-
financial_text = f"""
|
42 |
-
Revenue growth: {metrics['Ratios'].get('Revenue_Growth', 0):.2f}%
|
43 |
-
Profit margin: {metrics['Ratios'].get('Net_Margin', 0):.2f}%
|
44 |
-
Debt to equity: {metrics['Ratios'].get('Debt_to_Equity', 0):.2f}
|
45 |
-
Interest coverage: {metrics['Ratios'].get('Interest_Coverage', 0):.2f}%
|
46 |
-
Current ratio: {metrics['Ratios'].get('Current_Ratio', 0):.2f}
|
47 |
-
"""
|
48 |
-
|
49 |
-
inputs = self.finbert_tokenizer(financial_text, return_tensors="pt", padding=True, truncation=True)
|
50 |
-
outputs = self.finbert_model(**inputs)
|
51 |
-
probabilities = torch.nn.functional.softmax(outputs.logits, dim=-1)
|
52 |
-
sentiment_scores = probabilities.detach().numpy()[0]
|
53 |
-
|
54 |
-
sentiments = ['negative', 'neutral', 'positive']
|
55 |
-
sentiment_dict = dict(zip(sentiments, [float(score) for score in sentiment_scores]))
|
56 |
-
|
57 |
-
return sentiment_dict
|
58 |
-
except Exception as e:
|
59 |
-
print(f"Error in sentiment analysis: {str(e)}")
|
60 |
-
return {}
|
61 |
-
|
62 |
-
def generate_prompt(self, metrics, sentiment_dict):
|
63 |
-
"""Create analysis prompt"""
|
64 |
-
try:
|
65 |
-
# [Previous generate_prompt code remains the same]
|
66 |
-
pass
|
67 |
-
except Exception as e:
|
68 |
-
print(f"Error generating prompt: {str(e)}")
|
69 |
-
return ""
|
70 |
-
|
71 |
-
def generate_analysis(self, prompt):
|
72 |
-
"""Generate analysis using TinyLlama"""
|
73 |
-
try:
|
74 |
-
# [Previous generate_analysis code remains the same]
|
75 |
-
pass
|
76 |
-
except Exception as e:
|
77 |
-
print(f"Error generating analysis: {str(e)}")
|
78 |
-
return self.generate_fallback_analysis(self.last_metrics)
|
79 |
-
|
80 |
-
def generate_fallback_analysis(self, metrics):
|
81 |
-
"""Generate fallback analysis"""
|
82 |
-
try:
|
83 |
-
# [Previous generate_fallback_analysis code remains the same]
|
84 |
-
pass
|
85 |
-
except Exception as e:
|
86 |
-
return f"Error generating fallback analysis: {str(e)}"
|
87 |
-
|
88 |
-
def analyze_financials(self, balance_sheet_file, income_stmt_file):
|
89 |
-
"""Main analysis function"""
|
90 |
-
try:
|
91 |
-
# Get metrics from calculator
|
92 |
-
metrics = self.metrics_calculator.process_financial_statements(balance_sheet_file, income_stmt_file)
|
93 |
-
if isinstance(metrics, str): # Error message
|
94 |
-
return metrics
|
95 |
-
|
96 |
-
self.last_metrics = metrics
|
97 |
-
sentiment_dict = self.get_sentiment_analysis(metrics)
|
98 |
-
prompt = self.generate_prompt(metrics, sentiment_dict)
|
99 |
-
analysis = self.generate_analysis(prompt)
|
100 |
-
|
101 |
-
results = {
|
102 |
-
"Financial Analysis": {
|
103 |
-
"Key Metrics": metrics,
|
104 |
-
"Market Sentiment": sentiment_dict,
|
105 |
-
"AI Insights": analysis,
|
106 |
-
"Analysis Period": "2021-2025",
|
107 |
-
"Note": "All monetary values in millions ($M)"
|
108 |
-
}
|
109 |
-
}
|
110 |
-
|
111 |
-
return json.dumps(results, indent=2)
|
112 |
-
except Exception as e:
|
113 |
-
return f"Error in analysis: {str(e)}"
|
114 |
-
|
115 |
-
def create_interface():
|
116 |
-
analyzer = FinancialAIAnalyzer()
|
117 |
-
|
118 |
-
iface = gr.Interface(
|
119 |
-
fn=analyzer.analyze_financials,
|
120 |
-
inputs=[
|
121 |
-
gr.File(label="Balance Sheet (Markdown)", type="filepath"),
|
122 |
-
gr.File(label="Income Statement (Markdown)", type="filepath")
|
123 |
-
],
|
124 |
-
outputs=gr.Textbox(label="Analysis Results", lines=25),
|
125 |
-
title="AI Financial Statement Analyzer",
|
126 |
-
description="Upload financial statements in Markdown format for AI-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|