Prompting cho Financial Modeling & Scenario Analysis: Tạo Assumptions, Cashflow Projections, Sensitivity Analysis

Prompting for Financial Modeling & Scenario Analysis: Từ Lý Thuyết Đến Công Cụ Thực Chiến

Khi nói đến financial modeling, nhiều dev nghĩ ngay đến Excel với đống công thức lằng nhằng. Nhưng thực tế, trong môi trường doanh nghiệp hiện đại, financial modeling đã tiến hóa thành một hệ thống tích hợp dữ liệu thời gian thực, kịch bản tự động và phân tích nhạy cảm (sensitivity analysis) dựa trên AI.


1. Tại Sao Financial Modeling Cần Prompting?

Trước khi đi vào chi tiết, cần hiểu rõ mối liên hệ giữa prompting và financial modeling:

Prompting không chỉ là AI chat. Trong financial modeling, prompting là cách bạn thiết lập cấu trúc câu hỏi, tham số đầu vào và logic xử lý để hệ thống tự động tạo ra các kịch bản tài chính.

Ví dụ: Thay vì mở Excel và tự thay đổi từng cell, bạn có thể prompt: “Giả sử doanh thu giảm 15%, chi phí vận hành tăng 8%, tính toán dòng tiền 12 tháng tiếp theo.”


2. Các Thành Phần Cốt Lõi Của Financial Model

2.1 Assumptions (Giả Định)

Assumptions là nền tảng của mọi financial model. Đây là nơi bạn định nghĩa các tham số đầu vào:

# Python code for assumptions
class FinancialAssumptions:
    def __init__(self):
        self.revenue_growth = 0.15  # 15% annual growth
        self.gross_margin = 0.35    # 35% gross margin
        self.operating_expense_growth = 0.08  # 8% annual increase
        self.tax_rate = 0.2         # 20% corporate tax
        self.working_capital_days = 45  # Days of working capital

Lưu ý quan trọng: Assumptions phải được tách biệt hoàn toàn với calculations. Điều này giúp bạn dễ dàng thay đổi kịch bản mà không làm hỏng toàn bộ model.

2.2 Cash Flow Projections (Dự Báo Dòng Tiền)

Dòng tiền là “mạch máu” của doanh nghiệp. Công thức tính toán dòng tiền cơ bản:

\huge \text{Operating Cash Flow} = \text{Net Income} + \text{Non-Cash Expenses} - \Delta \text{Working Capital}

Giải thích tiếng Việt:
– Operating Cash Flow = Lợi nhuận ròng + Các khoản chi phí không dùng tiền mặt – Thay đổi vốn lưu động
– Non-Cash Expenses thường là khấu hao (depreciation)
– Δ Working Capital là thay đổi của tài sản và nợ ngắn hạn

2.3 Sensitivity Analysis (Phân Tích Nhạy Cảm)

Đây là phần quan trọng nhất của prompting. Sensitivity analysis giúp bạn hiểu rõ:
– Yếu tố nào ảnh hưởng lớn nhất đến kết quả
– Kịch bản tồi tệ nhất có thể xảy ra
– Điểm break-even (hòa vốn)


3. Build Financial Model: Step-by-Step

Bước 1: Xác Định Input Parameters

# Define input parameters
input_params = {
    'base_revenue': 1000000,  # $1M annual revenue
    'growth_scenarios': [0.1, 0.15, 0.2],  # 10%, 15%, 20% growth
    'cost_scenarios': [0.3, 0.35, 0.4],  # 30%, 35%, 40% COGS
    'periods': 5  # 5-year projection
}

Bước 2: Tạo Model Structure

import pandas as pd
import numpy as np

class FinancialModel:
    def __init__(self, params):
        self.params = params
        self.results = pd.DataFrame()

    def calculate_revenue(self, base, growth_rate, periods):
        """Calculate revenue for each period"""
        return base * (1 + growth_rate) ** np.arange(periods)

    def calculate_cogs(self, revenue, cogs_rate):
        """Calculate Cost of Goods Sold"""
        return revenue * cogs_rate

    def calculate_gross_profit(self, revenue, cogs):
        """Calculate Gross Profit"""
        return revenue - cogs

    def run_scenarios(self):
        """Run all scenarios and store results"""
        for growth in self.params['growth_scenarios']:
            for cogs_rate in self.params['cost_scenarios']:
                revenue = self.calculate_revenue(
                    self.params['base_revenue'], 
                    growth, 
                    self.params['periods']
                )
                cogs = self.calculate_cogs(revenue, cogs_rate)
                gross_profit = self.calculate_gross_profit(revenue, cogs)

                # Store results
                scenario_name = f"Growth_{growth}_COGS_{cogs_rate}"
                self.results[scenario_name] = gross_profit

    def sensitivity_analysis(self):
        """Perform sensitivity analysis"""
        # Calculate variance across scenarios
        variance = self.results.var(axis=1)
        return variance

# Usage
model = FinancialModel(input_params)
model.run_scenarios()
sensitivity = model.sensitivity_analysis()

Bước 3: Visualize Kết Quả

import matplotlib.pyplot as plt

def plot_scenarios(model_results):
    """Plot all scenarios for comparison"""
    plt.figure(figsize=(12, 8))

    for column in model_results.columns:
        plt.plot(model_results[column], label=column)

    plt.title('Revenue Scenarios Comparison')
    plt.xlabel('Period')
    plt.ylabel('Revenue ($)')
    plt.legend()
    plt.grid(True)
    plt.show()

plot_scenarios(model.results)

4. Advanced Techniques: Monte Carlo Simulation

Monte Carlo simulation là phương pháp thống kê giúp bạn mô phỏng hàng ngàn kịch bản khác nhau dựa trên phân phối xác suất.

import numpy as np
from scipy import stats

class MonteCarloModel:
    def __init__(self, base_params, iterations=10000):
        self.base_params = base_params
        self.iterations = iterations

    def run_simulation(self):
        """Run Monte Carlo simulation"""
        results = []

        for _ in range(self.iterations):
            # Sample random values based on distributions
            revenue = np.random.normal(
                self.base_params['base_revenue'],
                self.base_params['revenue_stddev']
            )
            growth = np.random.normal(
                self.base_params['growth_mean'],
                self.base_params['growth_stddev']
            )
            cogs_rate = np.random.normal(
                self.base_params['cogs_mean'],
                self.base_params['cogs_stddev']
            )

            # Calculate outcomes
            outcome = revenue * (1 + growth) * (1 - cogs_rate)
            results.append(outcome)

        return np.array(results)

    def analyze_results(self, simulation_results):
        """Analyze simulation results"""
        mean = np.mean(simulation_results)
        std_dev = np.std(simulation_results)
        percentile_5 = np.percentile(simulation_results, 5)
        percentile_95 = np.percentile(simulation_results, 95)

        return {
            'mean': mean,
            'std_dev': std_dev,
            '5th_percentile': percentile_5,
            '95th_percentile': percentile_95
        }

# Usage
mc_model = MonteCarloModel({
    'base_revenue': 1000000,
    'revenue_stddev': 100000,
    'growth_mean': 0.15,
    'growth_stddev': 0.05,
    'cogs_mean': 0.35,
    'cogs_stddev': 0.05
})

simulation_results = mc_model.run_simulation()
analysis = mc_model.analyze_results(simulation_results)

5. Tools & Technologies Comparison

Tool Độ Khó Performance Cộng Đồng Learning Curve
Excel Thấp Trung bình Cao Thấp
Python (Pandas) Trung bình Cao Cao Trung bình
R Cao Rất cao Trung bình Cao
Power BI Thấp Trung bình Cao Thấp
Tableau Thấp Cao Cao Trung bình

6. Best Practices & Common Pitfalls

Best Practices

  1. Modular Design: Tách biệt assumptions, calculations, và outputs
  2. Version Control: Dùng Git cho financial models
  3. Documentation: Comment mọi assumptions và formulas
  4. Testing: Viết unit tests cho critical calculations
  5. Audit Trail: Lưu lại mọi thay đổi và lý do

Common Pitfalls

  1. Hardcoding Values: Tránh nhúng số trực tiếp vào formulas
  2. Circular References: Cẩn thận với các phụ thuộc vòng
  3. Floating Point Errors: Dùng decimal module cho financial calculations
  4. Missing Edge Cases: Test với negative values và zero
  5. Overcomplication: Giữ model đơn giản nhất có thể

7. Real-World Use Case: Startup Financial Planning

Giả sử bạn đang tư vấn cho một startup SaaS với các thông số sau:

  • Monthly Recurring Revenue (MRR): $50,000
  • Customer Acquisition Cost (CAC): $500
  • Lifetime Value (LTV): $2,500
  • Monthly churn rate: 3%
class SaaSFinancialModel:
    def __init__(self, mrr, cac, ltv, churn_rate):
        self.mrr = mrr
        self.cac = cac
        self.ltv = ltv
        self.churn_rate = churn_rate
        self.months = 24  # 2-year projection

    def calculate_ltv_cac_ratio(self):
        """Calculate LTV/CAC ratio"""
        return self.ltv / self.cac

    def project_revenue(self):
        """Project revenue with churn"""
        revenue = [self.mrr * 12]  # Start with annual revenue
        for month in range(1, self.months):
            monthly_revenue = revenue[-1] / 12
            monthly_revenue = monthly_revenue * (1 - self.churn_rate)
            revenue.append(monthly_revenue * 12)
        return revenue

    def calculate_burn_rate(self, monthly_expenses):
        """Calculate burn rate"""
        return sum(monthly_expenses) - sum(self.project_revenue())

    def run_scenarios(self, expense_scenarios):
        """Run multiple expense scenarios"""
        results = {}
        for scenario, expenses in expense_scenarios.items():
            burn_rate = self.calculate_burn_rate(expenses)
            results[scenario] = burn_rate
        return results

# Usage
saas_model = SaaSFinancialModel(
    mrr=50000,
    cac=500,
    ltv=2500,
    churn_rate=0.03
)

ltv_cac = saas_model.calculate_ltv_cac_ratio()
print(f"LTV/CAC Ratio: {ltv_cac:.2f}")

revenue_projection = saas_model.project_revenue()
print(f"2-year Revenue Projection: ${sum(revenue_projection):,.2f}")

expense_scenarios = {
    'conservative': [40000] * 24,
    'moderate': [50000] * 24,
    'aggressive': [60000] * 24
}

scenario_results = saas_model.run_scenarios(expense_scenarios)
print("Scenario Results:", scenario_results)

8. Tích Hợp AI vào Financial Modeling

AI có thể tự động hóa nhiều phần của financial modeling:

from openai import OpenAI
import json

class AIPromptingModel:
    def __init__(self, api_key):
        self.client = OpenAI(api_key=api_key)

    def generate_assumptions(self, company_data):
        """Generate assumptions using AI"""
        prompt = f"""
        Generate financial assumptions for a {company_data['industry']} company with:
        - Revenue: ${company_data['revenue']:,}
        - Growth stage: {company_data['growth_stage']}
        - Market conditions: {company_data['market_conditions']}

        Provide assumptions for:
        1. Revenue growth rate
        2. Gross margin
        3. Operating expense growth
        4. Working capital requirements
        5. Tax rate
        """

        response = self.client.chat.completions.create(
            model="gpt-4",
            messages=[{"role": "user", "content": prompt}],
            temperature=0.3
        )

        return json.loads(response.choices[0].message.content)

    def scenario_analysis(self, base_model, scenarios):
        """Run AI-powered scenario analysis"""
        results = {}

        for scenario_name, scenario_params in scenarios.items():
            prompt = f"""
            Analyze financial scenario: {scenario_name}
            Base assumptions: {base_model}
            Scenario changes: {scenario_params}

            Calculate:
            1. Impact on cash flow
            2. Break-even point
            3. Sensitivity to key variables
            4. Risk assessment
            """

            response = self.client.chat.completions.create(
                model="gpt-4",
                messages=[{"role": "user", "content": prompt}],
                temperature=0.1
            )

            results[scenario_name] = json.loads(response.choices[0].message.content)

        return results

# Usage
ai_model = AIPromptingModel(api_key="your-api-key")
company_data = {
    'industry': 'SaaS',
    'revenue': 1000000,
    'growth_stage': 'early-stage',
    'market_conditions': 'growing'
}

assumptions = ai_model.generate_assumptions(company_data)
scenarios = {
    'pessimistic': {'revenue_growth': -0.1, 'costs': 1.2},
    'base_case': {'revenue_growth': 0.15, 'costs': 1.0},
    'optimistic': {'revenue_growth': 0.25, 'costs': 0.9}
}

analysis_results = ai_model.scenario_analysis(assumptions, scenarios)

Key Takeaways

  1. Prompting là chìa khóa: Cách bạn thiết lập prompts ảnh hưởng trực tiếp đến chất lượng financial model
  2. Automation là tương lai: AI và automation giúp financial modeling nhanh hơn, chính xác hơn
  3. Testing là bắt buộc: Luôn validate model với historical data và stress-test với extreme scenarios

Thảo Luận

Anh em đã từng build financial model cho dự án nào chưa? Gặp khó khăn gì trong việc thiết lập assumptions hay sensitivity analysis? Chia sẻ kinh nghiệm ở phần comment nhé!


Trợ lý AI của Hải
Nội dung được Hải định hướng, trợ lý AI giúp mình viết chi tiết.
Chia sẻ tới bạn bè và gia đình