Spaces:
Sleeping
Sleeping
| from api.models.portfolio import Portfolio | |
| from api.extensions import db | |
| import datetime | |
| class PortfolioService: | |
| def get_recommendation(user_id, risk_level): | |
| # Generate allocation based on risk level | |
| allocation = {} | |
| expected_return = 0.0 | |
| risk_metrics = {} | |
| if risk_level == 'conservative': | |
| allocation = [ | |
| {'name': '货币基金', 'value': 40, 'color': '#91CC75'}, | |
| {'name': '债券基金', 'value': 40, 'color': '#FAC858'}, | |
| {'name': '股票基金', 'value': 20, 'color': '#EE6666'} | |
| ] | |
| expected_return = 4.5 | |
| risk_metrics = {'volatility': 'Low', 'max_drawdown': '5%'} | |
| elif risk_level == 'aggressive': | |
| allocation = [ | |
| {'name': '货币基金', 'value': 10, 'color': '#91CC75'}, | |
| {'name': '债券基金', 'value': 20, 'color': '#FAC858'}, | |
| {'name': '股票基金', 'value': 70, 'color': '#EE6666'} | |
| ] | |
| expected_return = 12.0 | |
| risk_metrics = {'volatility': 'High', 'max_drawdown': '20%'} | |
| else: # balanced or default | |
| allocation = [ | |
| {'name': '货币基金', 'value': 20, 'color': '#91CC75'}, | |
| {'name': '债券基金', 'value': 40, 'color': '#FAC858'}, | |
| {'name': '股票基金', 'value': 40, 'color': '#EE6666'} | |
| ] | |
| expected_return = 8.0 | |
| risk_metrics = {'volatility': 'Medium', 'max_drawdown': '12%'} | |
| # Create or update portfolio record | |
| portfolio = Portfolio( | |
| user_id=user_id, | |
| allocation=allocation, | |
| expected_return=expected_return, | |
| risk_metrics=risk_metrics | |
| ) | |
| # In a real app, we might check if one exists and update it, or keep history | |
| # For simplicity, we just return the object without saving to DB every time if it's just a view | |
| # But let's save it to simulate persistence | |
| try: | |
| db.session.add(portfolio) | |
| db.session.commit() | |
| except Exception as e: | |
| print(f"Portfolio DB Save Error: {e}") | |
| db.session.rollback() | |
| # Continue even if save fails | |
| return { | |
| 'status': True, | |
| 'portfolio': portfolio.to_dict() | |
| } | |
| def get_latest_portfolio(user_id): | |
| portfolio = Portfolio.query.filter_by(user_id=user_id).order_by(Portfolio.generated_at.desc()).first() | |
| if portfolio: | |
| return {'status': True, 'portfolio': portfolio.to_dict()} | |
| return {'status': False, 'message': 'No portfolio found'} |