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.")
Function to label economic cycles
def label_economic_cycles(dates):
recession_periods = [
('2001-03-01', '2001-11-30'),
('2007-12-01', '2009-06-30'),
('2020-02-01', '2020-04-30')
]
labels = []
for date in dates:
# Remove timezone information if present
if date.tzinfo is not None:
date = date.replace(tzinfo=None)
label = 'Growth'
for start, end in recession_periods:
if pd.to_datetime(start) <= date <= pd.to_datetime(end):
label = 'Recession'
break
labels.append(label)
return labels
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()}")
# 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: Label economic cycles
print("Labeling economic cycles...")
return_dates = returns.index
labels = label_economic_cycles(return_dates)
labels = pd.Series(labels, index=return_dates) # Convert to Series with matching index
Step 5: 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
# Training Metrics
portfolio_returns_train = train_returns[selected].dot(weights)
portfolio_cagr_train = calculate_cagr(portfolio_returns_train)
portfolio_volatility_train = portfolio_returns_train.std() * np.sqrt(252)
sharpe_ratio_train = (portfolio_returns_train.mean() * 252 - RISK_FREE_RATE) / portfolio_volatility_train if portfolio_volatility_train != 0 else 0
sortino_growth_train = sortino_ratio(portfolio_returns_train[train_labels == 'Growth'])
sortino_recession_train = sortino_ratio(portfolio_returns_train[train_labels == 'Recession'])
annualized_return_train = portfolio_returns_train.mean() * 252
portfolio_cum_returns_growth_train = (1 + portfolio_returns_train[train_labels == 'Growth']).cumprod()
portfolio_cum_returns_recession_train = (1 + portfolio_returns_train[train_labels == 'Recession']).cumprod()
portfolio_max_drawdown_growth_train = max_drawdown(portfolio_cum_returns_growth_train)
portfolio_max_drawdown_recession_train = max_drawdown(portfolio_cum_returns_recession_train)
# Validation Metrics
try:
portfolio_returns_val = validation_returns[selected].dot(weights)
portfolio_cagr_val = calculate_cagr(portfolio_returns_val)
portfolio_volatility_val = portfolio_returns_val.std() * np.sqrt(252)
sharpe_ratio_val = (portfolio_returns_val.mean() * 252 - RISK_FREE_RATE) / portfolio_volatility_val if portfolio_volatility_val != 0 else 0
sortino_growth_val = sortino_ratio(portfolio_returns_val[validation_labels == 'Growth'])
sortino_recession_val = sortino_ratio(portfolio_returns_val[validation_labels == 'Recession'])
annualized_return_val = portfolio_returns_val.mean() * 252
portfolio_cum_returns_growth_val = (1 + portfolio_returns_val[validation_labels == 'Growth']).cumprod()
portfolio_cum_returns_recession_val = (1 + portfolio_returns_val[validation_labels == 'Recession']).cumprod()
portfolio_max_drawdown_growth_val = max_drawdown(portfolio_cum_returns_growth_val)
portfolio_max_drawdown_recession_val = max_drawdown(portfolio_cum_returns_recession_val)
except:
portfolio_cagr_val = 0
portfolio_volatility_val = 0
sharpe_ratio_val = 0
sortino_growth_val = 0
sortino_recession_val = 0
annualized_return_val = 0
portfolio_max_drawdown_growth_val = 0
portfolio_max_drawdown_recession_val = 0
# Testing Metrics
try:
portfolio_returns_test = test_returns[selected].dot(weights)
portfolio_cagr_test = calculate_cagr(portfolio_returns_test)
portfolio_volatility_test = portfolio_returns_test.std() * np.sqrt(252)
sharpe_ratio_test = (portfolio_returns_test.mean() * 252 - RISK_FREE_RATE) / portfolio_volatility_test if portfolio_volatility_test != 0 else 0
sortino_test_growth = sortino_ratio(portfolio_returns_test[test_labels == 'Growth'])
sortino_test_recession = sortino_ratio(portfolio_returns_test[test_labels == 'Recession'])
annualized_return_test = portfolio_returns_test.mean() * 252
portfolio_cum_returns_growth_test = (1 + portfolio_returns_test[test_labels == 'Growth']).cumprod()
portfolio_cum_returns_recession_test = (1 + portfolio_returns_test[test_labels == 'Recession']).cumprod()
portfolio_max_drawdown_growth_test = max_drawdown(portfolio_cum_returns_growth_test)
portfolio_max_drawdown_recession_test = max_drawdown(portfolio_cum_returns_recession_test)
except:
portfolio_cagr_test = 0
portfolio_volatility_test = 0
sharpe_ratio_test = 0
sortino_test_growth = 0
sortino_test_recession = 0
annualized_return_test = 0
portfolio_max_drawdown_growth_test = 0
portfolio_max_drawdown_recession_test = 0
# Composite Fitness Score on Training and Validation Sets
fitness_train = (
WEIGHT_SHARPE * sharpe_ratio_train +
WEIGHT_SORTINO_GROWTH * sortino_growth_train +
WEIGHT_SORTINO_RECESSION * sortino_recession_train +
WEIGHT_VOLATILITY * (-portfolio_volatility_train) +
WEIGHT_ANNUALIZED_RETURN * annualized_return_train +
WEIGHT_MAX_DRAWDOWN * (portfolio_max_drawdown_growth_train + portfolio_max_drawdown_recession_train) / 2
)
fitness_val = (
WEIGHT_SHARPE * sharpe_ratio_val +
WEIGHT_SORTINO_GROWTH * sortino_growth_val +
WEIGHT_SORTINO_RECESSION * sortino_recession_val +
WEIGHT_VOLATILITY * (-portfolio_volatility_val) +
WEIGHT_ANNUALIZED_RETURN * annualized_return_val +
WEIGHT_MAX_DRAWDOWN * (portfolio_max_drawdown_growth_val + portfolio_max_drawdown_recession_val) / 2
)
fitness = (fitness_train + fitness_val) / 2
portfolio_df = pd.DataFrame({
'Ticker': selected,
'Allocation': [f"{w*100:.2f}%" for w in weights]
})
print("Optimal Portfolio Found:")
display(portfolio_df)
print(f"--- Training Set Performance ---")
print(f"CAGR: {portfolio_cagr_train*100:.2f}%")
print(f"Annualized Volatility: {portfolio_volatility_train*100:.2f}%")
print(f"Sharpe Ratio: {sharpe_ratio_train:.2f}")
print(f"Sortino Ratio (Growth): {sortino_growth_train:.2f}")
print(f"Sortino Ratio (Recession): {sortino_recession_train:.2f}")
print(f"Annualized Return: {annualized_return_train*100:.2f}%")
print(f"Maximum Drawdown (Growth): {portfolio_max_drawdown_growth_train:.2%}")
print(f"Maximum Drawdown (Recession): {portfolio_max_drawdown_recession_train:.2%}")
print(f"--- Validation Set Performance ---")
print(f"CAGR: {portfolio_cagr_val*100:.2f}%")
print(f"Annualized Volatility: {portfolio_volatility_val*100:.2f}%")
print(f"Sharpe Ratio: {sharpe_ratio_val:.2f}")
print(f"Sortino Ratio (Growth): {sortino_growth_val:.2f}")
print(f"Sortino Ratio (Recession): {sortino_recession_val:.2f}")
print(f"Annualized Return: {annualized_return_val*100:.2f}%")
print(f"Maximum Drawdown (Growth): {portfolio_max_drawdown_growth_val:.2%}")
print(f"Maximum Drawdown (Recession): {portfolio_max_drawdown_recession_val:.2%}")
print(f"--- Testing Set Performance ---")
print(f"CAGR: {portfolio_cagr_test*100:.2f}%")
print(f"Annualized Volatility: {portfolio_volatility_test*100:.2f}%")
print(f"Sharpe Ratio: {sharpe_ratio_test:.2f}")
print(f"Sortino Ratio (Growth): {sortino_test_growth:.2f}")
print(f"Sortino Ratio (Recession): {sortino_test_recession:.2f}")
print(f"Annualized Return: {annualized_return_test*100:.2f}%")
print(f"Maximum Drawdown (Growth): {portfolio_max_drawdown_growth_test:.2%}")
print(f"Maximum Drawdown (Recession): {portfolio_max_drawdown_recession_test:.2%}")
# Assess overfitting
print("\n--- Overfitting Assessment ---")
# Define thresholds for acceptable performance differences
threshold_cagr = 0.05 # Threshold for CAGR difference
train_val_cagr_diff = portfolio_cagr_train - portfolio_cagr_val
train_test_cagr_diff = portfolio_cagr_train - portfolio_cagr_test if 'portfolio_cagr_test' in locals() else 0
train_val_vol_diff = portfolio_volatility_train - portfolio_volatility_val
train_test_vol_diff = portfolio_volatility_train - portfolio_volatility_test if 'portfolio_volatility_test' in locals() else 0
overfitting_cagr = train_test_cagr_diff > threshold_cagr
overfitting_vol = train_test_vol_diff < -threshold_volatility
if overfitting_cagr and overfitting_vol:
print("Warning: Overfitting detected! The portfolio performs significantly better on training and validation data compared to testing data.")
else:
print("No significant overfitting detected. The portfolio generalizes well to unseen data.")
# Plot cumulative returns for visual assessment
plt.figure(figsize=(14, 7))
# Training Cumulative Returns
plt.subplot(1, 2, 1)
if not portfolio_cum_returns_growth_train.empty:
plt.plot(portfolio_cum_returns_growth_train.index, portfolio_cum_returns_growth_train, label='Training Growth')
if not portfolio_cum_returns_recession_train.empty:
plt.plot(portfolio_cum_returns_recession_train.index, portfolio_cum_returns_recession_train, label='Training Recession')
if not portfolio_cum_returns_growth_val.empty:
plt.plot(portfolio_cum_returns_growth_val.index, portfolio_cum_returns_growth_val, label='Validation Growth')
if not portfolio_cum_returns_recession_val.empty:
plt.plot(portfolio_cum_returns_recession_val.index, portfolio_cum_returns_recession_val, label='Validation Recession')
if 'portfolio_cum_returns_growth_test' in locals() and not portfolio_cum_returns_growth_test.empty:
plt.plot(portfolio_cum_returns_growth_test.index, portfolio_cum_returns_growth_test, label='Testing Growth')
if 'portfolio_cum_returns_recession_test' in locals() and not portfolio_cum_returns_recession_test.empty:
plt.plot(portfolio_cum_returns_recession_test.index, portfolio_cum_returns_recession_test, label='Testing Recession')
plt.title('Cumulative Returns')
plt.xlabel('Date')
plt.ylabel('Cumulative Return')
plt.legend()
# Drawdowns
plt.subplot(1, 2, 2)
if not portfolio_cum_returns_growth_train.empty:
plt.plot(portfolio_cum_returns_growth_train.index, (portfolio_cum_returns_growth_train / portfolio_cum_returns_growth_train.cummax()) - 1, label='Training Growth Drawdown')
if not portfolio_cum_returns_recession_train.empty:
plt.plot(portfolio_cum_returns_recession_train.index, (portfolio_cum_returns_recession_train / portfolio_cum_returns_recession_train.cummax()) - 1, label='Training Recession Drawdown')
if not portfolio_cum_returns_growth_val.empty:
plt.plot(portfolio_cum_returns_growth_val.index, (portfolio_cum_returns_growth_val / portfolio_cum_returns_growth_val.cummax()) - 1, label='Validation Growth Drawdown')
if not portfolio_cum_returns_recession_val.empty:
plt.plot(portfolio_cum_returns_recession_val.index, (portfolio_cum_returns_recession_val / portfolio_cum_returns_recession_val.cummax()) - 1, label='Validation Recession Drawdown')
if 'portfolio_cum_returns_growth_test' in locals() and not portfolio_cum_returns_growth_test.empty:
plt.plot(portfolio_cum_returns_growth_test.index, (portfolio_cum_returns_growth_test / portfolio_cum_returns_growth_test.cummax()) - 1, label='Testing Growth Drawdown')
if 'portfolio_cum_returns_recession_test' in locals() and not portfolio_cum_returns_recession_test.empty:
plt.plot(portfolio_cum_returns_recession_test.index, (portfolio_cum_returns_recession_test / portfolio_cum_returns_recession_test.cummax()) - 1, label='Testing Recession Drawdown')
plt.title('Drawdowns')
plt.xlabel('Date')
plt.ylabel('Drawdown')
plt.legend()
plt.tight_layout()
plt.show()
refactor the above code and also fixing the genetic algorithm of optimization as it seems not working properly
To refactor the provided code and improve the genetic algorithm optimization process, it's important to break down the process into more manageable parts while ensuring easier readability and maintaining efficiency. Let's focus on restructuring the code while addressing potential issues in the genetic algorithm setup. Here's how you can refactor the code:
Imports and Setup
First, import all necessary libraries in one place:
import sys
import random
import numpy as np
import pandas as pd
import requests
from tqdm import tqdm
import yfinance as yf
from bs4 import BeautifulSoup
from deap import base, creator, tools, algorithms
import multiprocessing
import matplotlib.pyplot as plt
# Set random seed for reproducibility
RANDOM_SEED = 42
random.seed(RANDOM_SEED)
np.random.seed(RANDOM_SEED)
# Define parameters
START_DATE = '2000-01-01'
END_DATE = '2024-10-30'
NUM_ASSETS = 8
LOWER_WEIGHT = 0.10
UPPER_WEIGHT = 0.20
RISK_FREE_RATE = 0.017 # Approximate risk-free rate
Data Fetching and Processing
Refactor the function to fetch S&P 500 tickers:
def get_sp500_tickers():
try:
response = requests.get('https://en.wikipedia.org/wiki/List_of_S%26P_500_companies')
response.raise_for_status()
soup = BeautifulSoup(response.text, "lxml")
table = soup.find('table', {'id': 'constituents'})
tickers = [
row.findAll('td')[0].text.strip().replace('.', '-')
for row in table.findAll('tr')[1:]
]
return tickers
except requests.RequestException as e:
raise Exception("Failed to fetch S&P 500 tickers from Wikipedia.") from e
def download_data(tickers, start_date, end_date):
data = {}
for ticker in tqdm(tickers, desc="Downloading ticker data"):
try:
df = yf.download(ticker, start=start_date, end=end_date, progress=False)['Adj Close']
if not df.empty:
data[ticker] = df
except Exception as e:
continue
return pd.DataFrame(data)
tickers = get_sp500_tickers()
data = download_data(tickers, START_DATE, END_DATE)
Ensure you handle missing data correctly:
earliest_date = data.first_valid_index()
data = data.loc[earliest_date:].fillna(method='ffill').fillna(method='bfill')
def label_economic_cycles(dates):
recession_periods = [
('2001-03-01', '2001-11-30'),
('2007-12-01', '2009-06-30'),
('2020-02-01', '2020-04-30')
]
return [
'Recession' if any(pd.to_datetime(start) <= date <= pd.to_datetime(end) for start, end in recession_periods)
else 'Growth' for date in dates
]
The above refactoring aims to ensure clarity and maintain proper structure.
Each function and process is clearly separated for better readability and reusability.
The genetic algorithm configuration is streamlined, with necessary improvements like setting up the toolbox correctly, ensuring weights sum to 1, and checking for valid ticker selections.
Cell In[2], line 24, in download_data(tickers, start_date, end_date)
22 except Exception as e:
23 continue
---> 24 return pd.DataFrame(data)
File /opt/conda/lib/python3.11/site-packages/pandas/core/frame.py:736, in DataFrame.init(self, data, index, columns, dtype, copy)
730 mgr = self._init_mgr(
731 data, axes={"index": index, "columns": columns}, dtype=dtype, copy=copy
732 )
734 elif isinstance(data, dict):
735 # GH#38939 de facto copy defaults to False only in non-dict cases
--> 736 mgr = dict_to_mgr(data, index, columns, dtype=dtype, copy=copy, typ=manager)
737 elif isinstance(data, ma.MaskedArray):
738 from numpy.ma import mrecords
File /opt/conda/lib/python3.11/site-packages/pandas/core/internals/construction.py:503, in dict_to_mgr(data, index, columns, dtype, typ, copy)
499 else:
500 # dtype check to exclude e.g. range objects, scalars
501 arrays = [x.copy() if hasattr(x, "dtype") else x for x in arrays]
--> 503 return arrays_to_mgr(arrays, columns, index, dtype=dtype, typ=typ, consolidate=copy)
File /opt/conda/lib/python3.11/site-packages/pandas/core/internals/construction.py:114, in arrays_to_mgr(arrays, columns, index, dtype, verify_integrity, typ, consolidate)
111 if verify_integrity:
112 # figure out the index, if necessary
113 if index is None:
--> 114 index = _extract_index(arrays)
115 else:
116 index = ensure_index(index)
File /opt/conda/lib/python3.11/site-packages/pandas/core/internals/construction.py:667, in _extract_index(data)
664 raise ValueError("Per-column arrays must each be 1-dimensional")
666 if not indexes and not raw_lengths:
--> 667 raise ValueError("If using all scalar values, you must pass an index")
669 if have_series:
670 index = union_indexes(indexes)
ValueError: If using all scalar values, you must pass an index
The error you are seeing may occur if the data dictionary returned by the download_data function is empty when you try to create a DataFrame from it. This can happen if all ticker data downloads fail, leaving the data dictionary without any entries. Let's modify the code to handle this situation gracefully.
Debugging and Handling the Error
Check Data Availability: Ensure that at least some data were downloaded successfully.
Handle Connection Errors: Log connection errors for each ticker.
Provide Alternative Solutions: If data is not available, decide how to proceed.
Let's modify the code:
def download_data(tickers, start_date, end_date):
data = {}
failed_tickers = []
for ticker in tqdm(tickers, desc="Downloading ticker data"):
try:
df = yf.download(ticker, start=start_date, end=end_date, progress=False)['Adj Close']
if not df.empty:
data[ticker] = df
else:
failed_tickers.append(ticker)
except Exception as e:
failed_tickers.append(ticker)
if not data:
raise ValueError("No data was downloaded. Ensure internet connectivity or try reducing the number of tickers.")
return pd.DataFrame(data), failed_tickers
# Get the list of S&P 500 tickers
tickers = get_sp500_tickers()
data, failed_tickers = download_data(tickers, START_DATE, END_DATE)
# Check if there are failed tickers
if failed_tickers:
print(f"The following tickers failed to download: {failed_tickers}")
# Just to ensure we have some data
if data.empty:
print("No data available after processing. Exiting.")
sys.exit()
Explanation
Failed Ticker Logging: We store tickers that fail to download in the failed_tickers list. This allows us to debug which tickers are failing to download or determine if there's a pattern or server issue.
Check for Empty Data: After attempting to download data for all tickers, we check if the data DataFrame is empty:
If it is, we log a message or raise an error indicating no data is available, possibly with a suggestion to check the internet connection or try again later.
Download Retry or Exit Strategy: Depending on project requirements, decide whether to retry downloads for failed tickers, or exit if no data is retrieved at all.
By adding this error handling, you can provide more informative debugging information and make the script more robust against network errors or changes in the Yahoo Finance API.