PM (Portfolio Model)
Create a portfolio by combining alphas created by yourself or others
Importing Libraries
Here, necessary libraries are imported for the operation of the portfolio model.
import numpy as np
from finter import BasePortfolio
Define Model Universe
# Model information configuration
model_universe = 'kr_stock'
Alpha List Definition
A list of alphas for the portfolio is defined. These alphas are specific financial models or strategies to be used within the portfolio. alpha_list
replaces the functionality of the deprecated alpha_set
.
alpha_list = [
"krx.krx.stock.ldh0127_qt.sample_univ_1",
"krx.krx.stock.soobeom33_qt.low_vol_factor_simple"
]
Portfolio Class Definition
A Portfolio
class is defined, inheriting from BasePortfolio
. It includes methods for loading alpha positions for a given period and fetching alpha positions to construct the portfolio.
There are two key methods that must be inherited from BasePortfolio:
weight: This method should return a pd.DataFrame where the row indices represent the trading dates and the columns correspond to the “sub-alphas.” The rows must sum to 1.0 (i.e., the weights across sub-alphas for each date should add up to 1.0).
get: This method should return the model’s final positions as a pd.DataFrame. Each row (i.e., each trading date) must sum to 1e8.
In the BasePortfolio class, both methods are already implemented:
weight: Returns an equal-weighted DataFrame across the elements in alpha_list.
get: Returns the weighted sum of the results from the weight method.
class Portfolio(BasePortfolio):
alpha_list = alpha_list
def position_loader(self, start : int, end : int):
return self.alpha_loader_v2(self, start, end)
def weight(self, start, end):
# how to make 7:3 weighted Portfolio
weight_df = super().weight(start, end)
weight_df["krx.krx.stock.ldh0127_qt.sample_univ_1"] *= (7/5)
weight_df["krx.krx.stock.soobeom33_qt.low_vol_factor_simple"] *= (3/5)
return weight_df
def get(self, start, end):
# Add a constraint that maintains a 20% cash allocation.
pf = super().get(start, end)
pf *= 0.8
return pf.fillna(0)
Initializing Portfolio and Fetching Data
The portfolio is initialized, and data for a specified period is fetched.
start, end = (20190929, 20201230)
self = Portfolio()
pf = self.get(start, end)
Simulation
Constraints of portfolio
from finter.backtest.simulator import Simulator
# Generating model statistics
sim = Simulator('kr_stock')
res = sim.run(pf)
# Result Table
res.summary
# PnL Graph
res.summary.nav.plot()
Last updated
Was this helpful?