Adjust Return Calculation for Long-Term Focus: Switch from annualized metrics to multi-year compounding to better reflect long-term growth potential.
Incorporate Economic Cycles: Implement features or conditions that simulate economic cycles (e.g., growth, recession) to observe how portfolios perform in different market phases.
Enhanced Downside Risk Measures: Replace or complement the Sortino ratio with additional downside risk metrics, like Conditional Value at Risk (CVaR), which is useful for assessing tail risk over extended periods.
apply the above improvement to the system and return me the full enhanced code, no need any explnation:
import yfinance as yf
import pandas as pd
import numpy as np
import random
from bs4 import BeautifulSoup
import requests
from tqdm import tqdm
import sys
import warnings
import multiprocessing
import matplotlib.pyplot as plt
def sortino_ratio(returns, target=0):
downside = returns[returns < target]
if len(downside) == 0:
return 0 # No downside risk; assign a neutral value
expected_return = returns.mean() * 252
downside_risk = np.sqrt((downside ** 2).mean()) * np.sqrt(252)
return (expected_return - target) / downside_risk if downside_risk != 0 else 0
Function to generate portfolio weights within constraints
def generate_weights(n, lower=0.10, upper=0.20, max_attempts=1000):
"""
Generates a list of weights that sum to 1.0 with each weight between lower and upper bounds.
"""
for _ in range(max_attempts):
weights = np.random.uniform(lower, upper, n)
weights /= weights.sum()
if all(lower <= w <= upper for w in weights):
return weights
raise ValueError("Unable to generate weights within constraints after multiple attempts.")
Assistant
Parameters
START_DATE = '2000-01-01'
END_DATE = '2024-10-30'
NUM_ASSETS = 8 # Number of stocks in the portfolio
LOWER_WEIGHT = 0.10
UPPER_WEIGHT = 0.20
RISK_FREE_RATE = 0.017 # Approximate risk-free rate (e.g., 10-year US Treasury yield)
for ticker in tqdm(tickers, desc="Downloading tickers"):
try:
df = yf.download(ticker, start=START_DATE, end=END_DATE, progress=False)['Adj Close']
if df.empty:
failed_tickers.append(ticker)
else:
data[ticker] = df
successful_tickers.append(ticker)
ticker_first_dates[ticker] = df.first_valid_index()
except Exception as e:
failed_tickers.append(ticker)
print(f"\nTotal tickers with successful data download: {len(successful_tickers)}")
print(f"Total tickers failed to download: {len(failed_tickers)}")
if failed_tickers:
print(f"Failed tickers: {failed_tickers}")
Determine the earliest start date among all successful tickers
if ticker_first_dates:
earliest_date = min(ticker_first_dates.values())
print(f"Earliest available data starts from: {earliest_date.date()}")
code
# Adjust the dataset to start from the earliest_date
data = data.loc[earliest_date:]
# Forward fill to propagate last valid observation
data.fillna(method='ffill', inplace=True)
# Backward fill to handle any remaining NaNs at the start
data.fillna(method='bfill', inplace=True)
print(f"Data shape after adjusting start date and dropping incomplete data: {data.shape}")
else:
print("No data available after processing tickers.")
sys.exit()
If there are not enough tickers, exit
if len(data.columns) < NUM_ASSETS:
print("Not enough tickers with complete data to form a portfolio.")
sys.exit()
Step 3: Calculate daily returns
returns = data.pct_change().dropna()
Step 4: Split data into Training (70%), Validation (15%), Testing (15%)
POPULATION_SIZE = 500 # Adjusted for memory constraints
P_CROSSOVER = 0.8 # Probability for crossover
P_MUTATION = 0.2 # Probability for mutating an individual
MAX_GENERATIONS = 100 # Increased number of generations for better convergence
HALL_OF_FAME_SIZE = 1 # Number of best individuals to keep
Define the weights for each optimization objective
# Ensure all selected tickers are unique
if len(set(selected_tickers)) != NUM_ASSETS:
return -np.inf, # Invalid individual
# Ensure weights sum to 1 and are within constraints
weights = np.array(weights)
if not np.isclose(weights.sum(), 1.0):
return -np.inf,
if not all(LOWER_WEIGHT <= w <= UPPER_WEIGHT for w in weights):
return -np.inf,
# Check if all tickers are present in the covariance matrix
if not all(ticker in train_cov_matrix.columns for ticker in selected_tickers):
return -np.inf, # Invalid individual
# Calculate portfolio return and volatility using Training Set
try:
portfolio_return_train = np.dot(weights, train_ann_return[selected_tickers])
portfolio_volatility_train = np.sqrt(np.dot(weights, np.dot(train_cov_matrix.loc[selected_tickers, selected_tickers].values, weights)))
except KeyError as e:
# In case tickers are not found in covariance matrix
return -np.inf,
if portfolio_volatility_train == 0:
return -np.inf,
# Calculate Sharpe Ratio for Training
sharpe_ratio_train = (portfolio_return_train - RISK_FREE_RATE) / portfolio_volatility_train
# Calculate Sortino Ratio for Training
portfolio_sortino_train = sortino_ratio(train_returns[selected_tickers].dot(weights))
# Calculate portfolio cumulative returns for Max Drawdown using Training Set
portfolio_cum_returns_train = (1 + train_returns[selected_tickers].dot(weights)).cumprod()
portfolio_max_drawdown_train = max_drawdown(portfolio_cum_returns_train)
# Calculate Validation Metrics
try:
portfolio_return_val = np.dot(weights, validation_ann_return[selected_tickers])
portfolio_volatility_val = np.sqrt(np.dot(weights, np.dot(validation_cov_matrix.loc[selected_tickers, selected_tickers].values, weights)))
except KeyError as e:
return -np.inf,
if portfolio_volatility_val == 0:
return -np.inf,
# Calculate Sharpe Ratio for Validation
sharpe_ratio_val = (portfolio_return_val - RISK_FREE_RATE) / portfolio_volatility_val if portfolio_volatility_val != 0 else 0
# Calculate Sortino Ratio for Validation
portfolio_sortino_val = sortino_ratio(validation_returns[selected_tickers].dot(weights))
# Calculate portfolio cumulative returns for Max Drawdown using Validation Set
portfolio_cum_returns_val = (1 + validation_returns[selected_tickers].dot(weights)).cumprod()
portfolio_max_drawdown_val = max_drawdown(portfolio_cum_returns_val)
# Combine the metrics into a single fitness score
# Weighted average of training and validation scores
fitness_train = (WEIGHT_SHARPE * sharpe_ratio_train) \
- (WEIGHT_MAX_DRAWDOWN * portfolio_max_drawdown_train) \
+ (WEIGHT_ANNUAL_RETURN * portfolio_return_train) \
- (WEIGHT_VOLATILITY * portfolio_volatility_train) \
+ (WEIGHT_SORTINO * portfolio_sortino_train)
fitness_val = (WEIGHT_SHARPE * sharpe_ratio_val) \
- (WEIGHT_MAX_DRAWDOWN * portfolio_max_drawdown_val) \
+ (WEIGHT_ANNUAL_RETURN * portfolio_return_val) \
- (WEIGHT_VOLATILITY * portfolio_volatility_val) \
+ (WEIGHT_SORTINO * portfolio_sortino_val)
# Combine Training and Validation Fitness
fitness = (fitness_train + fitness_val) / 2
return fitness,
Create the DEAP framework
creator.create("FitnessMax", base.Fitness, weights=(1.0,)) # Single objective, maximize
creator.create("Individual", list, fitness=creator.FitnessMax)
print("\nStarting Genetic Algorithm Evolution...\n")
for gen in tqdm(range(1, MAX_GENERATIONS + 1), desc="Generations"):
# Select the next generation individuals
offspring = toolbox.select(population, len(population))
offspring = list(map(toolbox.clone, offspring))
code
# Apply crossover on the offspring
for child1, child2 in zip(offspring[::2], offspring[1::2]):
if random.random() < P_CROSSOVER:
toolbox.mate(child1, child2)
del child1.fitness.values
del child2.fitness.values
# Apply mutation on the offspring
for mutant in offspring:
if random.random() < P_MUTATION:
toolbox.mutate(mutant)
del mutant.fitness.values
# Evaluate the individuals with an invalid fitness
invalid_ind = [ind for ind in offspring if not ind.fitness.valid]
fitnesses = toolbox.map(toolbox.evaluate, invalid_ind)
for ind, fit in zip(invalid_ind, fitnesses):
ind.fitness.values = fit
# Replace population with offspring
population[:] = offspring
# Update the hall of fame with the generated individuals
hof.update(population)
# Gather all the fitnesses in one list
fits = [ind.fitness.values[0] for ind in population]
# Callback to print instant best portfolio
callback(gen, population, fits)