text
stringlengths
1
93.6k
if quick_test:
print("Quick test mode: Performing simplified XGBoost tuning...")
param_dist = {"n_estimators": randint(10, 50), "max_depth": randint(3, 6)}
n_iter = 5
else:
print("Full analysis mode: Performing comprehensive XGBoost tuning...")
param_dist = {
"n_estimators": randint(100, 500),
"max_depth": randint(3, 10),
"learning_rate": uniform(0.01, 0.3),
"subsample": uniform(0.6, 1.0),
"colsample_bytree": uniform(0.6, 1.0),
"gamma": uniform(0, 5),
}
n_iter = 20
# Initialize XGBoost model
xgb = XGBRegressor(random_state=42)
# Perform randomized search for best parameters
tscv = TimeSeriesSplit(n_splits=3 if quick_test else 5)
xgb_random = RandomizedSearchCV(
estimator=xgb,
param_distributions=param_dist,
n_iter=n_iter,
cv=tscv,
scoring="neg_mean_squared_error", # Change to MSE
verbose=2,
random_state=42,
n_jobs=-1,
)
xgb_random.fit(X.reshape(X.shape[0], -1), y)
print(f"Best XGBoost parameters: {xgb_random.best_params_}")
return xgb_random.best_estimator_
def implement_trading_strategy(actual_prices, predicted_prices, threshold=0.01):
returns = []
position = 0 # -1: short, 0: neutral, 1: long
for i in range(1, len(actual_prices)):
predicted_return = (predicted_prices[i] - actual_prices[i - 1]) / actual_prices[
i - 1
]
if predicted_return > threshold and position <= 0:
position = 1 # Buy
elif predicted_return < -threshold and position >= 0:
position = -1 # Sell
actual_return = (actual_prices[i] - actual_prices[i - 1]) / actual_prices[i - 1]
returns.append(position * actual_return)
return np.array(returns)
def select_features_rfe(X, y, n_features_to_select=10):
if isinstance(X, np.ndarray) and len(X.shape) == 3:
X_2d = X.reshape(X.shape[0], -1)
else:
X_2d = X
rfe = RFE(
estimator=RandomForestRegressor(random_state=42),
n_features_to_select=n_features_to_select,
)
X_selected = rfe.fit_transform(X_2d, y)
selected_features = rfe.support_
return X_selected, selected_features
def calculate_ensemble_weights(models, X, y):
weights = []
for name, model in models:
_, _, score, _ = train_and_evaluate_model(
model, X, y, n_splits=5, model_name=name
)
weights.append(max(score, 0)) # Ensure non-negative weights
if sum(weights) == 0:
# If all weights are zero, use equal weights
return [1 / len(weights)] * len(weights)
else:
return [w / sum(weights) for w in weights] # Normalize weights
def augment_data(X, y, noise_level=0.01):
X_aug = X.copy()
y_aug = y.copy()
noise = np.random.normal(0, noise_level, X.shape)
X_aug += noise
return X_aug, y_aug
# Main function to analyze stock data and make predictions
def analyze_and_predict_stock(
symbol,
start_date,
end_date,
future_days=30,
suppress_warnings=False,
quick_test=False,
models_to_run=["LSTM", "GRU", "Random Forest", "XGBoost"],
):
# Suppress warnings if flag is set