File size: 22,075 Bytes
f8c6d80 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 |
import os
import sqlite3
import pandas as pd
import numpy as np
import gradio as gr
import yfinance as yf
import tensorflow as tf
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, MinMaxScaler
from sklearn.ensemble import RandomForestRegressor, RandomForestClassifier
from sklearn.metrics import mean_squared_error, accuracy_score
import joblib
from datetime import datetime, timedelta
class AdvancedHedgeFundManagementSystem:
def __init__(self, db_path='data/advanced_hedge_fund_database.sqlite'): # path to database corrected
"""
Initialize the Advanced Hedge Fund Management System
Args:
db_path (str): Path to the SQLite database
"""
self.db_path = db_path
self.conn = None
self.cursor = None
# Investment Types
self.investment_types = [
'Stocks', 'Bonds', 'ETFs', 'Mutual Funds',
'Real Estate', 'Cryptocurrencies', 'Commodities',
'Private Equity', 'Hedge Funds', 'Derivatives'
]
# Market Indices for Benchmarking
self.market_indices = [
'^GSPC', # S&P 500
'^DJI', # Dow Jones Industrial Average
'^IXIC', # NASDAQ Composite
'^RUT', # Russell 2000
]
# Initialize database and create tables
self.initialize_database()
# Load or train predictive models
self.load_or_train_models()
# Define some common Equity and Bond ETF
self.equity_etfs = ['SPY', 'QQQ', 'IWM', 'VOO', 'IVV'] # US equities
self.bond_etfs = ['BND', 'AGG', 'LQD', 'TLT', 'SHY'] # US bonds
def initialize_database(self):
"""
Create database connection and initialize tables
"""
try:
self.conn = sqlite3.connect(self.db_path)
self.cursor = self.conn.cursor()
# Enhanced clients table
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS clients (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
email TEXT UNIQUE,
age INTEGER,
income REAL,
risk_tolerance INTEGER,
total_investment REAL,
investment_goals TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
)
''')
# Enhanced portfolios table
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS portfolios (
id INTEGER PRIMARY KEY,
client_id INTEGER,
investment_type TEXT,
asset_symbol TEXT,
investment_amount REAL,
purchase_price REAL,
current_price REAL,
performance REAL,
risk_score REAL,
allocation_percentage REAL,
last_updated DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (client_id) REFERENCES clients (id)
)
''')
# Transactions table with more details
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS transactions (
id INTEGER PRIMARY KEY,
portfolio_id INTEGER,
transaction_type TEXT,
asset_symbol TEXT,
amount REAL,
quantity REAL,
price REAL,
date DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (portfolio_id) REFERENCES portfolios (id)
)
''')
# Performance tracking table
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS performance_tracking (
id INTEGER PRIMARY KEY,
client_id INTEGER,
total_investment REAL,
current_value REAL,
total_return REAL,
annual_return REAL,
last_updated DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (client_id) REFERENCES clients (id)
)
''')
self.conn.commit()
except sqlite3.Error as e:
print(f"Database initialization error: {e}")
def get_real_time_market_data(self, symbols):
"""
Fetch real-time market data using Yahoo Finance
Args:
symbols (list): List of stock/asset symbols
Returns:
dict: Real-time market data
"""
market_data = {}
for symbol in symbols:
try:
ticker = yf.Ticker(symbol)
# Fetch historical data and current info
hist = ticker.history(period="1mo")
market_data[symbol] = {
'current_price': ticker.info.get('regularMarketPrice', 0),
'previous_close': ticker.info.get('previousClose', 0),
'volume': ticker.info.get('volume', 0),
'market_cap': ticker.info.get('marketCap', 0),
'beta': ticker.info.get('beta', 1.0),
'volatility': hist['Close'].std() if not hist.empty else 0,
'returns_1m': (hist['Close'][-1] / hist['Close'][0] - 1) * 100 if len(hist) > 1 else 0
}
except Exception as e:
print(f"Error fetching data for {symbol}: {e}")
return market_data
def generate_advanced_training_data(self, n_samples=5000):
"""
Generate advanced synthetic training data with more features
Returns:
tuple: Features and target variables
"""
np.random.seed(42)
# More comprehensive feature generation
age = np.random.randint(25, 65, n_samples)
income = np.random.uniform(30000, 1000000, n_samples)
investment_experience = np.random.randint(0, 30, n_samples)
current_investments = np.random.uniform(0, 5000000, n_samples)
# Additional features
education_level = np.random.randint(1, 5, n_samples) # 1-4 education levels
family_size = np.random.randint(1, 6, n_samples)
debt_to_income = np.random.uniform(0, 0.5, n_samples)
# Combine features
X = np.column_stack([
age, income, investment_experience, current_investments,
education_level, family_size, debt_to_income
])
# Advanced risk scoring with more nuanced calculation
y_risk = (
(income / 50000) +
(investment_experience / 10) -
(debt_to_income * 10) +
(education_level * 0.5) -
(current_investments / 500000)
)
y_risk = np.clip(y_risk, 1, 10) # Risk score between 1-10
# Portfolio performance with more complex calculation
y_portfolio_performance = (
(income / 25000) +
(investment_experience / 5) +
(current_investments / 250000) -
(debt_to_income * 20)
)
y_portfolio_performance = np.clip(y_portfolio_performance, 0, 100)
return X, y_risk, y_portfolio_performance
def train_advanced_models(self):
"""
Train advanced machine learning models for risk and portfolio prediction
"""
# Generate training data
X, y_risk, y_portfolio_performance = self.generate_advanced_training_data()
# Split the data
X_train, X_test, y_risk_train, y_risk_test, y_perf_train, y_perf_test = train_test_split(
X, y_risk, y_portfolio_performance, test_size=0.2, random_state=42
)
# Scale features
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
# Risk Prediction Model (Regression)
risk_model = RandomForestRegressor(n_estimators=200, random_state=42)
risk_model.fit(X_train_scaled, y_risk_train)
y_risk_pred = risk_model.predict(X_test_scaled)
risk_mse = mean_squared_error(y_risk_test, y_risk_pred)
# Portfolio Performance Model (Regression)
portfolio_model = RandomForestRegressor(n_estimators=200, random_state=42)
portfolio_model.fit(X_train_scaled, y_perf_train)
y_perf_pred = portfolio_model.predict(X_test_scaled)
perf_mse = mean_squared_error(y_perf_test, y_perf_pred)
# Investment Type Recommendation Model (Classification)
# Create synthetic labels for investment type recommendation
y_investment_type = np.random.choice(len(self.investment_types), len(X))
X_type_train, X_type_test, y_type_train, y_type_test = train_test_split(
X, y_investment_type, test_size=0.2, random_state=42
)
X_type_train_scaled = scaler.transform(X_type_train)
X_type_test_scaled = scaler.transform(X_type_test)
investment_type_model = RandomForestClassifier(n_estimators=200, random_state=42)
investment_type_model.fit(X_type_train_scaled, y_type_train)
y_type_pred = investment_type_model.predict(X_type_test_scaled)
type_accuracy = accuracy_score(y_type_test, y_type_pred)
# Save models and scaler
joblib.dump({
'risk_model': risk_model,
'portfolio_model': portfolio_model,
'investment_type_model': investment_type_model,
'scaler': scaler
}, 'advanced_hedge_fund_models.joblib')
# Print model performance
print(f"Risk Prediction MSE: {risk_mse}")
print(f"Portfolio Performance MSE: {perf_mse}")
print(f"Investment Type Recommendation Accuracy: {type_accuracy}")
return risk_model, portfolio_model, investment_type_model, scaler
def load_or_train_models(self):
"""
Load existing models or train new predictive models
"""
try:
# Try to load pre-trained models
models = joblib.load('advanced_hedge_fund_models.joblib')
self.risk_model = models['risk_model']
self.portfolio_model = models['portfolio_model']
self.investment_type_model = models['investment_type_model']
self.scaler = models['scaler']
except (FileNotFoundError, KeyError):
# Train new models if not found
(self.risk_model,
self.portfolio_model,
self.investment_type_model,
self.scaler) = self.train_advanced_models()
def recommend_portfolio_allocation(self, client_features, target_return=0.15):
"""
Recommend portfolio allocation with 15% target return
Args:
client_features (numpy.ndarray): Client features
target_return (float): Target annual return percentage
Returns:
dict: Recommended portfolio allocation
"""
# Scale client features
scaled_features = self.scaler.transform(client_features.reshape(1, -1))
# Predict risk and investment type
risk_score = float(self.risk_model.predict(scaled_features)[0])
investment_type_index = int(self.investment_type_model.predict(scaled_features)[0])
recommended_investment_type = self.investment_types[investment_type_index]
# Fetch real-time market data for market indices
market_data = self.get_real_time_market_data(self.market_indices)
# Calculate portfolio allocation
base_allocation = {
'Stocks': 0.4,
'Bonds': 0.3,
'ETFs': 0.15,
'Real Estate': 0.1,
'Other Alternatives': 0.05
}
# Adjust allocation based on risk tolerance
if risk_score <= 3: # Conservative
base_allocation = {
'Bonds': 0.6,
'Stocks': 0.2,
'ETFs': 0.1,
'Real Estate': 0.05,
'Other Alternatives': 0.05
}
elif risk_score >= 8: # Aggressive
base_allocation = {
'Stocks': 0.5,
'ETFs': 0.2,
'Real Estate': 0.1,
'Cryptocurrencies': 0.1,
'Other Alternatives': 0.1
}
# Recommended portfolio details
portfolio_recommendation = {
'risk_score': risk_score,
'recommended_investment_type': recommended_investment_type,
'allocation': base_allocation,
'target_return': target_return,
'market_indices': market_data
}
return portfolio_recommendation
def analyze_equity_bonds(self, risk_tolerance, investment_amount, investment_timeframe, sector_preference = None):
"""Analyze Equities and Bonds and recommend investments
Args:
risk_tolerance: (str) "Low", "Medium", "High"
investment_amount: (float) total investment amount
investment_timeframe: (str) "Short term", "Medium term", "Long term"
sector_preference: (str) for equities, can be "Tech", "Healthcare", "Finance", etc.
"""
# Step 1: Data Retrieval for equities
equity_data = self.get_real_time_market_data(self.equity_etfs)
equity_df = pd.DataFrame.from_dict(equity_data, orient='index')
# Step 2: Data Retrieval for bonds
bond_data = self.get_real_time_market_data(self.bond_etfs)
bond_df = pd.DataFrame.from_dict(bond_data, orient='index')
# Additional data retrieval
for symbol in self.equity_etfs + self.bond_etfs:
ticker = yf.Ticker(symbol)
hist = ticker.history(period="1y")
if not hist.empty:
returns = hist['Close'].pct_change().dropna() # Daily returns, remove the first NAN value
equity_df.loc[symbol, 'annual_return'] = returns.mean() * 252 # Annualize returns
else:
equity_df.loc[symbol, 'annual_return'] = 0
# Equity Analysis
equity_df['risk_adjusted_return'] = equity_df['annual_return'] / equity_df['volatility'] if equity_df['volatility'].any() > 0 else 0
if sector_preference:
# Fetch and match to sector specific ETFs
sector_etfs_dict = {
"Technology": ["XLK","VGT"],
"Healthcare":["XLV","VHT"],
"Finance": ["XLF", "VFH"]
}
sector_etfs = sector_etfs_dict.get(sector_preference, None)
if sector_etfs:
sector_data = self.get_real_time_market_data(sector_etfs)
sector_df = pd.DataFrame.from_dict(sector_data, orient='index')
# additional data retrieve for sector
for symbol in sector_etfs:
ticker = yf.Ticker(symbol)
hist = ticker.history(period="1y")
if not hist.empty:
returns = hist['Close'].pct_change().dropna() # Daily returns, remove the first NAN value
sector_df.loc[symbol, 'annual_return'] = returns.mean() * 252 # Annualize returns
else:
sector_df.loc[symbol, 'annual_return'] = 0
sector_df['risk_adjusted_return'] = sector_df['annual_return'] / sector_df['volatility'] if sector_df['volatility'].any() > 0 else 0
# Concatenate the dataframes of the Sector data with the equity data
equity_df = pd.concat([equity_df, sector_df])
# Bond analysis
bond_df['risk_adjusted_return'] = bond_df['returns_1m'] / bond_df['volatility'] if bond_df['volatility'].any() > 0 else 0
# Step 3: Asset selection based on risk tolerance
if risk_tolerance == "Low":
equity_recommendations = equity_df.sort_values(by=['volatility']).head(3).index.tolist() # Lower vol
bond_recommendations = bond_df.sort_values(by=['risk_adjusted_return'], ascending=False).head(2).index.tolist() # Higher returns for low risk
elif risk_tolerance == "Medium":
equity_recommendations = equity_df.sort_values(by=['risk_adjusted_return'], ascending=False).head(3).index.tolist()
bond_recommendations = bond_df.sort_values(by=['risk_adjusted_return'], ascending=False).head(2).index.tolist()
else: # High Risk
equity_recommendations = equity_df.sort_values(by=['risk_adjusted_return'], ascending=False).head(3).index.tolist()
bond_recommendations = bond_df.sort_values(by=['volatility'], ascending=False).head(2).index.tolist() # higher yield, volatile bonds
# Step 4: Recommended Investment with allocation
if investment_timeframe == 'Short term':
allocation = {'Bonds':0.6, 'Equities':0.4}
elif investment_timeframe == 'Medium term':
allocation = {'Bonds': 0.4, 'Equities':0.6}
else: # Long Term
allocation = {'Bonds':0.3, 'Equities':0.7}
formatted_output = f"Recommended allocation: Bonds {allocation['Bonds'] * 100:.2f}%, Equities: {allocation['Equities'] * 100:.2f}% \n"
formatted_output += f"Equity Recommendations: \n"
for rec in equity_recommendations:
formatted_output += f" - {rec}\n"
formatted_output += f"Bond Recommendations: \n"
for rec in bond_recommendations:
formatted_output += f" - {rec}\n"
return formatted_output
def create_gradio_interface(self):
"""
Create Gradio interface for the Advanced Hedge Fund Management System
Returns:
gr.Interface: Gradio web interface
"""
def analyze_investment_profile(age, income, investment_experience,
current_investments, education_level,
family_size, debt_to_income):
"""
Comprehensive investment profile analysis
"""
# Prepare client features
client_features = np.array([
age, income, investment_experience, current_investments,
education_level, family_size, debt_to_income
])
# Get portfolio recommendation
recommendation = self.recommend_portfolio_allocation(client_features)
# Format output
allocation_str = "\n".join([
f"{k}: {v*100:.2f}%" for k, v in recommendation['allocation'].items()
])
output = (
f"Risk Score: {recommendation['risk_score']:.2f}/10\n"
f"Recommended Investment Type: {recommendation['recommended_investment_type']}\n"
f"Target Annual Return: {recommendation['target_return']*100:.2f}%\n\n"
"Portfolio Allocation:\n" + allocation_str + "\n\n"
"Market Indices Performance:\n" +
"\n".join([
f"{symbol}: {data['returns_1m']:.2f}% (1M Return)"
for symbol, data in recommendation['market_indices'].items()
])
)
return output
def analyze_equity_bond_investments(risk_tolerance, investment_amount, investment_timeframe, sector_preference):
"""
Analyze equity and bond investments based on users preferences
"""
return self.analyze_equity_bonds(risk_tolerance, investment_amount, investment_timeframe, sector_preference)
# Gradio interface with more comprehensive inputs
interface = gr.TabbedInterface(
[
gr.Interface(
fn=analyze_investment_profile,
inputs=[
gr.Number(label="Age"),
gr.Number(label="Annual Income"),
gr.Number(label="Investment Experience (Years)"),
gr.Number(label="Current Investments"),
gr.Dropdown(label="Education Level", choices=[1, 2, 3, 4]),
gr.Number(label="Family Size"),
gr.Number(label="Debt-to-Income Ratio")
],
outputs=gr.Textbox(label="Investment Profile Analysis"),
title="Investment Profile Analysis",
description="Get personalized recommendations based on your profile"
),
gr.Interface(
fn=analyze_equity_bond_investments,
inputs=[
gr.Dropdown(label="Risk Tolerance", choices=["Low", "Medium", "High"]),
gr.Number(label="Investment Amount"),
gr.Dropdown(label="Investment Timeframe", choices=["Short term", "Medium term", "Long term"]),
gr.Dropdown(label="Sector Preference", choices = ["Technology","Healthcare", "Finance", None] )
],
outputs=gr.Textbox(label="Equity and Bond Analysis"),
title="Equity and Bond Analysis",
description="Analyze and get recommended Equities and Bonds based on your parameters"
)
],
tab_names=["Investment Profile","Equity and Bond Analyzer"],
title="Advanced Hedge Fund Management System",
# description="Enter your details to get personalized investment recommendations." # Removed description here
)
return interface
def run_gradio_app(self):
"""
Run the Gradio web application
"""
interface = self.create_gradio_interface()
interface.launch()
if __name__ == "__main__":
hedge_fund_system = AdvancedHedgeFundManagementSystem()
hedge_fund_system.run_gradio_app() |