AM (Alpha Model)
Creating Your Portfolio Position in a Very Simple Way: Embracing a Bias-Free Approach
Develop AM (Alpha Model)
Helper Function: Calculating Previous Start Date
from datetime import datetime, timedelta
def calculate_previous_start_date(start_date, lookback_days):
start = datetime.strptime(str(start_date), "%Y%m%d")
previous_start = start - timedelta(days=lookback_days)
return int(previous_start.strftime("%Y%m%d"))
Very simple AM script
from finter import BaseAlpha
# Define the lookback period in days
LOOKBACK_DAYS = 365
start, end = 20200101, 20220101
# Alpha class inheriting from BaseAlpha
class Alpha(BaseAlpha):
# Method to generate alpha
def get(self, start, end):
# Calculate the start date for data retrieval
pre_start = calculate_previous_start_date(start, LOOKBACK_DAYS)
# Retrieve daily closing prices
self.close = self.get_cm(
"content.fnguide.ftp.price_volume.price_close.1d"
).get_df(pre_start, end)
# Calculate momentum
momentum_21d = self.close.pct_change(21)
# Rank stocks by momentum
stock_rank = momentum_21d.rank(pct=True, axis=1)
# Select top 10% of stocks
stock_top10 = stock_rank[stock_rank>=0.9]
# Apply rolling mean to smooth data
stock_top10_rolling = stock_top10.rolling(21).apply(lambda x: x.mean())
# Normalize and scale to position sizes
stock_ratio = stock_top10_rolling.div(stock_top10_rolling.sum(axis=1), axis=0)
position = stock_ratio * 1e8
# Shift positions to avoid look-ahead bias
alpha = position.shift(1)
# Alpha position must be a value between start and end
return alpha.loc[str(start): str(end)]
# Run the alpha generation process
alpha = Alpha().get(start, end)
This guide provides a basic framework for writing an alpha in Python. It is important to note that this is a simplified example, and real-world alpha development involves more complex data analysis, risk management, and performance evaluation.
Last updated
Was this helpful?