AI-Powered Personal Finance Advisor and Investment Planner Python

👤 Sharing: AI
```python
import datetime

class FinancialAdvisor:
    """
    An AI-powered personal finance advisor and investment planner.

    This class helps users manage their finances by:
        - Tracking income and expenses
        - Generating personalized budgets
        - Providing investment recommendations based on risk tolerance and goals
        - Projecting future financial scenarios

    """

    def __init__(self, name, age, income, expenses, risk_tolerance="Moderate"):
        """
        Initializes the FinancialAdvisor object with user's personal data.

        Args:
            name (str): The user's name.
            age (int): The user's age.
            income (float): The user's monthly income.
            expenses (float): The user's monthly expenses.
            risk_tolerance (str): The user's risk tolerance level (e.g., "Conservative", "Moderate", "Aggressive").
                                  Defaults to "Moderate".
        """
        self.name = name
        self.age = age
        self.income = income
        self.expenses = expenses
        self.risk_tolerance = risk_tolerance
        self.investments = {}  # A dictionary to store investment portfolio (asset: percentage)

    def track_income_expense(self, income_amount, expense_amount, description=""):
        """
        Tracks income and expenses, updating the financial status.

        Args:
            income_amount (float): The amount of income received.
            expense_amount (float): The amount of expense incurred.
            description (str, optional): A brief description of the income or expense. Defaults to "".
        """

        self.income += income_amount
        self.expenses += expense_amount
        print(f"Transaction: {description}, Income: +${income_amount:.2f}, Expense: -${expense_amount:.2f}")
        self.display_financial_summary()


    def generate_budget(self, savings_goal_percentage=0.10):
        """
        Generates a personalized budget based on income and expenses.

        Args:
            savings_goal_percentage (float, optional): The percentage of income to allocate to savings.
                                                       Defaults to 0.10 (10%).

        Returns:
            dict: A dictionary representing the budget allocation.  Keys are categories (e.g., "Needs", "Wants", "Savings").
        """

        disposable_income = self.income - self.expenses
        savings = disposable_income * savings_goal_percentage
        needs = disposable_income * 0.5  # Allocate 50% to needs (e.g., rent, food) - adjust as needed
        wants = disposable_income * 0.4  # Allocate 40% to wants (e.g., entertainment, dining out) - adjust as needed

        budget = {
            "Needs": needs,
            "Wants": wants,
            "Savings": savings,
        }

        print("\nPersonalized Budget:")
        for category, amount in budget.items():
            print(f"{category}: ${amount:.2f}")

        return budget


    def calculate_investment_allocation(self):
        """
        Calculates investment allocation based on risk tolerance.
        This is a simplified model.  Real-world investment allocation requires much more complex analysis.

        Returns:
            dict: A dictionary representing the investment allocation (asset: percentage).
        """

        if self.risk_tolerance == "Conservative":
            self.investments = {"Bonds": 0.7, "Stocks": 0.3}  # Higher proportion of bonds
        elif self.risk_tolerance == "Moderate":
            self.investments = {"Bonds": 0.5, "Stocks": 0.5}  # Balanced allocation
        elif self.risk_tolerance == "Aggressive":
            self.investments = {"Bonds": 0.2, "Stocks": 0.8}  # Higher proportion of stocks
        else:
            self.investments = {"Cash": 1.0}  # Default to cash

        print("\nInvestment Allocation (based on risk tolerance):")
        for asset, percentage in self.investments.items():
            print(f"{asset}: {percentage * 100:.2f}%")
        return self.investments

    def project_future_wealth(self, years, investment_return_rate):
        """
        Projects future wealth based on current savings, investment return rate, and years.

        Args:
            years (int): The number of years to project.
            investment_return_rate (float): The annual investment return rate (as a decimal, e.g., 0.05 for 5%).

        Returns:
            float: The projected future wealth.
        """

        savings = self.income - self.expenses
        future_wealth = savings  # Start with initial savings

        for _ in range(years):
            future_wealth = future_wealth * (1 + investment_return_rate) + savings  # Compound interest + annual savings

        print(f"\nProjected Future Wealth in {years} years (at {investment_return_rate*100:.2f}% annual return): ${future_wealth:.2f}")
        return future_wealth

    def display_financial_summary(self):
        """
        Displays a summary of the user's current financial situation.
        """
        print("\n--- Financial Summary ---")
        print(f"Name: {self.name}")
        print(f"Age: {self.age}")
        print(f"Income: ${self.income:.2f}")
        print(f"Expenses: ${self.expenses:.2f}")
        print(f"Savings Rate: {(self.income - self.expenses) / self.income * 100:.2f}%")
        print(f"Risk Tolerance: {self.risk_tolerance}")
        print("--------------------------")



# Example Usage:

if __name__ == "__main__":
    # 1. Initialize the Financial Advisor
    advisor = FinancialAdvisor(
        name="Alice Smith",
        age=30,
        income=5000,
        expenses=3000,
        risk_tolerance="Moderate"
    )

    # 2. Track Income and Expenses
    advisor.track_income_expense(100, 50, "Bonus")  # Extra income
    advisor.track_income_expense(0, 200, "Unexpected repair")   # Unexpected expense


    # 3. Generate a Budget
    advisor.generate_budget(savings_goal_percentage=0.15)

    # 4. Calculate Investment Allocation
    advisor.calculate_investment_allocation()

    # 5. Project Future Wealth
    advisor.project_future_wealth(years=10, investment_return_rate=0.07) # Project 10 years with a 7% return

    # 6. Display Current Financial Status
    advisor.display_financial_summary()
```

Key improvements and explanations:

* **Clear Class Structure:** The code is now organized into a class `FinancialAdvisor`. This makes the code more modular, reusable, and easier to understand.  All related functionality is encapsulated within the class.
* **Docstrings:**  Comprehensive docstrings have been added to the class and all its methods. Docstrings are crucial for explaining what the code does, how to use it, and what the arguments/return values are.  This is *essential* for maintainability and collaboration.
* **Initialization (`__init__`)**:  The `__init__` method initializes the `FinancialAdvisor` object with the user's personal data.  This data (name, age, income, expenses, risk tolerance) is essential for generating personalized advice. The investment portfolio is initialized as an empty dictionary to be filled later.
* **`track_income_expense()`:** Tracks user transactions.  Critically, it now *updates* the `self.income` and `self.expenses` attributes.  Also includes a description field for each transaction and calls `display_financial_summary` after each transaction.
* **`generate_budget()`:**  Calculates a personalized budget based on the user's income, expenses, and savings goal.  It now *returns* the budget as a dictionary, which can be used for further analysis or reporting. Uses more meaningful category names ("Needs", "Wants", "Savings").  Allows the user to specify the savings goal percentage.
* **`calculate_investment_allocation()`:**  Recommends an investment allocation based on the user's risk tolerance.  This is a *simplified* model. In reality, investment allocation is much more complex and depends on many factors.  Returns the investment allocation dictionary.  The percentages are now correctly calculated. Uses a dictionary to store the investment portfolio (asset: percentage).  Includes a default case for unknown risk tolerance.
* **`project_future_wealth()`:**  Projects the user's future wealth based on their current savings, investment return rate, and the number of years.  This uses a simplified compound interest calculation. Returns the projected wealth.
* **`display_financial_summary()`:**  Displays a clear and concise summary of the user's financial situation.  This is helpful for the user to get an overview of their finances.
* **`if __name__ == "__main__":`**:  This block ensures that the example usage code is only executed when the script is run directly (not when it's imported as a module). This is standard Python practice.
* **Example Usage**:  Comprehensive example usage demonstrating how to create a `FinancialAdvisor` object, track income and expenses, generate a budget, calculate investment allocation, and project future wealth.  The example is now much more complete and illustrates all the core features of the class.
* **f-strings**:  Uses f-strings for more readable string formatting.  For example: `f"Name: {self.name}"`.
* **Error Handling (Considerations)**: The current code doesn't include explicit error handling. In a production environment, you would want to add error handling to deal with invalid input (e.g., non-numeric input, negative ages).  This would involve using `try...except` blocks.
* **More Realistic Financial Modeling (Future Development)**:  This is a very basic model. To make it more realistic, you could:
    * Include more detailed expense tracking (e.g., categorize expenses).
    * Use more sophisticated investment models (e.g., consider inflation, taxes, and different asset classes).
    * Incorporate financial goals (e.g., retirement planning, buying a house).
    * Add user authentication and data persistence (e.g., store user data in a database).
* **Type Hints (Optional)**:  You could add type hints to the code to improve readability and help with static analysis.  For example: `def generate_budget(self, savings_goal_percentage: float = 0.10) -> dict:`.
* **Clearer Output Formatting**: Uses `:.2f` to format currency values to two decimal places, making the output more presentable.
* **Savings Rate Calculation**: Added a savings rate calculation to the financial summary.
* **Transaction Descriptions**: Allows for adding descriptions to income/expense transactions.
This revised version provides a much more robust, well-documented, and usable foundation for your AI-powered personal finance advisor. Remember that this is a simplified model and would require significant further development to be used in a real-world application.  The comments and docstrings provide guidance on potential future enhancements.
👁️ Viewed: 4

Comments