Editing
Algorithmic Trading
(section)
Jump to navigation
Jump to search
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
== <span style="color: #FFFFFF;">Applying</span> == '''ML trading strategy with cross-sectional momentum:''' <syntaxhighlight lang="python"> import pandas as pd import numpy as np from sklearn.ensemble import GradientBoostingRegressor from sklearn.preprocessing import RobustScaler import yfinance as yf def compute_features(prices_df: pd.DataFrame) -> pd.DataFrame: """Compute cross-sectional trading features.""" features = pd.DataFrame(index=prices_df.index) # Momentum features (key factors in equity strategies) for window in [5, 21, 63, 126, 252]: returns = prices_df.pct_change(window) features[f'mom_{window}d'] = returns.rank(axis=1, pct=True).stack() # Mean-reversion (contrarian at short timescales) features['reversal_5d'] = -prices_df.pct_change(5).rank(axis=1, pct=True).stack() # Volatility (vol normalization) features['vol_21d'] = prices_df.pct_change().rolling(21).std().stack() # Volume-price trend features['volume_trend'] = (prices_df / prices_df.rolling(20).mean()).stack() return features.dropna() def train_alpha_model(features: pd.DataFrame, returns: pd.Series): """Train cross-sectional return predictor.""" # Target: forward 21-day cross-sectional rank of returns y = returns.groupby(level='date').rank(pct=True) X = features.reindex(y.index) # Time-series cross-validation (never look forward) cutoff = int(len(y.unique()) * 0.8) dates = sorted(y.index.get_level_values('date').unique()) train_dates = dates[:cutoff] X_train = X[X.index.get_level_values('date').isin(train_dates)] y_train = y[y.index.get_level_values('date').isin(train_dates)] scaler = RobustScaler() model = GradientBoostingRegressor(n_estimators=200, max_depth=3, learning_rate=0.05) model.fit(scaler.fit_transform(X_train.fillna(0)), y_train) return model, scaler def backtest_strategy(model, scaler, features, prices, top_n=20): """Simulate long-short strategy: long top quintile, short bottom quintile.""" returns = prices.pct_change() preds = pd.Series(model.predict(scaler.transform(features.fillna(0))), index=features.index, name='alpha_score') portfolio_returns = [] for date in sorted(preds.index.get_level_values('date').unique()): day_preds = preds.xs(date, level='date').sort_values(ascending=False) longs = day_preds.head(top_n).index shorts = day_preds.tail(top_n).index if date in returns.index: long_ret = returns.loc[date, longs].mean() short_ret = returns.loc[date, shorts].mean() portfolio_returns.append(long_ret - short_ret) pnl = pd.Series(portfolio_returns) sharpe = pnl.mean() / pnl.std() * np.sqrt(252) print(f"Annualized Sharpe: {sharpe:.2f} | Max Drawdown: {(pnl.cumsum() - pnl.cumsum().cummax()).min():.2%}") return pnl </syntaxhighlight> ; Algorithmic trading AI tools : '''Backtesting''' β Backtrader, Zipline, QuantConnect (cloud), VectorBT : '''Alternative data''' β Quandl (Nasdaq), Bloomberg Terminal, Refinitiv Eikon : '''NLP sentiment''' β FinBERT, Bloomberg NLP, Ravenpack, Accern : '''Execution''' β Alpaca (API broker), Interactive Brokers API, FIX Protocol : '''Research platforms''' β QuantConnect, Numerai (crowdsourced hedge fund) </div> <div style="background-color: #8B4500; color: #FFFFFF; padding: 20px; border-radius: 8px; margin-bottom: 15px;">
Summary:
Please note that all contributions to BloomWiki may be edited, altered, or removed by other contributors. If you do not want your writing to be edited mercilessly, then do not submit it here.
You are also promising us that you wrote this yourself, or copied it from a public domain or similar free resource (see
BloomWiki:Copyrights
for details).
Do not submit copyrighted work without permission!
Cancel
Editing help
(opens in new window)
Navigation menu
Personal tools
Not logged in
Talk
Contributions
Create account
Log in
Namespaces
Page
Discussion
English
Views
Read
Edit
View history
More
Search
Navigation
Main page
Recent changes
Random page
Help about MediaWiki
Tools
What links here
Related changes
Special pages
Page information