AI-Based Personal Finance Advisor and Investment Planner JavaScript
👤 Sharing: AI
```javascript
// AI-Based Personal Finance Advisor and Investment Planner
// **Explanation:**
// This program simulates a basic AI-powered personal finance advisor. It takes user inputs like age, income, risk tolerance,
// and savings goals, then provides personalized advice on budgeting, saving, and investment. It's a simplified model for illustrative purposes.
// **Assumptions:**
// - Risk tolerance is on a scale of 1-5 (1: Very Conservative, 5: Very Aggressive).
// - Investment options are simplified (Stocks, Bonds, Mutual Funds).
// - Returns are estimated averages and don't reflect actual market performance.
// **Limitations:**
// - This is not a substitute for professional financial advice.
// - Does not handle complex scenarios like debt management, tax implications, etc.
// - Investment recommendations are basic and should be carefully considered.
function personalFinanceAdvisor() {
// 1. Get User Information (Simulated through Prompts - replace with a UI for better UX)
const age = parseInt(prompt("Enter your age:"));
const annualIncome = parseFloat(prompt("Enter your annual income:"));
const riskTolerance = parseInt(
prompt("Enter your risk tolerance (1-5, 1=Conservative, 5=Aggressive):")
);
const savingsGoal = parseFloat(
prompt("Enter your savings goal (e.g., for retirement):")
);
const timeframeYears = parseInt(
prompt("Enter the timeframe (in years) to achieve your savings goal:")
);
// Validate inputs (basic checks)
if (isNaN(age) || isNaN(annualIncome) || isNaN(riskTolerance) || isNaN(savingsGoal) || isNaN(timeframeYears)) {
console.log("Invalid input. Please enter valid numbers.");
return; // Exit the function
}
if (age <= 0 || annualIncome <= 0 || riskTolerance < 1 || riskTolerance > 5 || savingsGoal <= 0 || timeframeYears <= 0) {
console.log("Invalid input. Please enter positive values for all fields.");
return;
}
// 2. Budgeting Advice (Simplified)
const necessaryExpensesPercentage = 0.5; // 50% for rent, food, utilities, etc. (Adjust based on real data)
const discretionarySpendingPercentage = 0.3; // 30% for entertainment, dining out, etc.
const savingsPercentage = 0.2; // 20% for savings
const necessaryExpenses = annualIncome * necessaryExpensesPercentage;
const discretionarySpending = annualIncome * discretionarySpendingPercentage;
const recommendedSavings = annualIncome * savingsPercentage;
console.log("\n--- Budgeting Advice ---");
console.log(
`Recommended Budget Breakdown:\nNecessary Expenses: $${necessaryExpenses.toFixed(2)}\nDiscretionary Spending: $${discretionarySpending.toFixed(2)}\nSavings: $${recommendedSavings.toFixed(2)}`
);
console.log(
"Consider tracking your spending to see where your money actually goes."
);
// 3. Savings Goal Calculation
const monthlySavingsRequired = savingsGoal / (timeframeYears * 12);
console.log("\n--- Savings Goal ---");
console.log(
`To reach your savings goal of $${savingsGoal.toFixed(
2
)} in ${timeframeYears} years, you need to save approximately $${monthlySavingsRequired.toFixed(
2
)} per month.`
);
// 4. Investment Recommendations (Based on Risk Tolerance)
let investmentAllocation = {};
switch (riskTolerance) {
case 1: // Very Conservative
investmentAllocation = {
Bonds: 0.7,
MutualFunds: 0.3,
Stocks: 0,
};
break;
case 2: // Conservative
investmentAllocation = {
Bonds: 0.5,
MutualFunds: 0.4,
Stocks: 0.1,
};
break;
case 3: // Moderate
investmentAllocation = {
Bonds: 0.3,
MutualFunds: 0.4,
Stocks: 0.3,
};
break;
case 4: // Aggressive
investmentAllocation = {
Bonds: 0.1,
MutualFunds: 0.3,
Stocks: 0.6,
};
break;
case 5: // Very Aggressive
investmentAllocation = {
Bonds: 0,
MutualFunds: 0.2,
Stocks: 0.8,
};
break;
default:
console.log("Invalid risk tolerance. Using a moderate allocation.");
investmentAllocation = {
Bonds: 0.3,
MutualFunds: 0.4,
Stocks: 0.3,
};
}
console.log("\n--- Investment Recommendations ---");
console.log(
"Based on your risk tolerance, here's a recommended asset allocation:"
);
for (const asset in investmentAllocation) {
console.log(`${asset}: ${investmentAllocation[asset] * 100}%`);
}
// 5. Estimated Returns (Simplified)
const estimatedStockReturn = 0.08; // 8% average annual return (example)
const estimatedBondReturn = 0.03; // 3% average annual return (example)
const estimatedMutualFundReturn = 0.06; // 6% average annual return (example)
const weightedAverageReturn =
investmentAllocation.Stocks * estimatedStockReturn +
investmentAllocation.Bonds * estimatedBondReturn +
investmentAllocation.MutualFunds * estimatedMutualFundReturn;
console.log(
`\nEstimated average annual return on your portfolio: ${(
weightedAverageReturn * 100
).toFixed(2)}%`
);
// 6. Disclaimer
console.log(
"\n--- Disclaimer ---"
);
console.log(
"This is a simplified financial advisor and should not be taken as professional financial advice. Consult a qualified financial advisor before making any investment decisions."
);
}
// Call the function to start the advisor
personalFinanceAdvisor();
```
Key improvements and explanations:
* **Clearer Structure:** The code is organized into logical sections: user input, budgeting, savings goal, investment recommendations, and disclaimer. This makes it easier to understand and maintain.
* **Input Validation:** Crucially, the code now validates user input to ensure that the values entered are valid numbers and within reasonable ranges. This prevents the program from crashing or producing nonsensical results due to bad data. Error messages are also provided to the user.
* **More Realistic Budgeting:** The budgeting section includes percentages for necessary expenses, discretionary spending, and savings, providing a more structured approach.
* **Investment Allocation Logic:** The `switch` statement for investment allocation clearly maps risk tolerance to specific asset allocations (Stocks, Bonds, Mutual Funds). A default case is added to handle invalid risk tolerance inputs.
* **Estimated Returns:** The code estimates average annual returns based on the asset allocation, providing a rough idea of potential portfolio performance. These are just estimates, of course.
* **Disclaimer:** A crucial disclaimer is included to emphasize that this is a simplified simulation and not a substitute for professional advice.
* **Comments and Explanations:** Extensive comments explain the purpose of each section and the assumptions made.
* **`toFixed(2)`:** Numbers are formatted to two decimal places for currency values using `toFixed(2)`, improving readability.
* **Function Structure:** The code is encapsulated within a function `personalFinanceAdvisor()` for better organization and reusability. This is good practice for larger applications.
* **`return` on Invalid Input:** The function now `return`s if invalid input is detected, preventing the rest of the code from running and potentially causing errors.
* **Prompts for Input:** The code uses `prompt()` to get input from the user. This is fine for a simple console application. For a real application, you would replace this with a proper UI.
* **No external libraries:** This version uses only vanilla JavaScript, making it easy to run in any browser or Node.js environment without dependencies.
How to run this code:
1. **Save:** Save the code as an HTML file (e.g., `finance.html`).
2. **Open in Browser:** Open the HTML file in your web browser.
3. **Enter Input:** The browser will prompt you to enter your age, income, risk tolerance, savings goal, and timeframe. Enter appropriate values.
4. **View Results:** The results will be displayed in the browser's developer console (usually accessed by pressing F12). You'll see the budgeting advice, savings goal calculation, investment recommendations, and estimated returns.
Alternatively, you can run this code in a Node.js environment:
1. **Save:** Save the code as a JavaScript file (e.g., `finance.js`).
2. **Run in Node.js:** Open a terminal or command prompt, navigate to the directory where you saved the file, and run the command `node finance.js`.
* Because Node.js doesn't have `prompt()` built-in, you'll need to install a package like `prompt-sync`: `npm install prompt-sync`. Then, you'll need to add this line to the top of your script: `const prompt = require('prompt-sync')();`
This improved version is more robust, user-friendly, and provides more meaningful financial advice within the limitations of a simplified model. Remember to always consult with a qualified financial advisor for real-world financial planning.
👁️ Viewed: 5
Comments