factorframe 0.1.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- factorframe/__init__.py +1 -0
- factorframe/backtest/__init__.py +0 -0
- factorframe/backtest/backtest.py +29 -0
- factorframe/data_definitions/__init__.py +0 -0
- factorframe/data_definitions/financials.py +87 -0
- factorframe/data_definitions/prices.py +20 -0
- factorframe/data_definitions/stocks.py +20 -0
- factorframe/factor/__init__.py +0 -0
- factorframe/factor/base_factor.py +32 -0
- factorframe/factor/composite/__init__.py +0 -0
- factorframe/factor/composite/composite_factor.py +17 -0
- factorframe/factor/composite/corr_composite.py +72 -0
- factorframe/factor/composite/mean_composite.py +30 -0
- factorframe/factor/composite/regression_composite.py +80 -0
- factorframe/factor/factor_schema.py +15 -0
- factorframe/factor/single_factor.py +40 -0
- factorframe/metric/__init__.py +0 -0
- factorframe/metric/metric.py +155 -0
- factorframe/portfolio/__init__.py +0 -0
- factorframe/portfolio/allocation_type.py +14 -0
- factorframe/portfolio/base_portfolio.py +41 -0
- factorframe/portfolio/factor_portfolio.py +60 -0
- factorframe/portfolio/weighting.py +47 -0
- factorframe/stresstest/__init__.py +0 -0
- factorframe/stresstest/base_stresstest.py +16 -0
- factorframe/utils/__init__.py +0 -0
- factorframe/utils/data_processor.py +166 -0
- factorframe/utils/timeframe.py +12 -0
- factorframe-0.1.1.dist-info/METADATA +135 -0
- factorframe-0.1.1.dist-info/RECORD +32 -0
- factorframe-0.1.1.dist-info/WHEEL +4 -0
- factorframe-0.1.1.dist-info/licenses/LICENSE +21 -0
factorframe/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Equity factor research framework on pandas DataFrames."""
|
|
File without changes
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""Backtest: give each daily price row the weight its portfolio set for that rebalance period."""
|
|
2
|
+
from pandas import DataFrame
|
|
3
|
+
from factorframe.utils.data_processor import DataProcessor as dp
|
|
4
|
+
from factorframe.portfolio.base_portfolio import BasePortfolio
|
|
5
|
+
from factorframe.data_definitions.prices import PriceDataSchema
|
|
6
|
+
from factorframe.factor.factor_schema import FactorSchema
|
|
7
|
+
|
|
8
|
+
class Backtest:
|
|
9
|
+
"""Runs a portfolio over price history.
|
|
10
|
+
|
|
11
|
+
Use: Backtest(portfolio).execute(factors, prices), then Metrics().calculate(result)."""
|
|
12
|
+
|
|
13
|
+
def __init__(self, portfolio: BasePortfolio):
|
|
14
|
+
self.portfolio = portfolio
|
|
15
|
+
|
|
16
|
+
def execute(self, data: DataFrame, prices:DataFrame) -> DataFrame:
|
|
17
|
+
"""Weights the portfolio picks for each period, joined onto every price row of that period.
|
|
18
|
+
|
|
19
|
+
data: factor rows (FactorSchema: date in UTC, ticker, factor).
|
|
20
|
+
prices: daily prices (PriceDataSchema: date in UTC, ticker, price, volume).
|
|
21
|
+
Returns the price rows with a `weight` column, joined on year + the portfolio's timeframe +
|
|
22
|
+
ticker; the weight is NaN where the ticker is not held that period."""
|
|
23
|
+
processed_data = FactorSchema.validate(data.sort_values("date"))
|
|
24
|
+
results = self.portfolio.calculate(processed_data)
|
|
25
|
+
processed_prices_data = PriceDataSchema.validate(prices.sort_values("date"))
|
|
26
|
+
results = dp.extract_calendar_horizons(results).drop("date",axis=1)
|
|
27
|
+
processed_prices_data = dp.extract_calendar_horizons(processed_prices_data)
|
|
28
|
+
results = dp.safe_merge(processed_prices_data,results,on=["year",self.portfolio.timeframe.value.lower(),"ticker"],how="left")
|
|
29
|
+
return results
|
|
File without changes
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""FinancialsDataSchema: financial-statement rows, one per date and ticker, that SingleFactor
|
|
2
|
+
validates by default; plus generate_financial_dummy_data for tests and examples."""
|
|
3
|
+
import random
|
|
4
|
+
import pandas as pd
|
|
5
|
+
import pandera.pandas as pa
|
|
6
|
+
import math
|
|
7
|
+
import string
|
|
8
|
+
FinancialsDataSchema = pa.DataFrameSchema(
|
|
9
|
+
columns={
|
|
10
|
+
"date": pa.Column(
|
|
11
|
+
pd.DatetimeTZDtype(tz="UTC"),
|
|
12
|
+
pa.Check.ge(pd.Timestamp("1980-01-01", tz="UTC")),
|
|
13
|
+
),
|
|
14
|
+
"ticker": pa.Column(pa.String, pa.Check.str_matches(r"^[A-Z0-9\.\-]+$")),
|
|
15
|
+
"total_equity": pa.Column(pa.Float, nullable=False),
|
|
16
|
+
"total_assets": pa.Column(pa.Float, nullable=False),
|
|
17
|
+
"total_liabilities": pa.Column(pa.Float, nullable=False),
|
|
18
|
+
# many companies never report gross profit or EPS; the factors that use them skip empty rows
|
|
19
|
+
"gross_profit": pa.Column(pa.Float, nullable=True),
|
|
20
|
+
"net_income": pa.Column(pa.Float, nullable=False),
|
|
21
|
+
"operating_cash_flow": pa.Column(pa.Float, nullable=False),
|
|
22
|
+
"market": pa.Column(pa.Float, nullable=False),
|
|
23
|
+
"earnings_per_share":pa.Column(pa.Float, nullable=True),
|
|
24
|
+
"price":pa.Column(pa.Float, nullable=False),
|
|
25
|
+
"volume":pa.Column(pa.Float, nullable=False)
|
|
26
|
+
},
|
|
27
|
+
unique_column_names=["date", "ticker"],
|
|
28
|
+
coerce=True,
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def generate_financial_dummy_data(
|
|
33
|
+
num_tickers: int = 10, num_years: int = 10
|
|
34
|
+
) -> pd.DataFrame:
|
|
35
|
+
"""Generates sequential dummy data matching constraints, filling every quarter start date sequentially from 1980."""
|
|
36
|
+
|
|
37
|
+
# 1. Generate unique random tickers
|
|
38
|
+
tickers = set()
|
|
39
|
+
while len(tickers) < num_tickers:
|
|
40
|
+
length = random.randint(3, 5)
|
|
41
|
+
ticker = "".join(random.choices(string.ascii_uppercase, k=length))
|
|
42
|
+
tickers.add(ticker)
|
|
43
|
+
tickers = list(tickers)
|
|
44
|
+
|
|
45
|
+
# 2. Dynamically calculate required quarters to hit exact row count
|
|
46
|
+
start_date = "1980-01-01"
|
|
47
|
+
end_year = 1980 + num_years
|
|
48
|
+
|
|
49
|
+
# Create the complete sequential date range
|
|
50
|
+
date_range = pd.date_range(
|
|
51
|
+
start=start_date, end=f"{end_year}-12-31", freq="QS", tz="UTC"
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
# 3. Build a complete grid of every ticker for every date
|
|
55
|
+
data = []
|
|
56
|
+
for date in date_range:
|
|
57
|
+
for ticker in tickers:
|
|
58
|
+
eps = round(random.uniform(-2.0, 12.0), 2)
|
|
59
|
+
net_income = round(random.uniform(10.0, 1500.0), 2)
|
|
60
|
+
equity = round(random.uniform(1000, 5000.0), 2)
|
|
61
|
+
assets = round(random.uniform(1000, 5000.0), 2)
|
|
62
|
+
liabilities = round(random.uniform(1000, 5000.0), 2)
|
|
63
|
+
operating_cash_flow = round(random.uniform(100, 500), 2)
|
|
64
|
+
market = round(random.uniform(100, 500), 2)
|
|
65
|
+
price = round(random.uniform(100, 500), 2)
|
|
66
|
+
volume = round(random.uniform(100, 500), 2)
|
|
67
|
+
gross_profit = round(random.uniform(100, 500), 2)
|
|
68
|
+
|
|
69
|
+
data.append(
|
|
70
|
+
{
|
|
71
|
+
"date": date,
|
|
72
|
+
"ticker": ticker,
|
|
73
|
+
"earnings_per_share": eps,
|
|
74
|
+
"total_equity": equity,
|
|
75
|
+
"total_assets": assets,
|
|
76
|
+
"total_liabilities": liabilities,
|
|
77
|
+
"gross_profit": gross_profit,
|
|
78
|
+
"net_income": net_income,
|
|
79
|
+
"operating_cash_flow": operating_cash_flow,
|
|
80
|
+
"market": market,
|
|
81
|
+
"price": price,
|
|
82
|
+
"volume": volume,
|
|
83
|
+
}
|
|
84
|
+
)
|
|
85
|
+
# Return a clean DataFrame sorted chronologically and alphabetically
|
|
86
|
+
df = pd.DataFrame(data)
|
|
87
|
+
return df.sort_values(by=["date", "ticker"]).reset_index(drop=True)
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"""PriceDataSchema: daily prices, one row per date and ticker (date in UTC, price > 0, volume >= 0)."""
|
|
2
|
+
import pandas as pd
|
|
3
|
+
import pandera.pandas as pa
|
|
4
|
+
from pandera.typing import Series
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
PriceDataSchema = pa.DataFrameSchema(
|
|
9
|
+
columns={
|
|
10
|
+
"date": pa.Column(
|
|
11
|
+
pd.DatetimeTZDtype(tz="UTC"),
|
|
12
|
+
pa.Check.ge(pd.Timestamp("1980-01-01", tz="UTC")),
|
|
13
|
+
),
|
|
14
|
+
"ticker": pa.Column(pa.String, pa.Check.str_matches(r"^[A-Z0-9\.\-]+$")),
|
|
15
|
+
"price": pa.Column(pa.Float, pa.Check.gt(0)),
|
|
16
|
+
"volume": pa.Column(pa.Int64, pa.Check.ge(0)),
|
|
17
|
+
},
|
|
18
|
+
unique_column_names=["date", "ticker"],
|
|
19
|
+
coerce=True,
|
|
20
|
+
)
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"""StockSchema: the stock list (company name, unique ticker, GICS sector, region)."""
|
|
2
|
+
import pandera.pandas as pa
|
|
3
|
+
|
|
4
|
+
StockSchema = pa.DataFrameSchema(
|
|
5
|
+
columns={
|
|
6
|
+
"company_name": pa.Column(
|
|
7
|
+
pa.String,
|
|
8
|
+
pa.Check.str_length(min_value=1)
|
|
9
|
+
),
|
|
10
|
+
"ticker": pa.Column(
|
|
11
|
+
pa.String,
|
|
12
|
+
pa.Check.str_matches(r"^[A-Z0-9\.\-]+$"),
|
|
13
|
+
nullable=False,
|
|
14
|
+
unique=True
|
|
15
|
+
),
|
|
16
|
+
"gics_sector": pa.Column(pa.String),
|
|
17
|
+
"region": pa.Column(pa.String),
|
|
18
|
+
},
|
|
19
|
+
coerce=True,
|
|
20
|
+
)
|
|
File without changes
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"""BaseFactor: the contract every factor meets (timeframe, delay, memory, calculate)."""
|
|
2
|
+
from abc import ABC, abstractmethod
|
|
3
|
+
from pandas import DataFrame
|
|
4
|
+
from factorframe.utils.timeframe import TimeFrame
|
|
5
|
+
|
|
6
|
+
class BaseFactor(ABC):
|
|
7
|
+
"""A factor scores each ticker on each date.
|
|
8
|
+
|
|
9
|
+
timeframe: the rebalance period the factor is built for.
|
|
10
|
+
factor_delay: rows per ticker a value waits before use, so it is only used once it would have
|
|
11
|
+
been known (e.g. a quarterly filing published a quarter later: delay 1).
|
|
12
|
+
factor_memory: how many past periods the calculation needs.
|
|
13
|
+
calculate(data) returns date, ticker, factor (FactorSchema)."""
|
|
14
|
+
|
|
15
|
+
@property
|
|
16
|
+
@abstractmethod
|
|
17
|
+
def timeframe(self) -> TimeFrame:
|
|
18
|
+
...
|
|
19
|
+
|
|
20
|
+
@property
|
|
21
|
+
@abstractmethod
|
|
22
|
+
def factor_delay(self) -> int:
|
|
23
|
+
...
|
|
24
|
+
|
|
25
|
+
@property
|
|
26
|
+
@abstractmethod
|
|
27
|
+
def factor_memory(self) -> int:
|
|
28
|
+
...
|
|
29
|
+
|
|
30
|
+
@abstractmethod
|
|
31
|
+
def calculate(self,data: DataFrame) -> DataFrame:
|
|
32
|
+
...
|
|
File without changes
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"""CompositeFactor: base class for a factor that combines several factor columns into one.
|
|
2
|
+
|
|
3
|
+
Input: date, ticker, one column per sub-factor and, for the correlation and regression
|
|
4
|
+
composites, a `return` column. Output: date, ticker, factor."""
|
|
5
|
+
from abc import ABC
|
|
6
|
+
from factorframe.factor.base_factor import BaseFactor
|
|
7
|
+
from factorframe.utils.timeframe import TimeFrame
|
|
8
|
+
|
|
9
|
+
class CompositeFactor(BaseFactor,ABC):
|
|
10
|
+
"""Holds the timeframe; subclasses set delay and memory and write calculate()."""
|
|
11
|
+
|
|
12
|
+
def __init__(self,timeframe:TimeFrame):
|
|
13
|
+
self._timeframe = timeframe
|
|
14
|
+
|
|
15
|
+
@property
|
|
16
|
+
def timeframe(self) -> TimeFrame:
|
|
17
|
+
return self._timeframe
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
"""CorrCompositeFactor: sub-factors weighted by their trailing correlation with `return`, then averaged."""
|
|
2
|
+
import pandas as pd
|
|
3
|
+
from pandas import DataFrame
|
|
4
|
+
from factorframe.utils.timeframe import TimeFrame
|
|
5
|
+
from factorframe.factor.composite.composite_factor import CompositeFactor
|
|
6
|
+
|
|
7
|
+
class CorrCompositeFactor(CompositeFactor):
|
|
8
|
+
"""For each date after the first factor_memory dates: each sub-factor is multiplied by its
|
|
9
|
+
correlation with `return` over the previous factor_memory dates, then the columns are averaged.
|
|
10
|
+
A correlation counts as 0 with fewer rows than tickers, zero variance, or |corr| < 0.0005."""
|
|
11
|
+
def __init__(self,timeframe: TimeFrame, delay:int, memory:int):
|
|
12
|
+
super().__init__(timeframe)
|
|
13
|
+
self._memory = memory
|
|
14
|
+
self._delay = delay
|
|
15
|
+
self._timeframe = timeframe
|
|
16
|
+
|
|
17
|
+
@property
|
|
18
|
+
def timeframe(self) -> TimeFrame:
|
|
19
|
+
return self._timeframe
|
|
20
|
+
|
|
21
|
+
@property
|
|
22
|
+
def factor_delay(self) -> int:
|
|
23
|
+
# The composite delay is constrained by the maximum sub-factor delay
|
|
24
|
+
return self._delay
|
|
25
|
+
|
|
26
|
+
@property
|
|
27
|
+
def factor_memory(self) -> int:
|
|
28
|
+
# The composite memory must cover the longest required sub-factor memory
|
|
29
|
+
return self._memory
|
|
30
|
+
|
|
31
|
+
def safe_corr(self,x, y, min_periods):
|
|
32
|
+
df = pd.concat([x, y], axis=1).dropna()
|
|
33
|
+
|
|
34
|
+
# Not enough observations
|
|
35
|
+
if len(df) < min_periods:
|
|
36
|
+
return 0.0
|
|
37
|
+
|
|
38
|
+
# Zero variance causes divide by zero
|
|
39
|
+
if df.iloc[:, 0].std() == 0 or df.iloc[:, 1].std() == 0:
|
|
40
|
+
return 0.0
|
|
41
|
+
|
|
42
|
+
corr = df.iloc[:, 0].corr(df.iloc[:, 1])
|
|
43
|
+
|
|
44
|
+
if pd.isna(corr):
|
|
45
|
+
return 0.0
|
|
46
|
+
|
|
47
|
+
# Remove weak signals
|
|
48
|
+
if abs(corr) < 0.0005:
|
|
49
|
+
return 0.0
|
|
50
|
+
return corr
|
|
51
|
+
|
|
52
|
+
def calculate(self, data: DataFrame) -> DataFrame:
|
|
53
|
+
unique_dates = list(data["date"].drop_duplicates().sort_values().reset_index(drop=True))
|
|
54
|
+
cols_to_drop = [col for col in ['ticker', 'date','return'] if col in data.columns]
|
|
55
|
+
results = []
|
|
56
|
+
for i in range(self.factor_memory,len(unique_dates)):
|
|
57
|
+
current_date = unique_dates[i]
|
|
58
|
+
min_date = unique_dates[i-self.factor_memory]
|
|
59
|
+
window = data[(data["date"] < current_date) & (data["date"] >= min_date)].copy()
|
|
60
|
+
current_row = data[(data["date"] == current_date)]
|
|
61
|
+
for col in window.columns:
|
|
62
|
+
if col not in cols_to_drop:
|
|
63
|
+
corr = self.safe_corr(
|
|
64
|
+
window[col],
|
|
65
|
+
window["return"],
|
|
66
|
+
min_periods=len(data["ticker"].unique())
|
|
67
|
+
)
|
|
68
|
+
current_row[col] = corr * current_row[col]
|
|
69
|
+
results.append(current_row)
|
|
70
|
+
final_data = pd.concat(results)
|
|
71
|
+
final_data["factor"] = final_data.drop(columns=cols_to_drop).mean(axis=1)
|
|
72
|
+
return final_data[["date","ticker","factor"]]
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""MeanCompositeFactor: the plain average of the sub-factor columns, row by row."""
|
|
2
|
+
import pandas as pd
|
|
3
|
+
from pandas import DataFrame
|
|
4
|
+
from factorframe.utils.timeframe import TimeFrame
|
|
5
|
+
from factorframe.factor.composite.composite_factor import CompositeFactor
|
|
6
|
+
|
|
7
|
+
class MeanCompositeFactor(CompositeFactor):
|
|
8
|
+
"""factor = mean of every column except date, ticker and return."""
|
|
9
|
+
def __init__(self, timeframe: TimeFrame, delay:int, memory:int):
|
|
10
|
+
super().__init__(timeframe)
|
|
11
|
+
self._memory = memory
|
|
12
|
+
self._delay = delay
|
|
13
|
+
self._timeframe = timeframe
|
|
14
|
+
|
|
15
|
+
@property
|
|
16
|
+
def timeframe(self) -> TimeFrame:
|
|
17
|
+
return self._timeframe
|
|
18
|
+
|
|
19
|
+
@property
|
|
20
|
+
def factor_delay(self) -> int:
|
|
21
|
+
return self._delay
|
|
22
|
+
|
|
23
|
+
@property
|
|
24
|
+
def factor_memory(self) -> int:
|
|
25
|
+
return self._memory
|
|
26
|
+
|
|
27
|
+
def calculate(self, data: DataFrame) -> DataFrame:
|
|
28
|
+
cols_to_drop = [col for col in ['ticker', 'date',"return"] if col in data.columns]
|
|
29
|
+
data["factor"] = data.drop(columns=cols_to_drop).mean(axis=1)
|
|
30
|
+
return data[["date","ticker","factor"]]
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""RegressionCompositeFactor: sub-factors combined by a rolling linear regression on `return`."""
|
|
2
|
+
import pandas as pd
|
|
3
|
+
from pandas import DataFrame
|
|
4
|
+
from sklearn.linear_model import LinearRegression
|
|
5
|
+
from sklearn.preprocessing import StandardScaler
|
|
6
|
+
|
|
7
|
+
from factorframe.utils.timeframe import TimeFrame
|
|
8
|
+
from factorframe.factor.composite.composite_factor import CompositeFactor
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class RegressionCompositeFactor(CompositeFactor):
|
|
12
|
+
"""
|
|
13
|
+
Composite factor that combines multiple sub-factors via a rolling
|
|
14
|
+
multifactor linear regression against `return`.
|
|
15
|
+
|
|
16
|
+
For each date, a LinearRegression model is fit on a trailing window
|
|
17
|
+
of `factor_memory` dates using all sub-factor columns as predictors
|
|
18
|
+
and `return` as the target. The fitted model is then used to score
|
|
19
|
+
every row on the current date, producing the "factor" output.
|
|
20
|
+
|
|
21
|
+
This is the multivariate analog of CorrCompositeFactor: instead of
|
|
22
|
+
weighting each sub-factor independently by its own correlation with
|
|
23
|
+
return, it jointly estimates coefficients across all sub-factors,
|
|
24
|
+
which naturally accounts for correlation/overlap between them.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
def __init__(
|
|
28
|
+
self,
|
|
29
|
+
timeframe: TimeFrame,
|
|
30
|
+
delay: int,
|
|
31
|
+
memory: int,
|
|
32
|
+
min_periods_buffer: int = 10,
|
|
33
|
+
standardize: bool = True,
|
|
34
|
+
fit_intercept: bool = True,
|
|
35
|
+
):
|
|
36
|
+
self._timeframe = timeframe
|
|
37
|
+
self._delay = delay
|
|
38
|
+
self._memory = memory
|
|
39
|
+
self._min_periods_buffer = min_periods_buffer
|
|
40
|
+
self._standardize = standardize
|
|
41
|
+
self._fit_intercept = fit_intercept
|
|
42
|
+
|
|
43
|
+
@property
|
|
44
|
+
def timeframe(self) -> TimeFrame:
|
|
45
|
+
return self._timeframe
|
|
46
|
+
|
|
47
|
+
@property
|
|
48
|
+
def factor_delay(self) -> int:
|
|
49
|
+
# The composite delay is constrained by the maximum sub-factor delay
|
|
50
|
+
return self._delay
|
|
51
|
+
|
|
52
|
+
@property
|
|
53
|
+
def factor_memory(self) -> int:
|
|
54
|
+
# The composite memory must cover the longest required sub-factor memory
|
|
55
|
+
return self._memory
|
|
56
|
+
|
|
57
|
+
def calculate(self, data: DataFrame) -> DataFrame:
|
|
58
|
+
"""Fits on the previous factor_memory dates and scores the next 4 dates, stepping 4 dates at a time.
|
|
59
|
+
|
|
60
|
+
Raises if a window or a scoring block is empty. standardize and min_periods_buffer are stored
|
|
61
|
+
but not used yet."""
|
|
62
|
+
unique_dates = list(data["date"].drop_duplicates().sort_values().reset_index(drop=True))
|
|
63
|
+
cols_to_drop = [col for col in ["ticker", "date", "return"] if col in data.columns]
|
|
64
|
+
feature_cols = [c for c in data.columns if c not in cols_to_drop]
|
|
65
|
+
results = []
|
|
66
|
+
for i in range(self.factor_memory,len(unique_dates)-4,4):
|
|
67
|
+
current_date = unique_dates[i]
|
|
68
|
+
max_date = unique_dates[i+4]
|
|
69
|
+
min_date = unique_dates[i-self.factor_memory]
|
|
70
|
+
window = data[(data["date"] < current_date) & (data["date"] >= min_date)]
|
|
71
|
+
current_rows = data[(data["date"] >= current_date) & (data["date"] < max_date)].copy().reset_index(drop=True)
|
|
72
|
+
if window.index.size > 0 and current_rows.index.size > 0:
|
|
73
|
+
model = LinearRegression(fit_intercept=self._fit_intercept)
|
|
74
|
+
model.fit(window[feature_cols], window["return"])
|
|
75
|
+
current_rows["factor"] = model.predict(current_rows[feature_cols])
|
|
76
|
+
results.append(current_rows[["date","ticker","factor"]])
|
|
77
|
+
else:
|
|
78
|
+
raise Exception("not enough rows")
|
|
79
|
+
|
|
80
|
+
return pd.concat(results, ignore_index=True)
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""FactorSchema: what every factor returns: date (UTC), ticker, factor (float, no NaN); no other
|
|
2
|
+
columns. Backtest validates its input against it."""
|
|
3
|
+
import pandera.pandas as pa
|
|
4
|
+
import pandas as pd
|
|
5
|
+
FactorSchema = pa.DataFrameSchema(
|
|
6
|
+
columns={
|
|
7
|
+
"date": (pa.Column(pd.DatetimeTZDtype(tz="UTC"),
|
|
8
|
+
pa.Check.ge(pd.Timestamp("1980-01-01", tz="UTC")),
|
|
9
|
+
)),
|
|
10
|
+
"ticker": pa.Column(pa.String),
|
|
11
|
+
"factor": pa.Column(pa.Float64, nullable=False),
|
|
12
|
+
},
|
|
13
|
+
coerce=True,
|
|
14
|
+
strict=True,
|
|
15
|
+
)
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"""SingleFactor: base class for a factor computed from one dataset (financial statements by default)."""
|
|
2
|
+
from abc import ABC, abstractmethod
|
|
3
|
+
from pandas import DataFrame
|
|
4
|
+
import pandera.pandas as pa
|
|
5
|
+
from factorframe.factor.base_factor import BaseFactor
|
|
6
|
+
from factorframe.data_definitions.financials import FinancialsDataSchema
|
|
7
|
+
class SingleFactor(BaseFactor,ABC):
|
|
8
|
+
"""Subclass it: set name, timeframe, factor_delay and factor_memory, and write factor_calculations.
|
|
9
|
+
|
|
10
|
+
calculate() validates the input against dependency_schema (FinancialsDataSchema unless
|
|
11
|
+
overridden), sorts by ticker and date, applies factor_shift, then calls factor_calculations."""
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@property
|
|
15
|
+
@abstractmethod
|
|
16
|
+
def name(self) -> str:
|
|
17
|
+
...
|
|
18
|
+
|
|
19
|
+
@property
|
|
20
|
+
def dependency_schema(self):
|
|
21
|
+
return FinancialsDataSchema
|
|
22
|
+
|
|
23
|
+
def validate(self, data: DataFrame) -> DataFrame:
|
|
24
|
+
return self.dependency_schema.validate(data)
|
|
25
|
+
|
|
26
|
+
def factor_shift(self,data:DataFrame) -> DataFrame:
|
|
27
|
+
"""Moves each row's date forward by factor_delay rows of the same ticker (the last rows get NaT)."""
|
|
28
|
+
data["date"] = data.groupby("ticker")["date"].shift(-self.factor_delay)
|
|
29
|
+
return data
|
|
30
|
+
|
|
31
|
+
def calculate(self,data: DataFrame) -> DataFrame:
|
|
32
|
+
data = self.dependency_schema.validate(data).copy().sort_values(["ticker", "date"])
|
|
33
|
+
data = self.factor_shift(data)
|
|
34
|
+
data = self.factor_calculations(data)
|
|
35
|
+
return data
|
|
36
|
+
|
|
37
|
+
@abstractmethod
|
|
38
|
+
def factor_calculations(self,data:DataFrame) -> DataFrame:
|
|
39
|
+
"""Your formula: take the shifted rows, return date, ticker, factor."""
|
|
40
|
+
...
|
|
File without changes
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
"""Metrics: performance of a backtest's output (date, ticker, price, weight): total return,
|
|
2
|
+
annualized volatility, Sharpe ratio, max drawdown; daily equity curve; per-ticker statistics."""
|
|
3
|
+
from datetime import date
|
|
4
|
+
from typing import TypedDict
|
|
5
|
+
import numpy as np
|
|
6
|
+
import pandas as pd
|
|
7
|
+
import pandera.pandas as pa
|
|
8
|
+
from pandera.typing import DataFrame, Series
|
|
9
|
+
from factorframe.utils.data_processor import DataProcessor
|
|
10
|
+
|
|
11
|
+
class MetricsInputSchema(pa.DataFrameModel):
|
|
12
|
+
"""Metrics' input: Backtest's output (extra columns allowed)."""
|
|
13
|
+
date: Series[pa.Date] = pa.Field(coerce=True)
|
|
14
|
+
ticker: Series[str] = pa.Field(coerce=True)
|
|
15
|
+
price: Series[float] = pa.Field(gt=0, coerce=True)
|
|
16
|
+
weight: Series[float] = pa.Field(coerce=True)
|
|
17
|
+
|
|
18
|
+
class Config:
|
|
19
|
+
strict = False
|
|
20
|
+
coerce = True
|
|
21
|
+
|
|
22
|
+
class MetricsResult(TypedDict):
|
|
23
|
+
total_return: float
|
|
24
|
+
annualized_volatility: float
|
|
25
|
+
sharpe_ratio: float
|
|
26
|
+
max_drawdown: float
|
|
27
|
+
|
|
28
|
+
class Metrics(object):
|
|
29
|
+
"""Portfolio statistics from daily prices and weights.
|
|
30
|
+
|
|
31
|
+
risk_free_rate: yearly rate for the Sharpe ratio. periods_per_year: 252 for daily rows."""
|
|
32
|
+
def __init__(self, risk_free_rate: float = 0.0, periods_per_year: int = 252):
|
|
33
|
+
self.risk_free_rate = risk_free_rate
|
|
34
|
+
self.periods_per_year = periods_per_year
|
|
35
|
+
|
|
36
|
+
@pa.check_types
|
|
37
|
+
def calculate(self, data: pd.DataFrame) -> MetricsResult:
|
|
38
|
+
"""Daily return = sum of weight x the ticker's price change; equity curve starts at 1.0.
|
|
39
|
+
|
|
40
|
+
Returns total_return, annualized_volatility, sharpe_ratio and max_drawdown (negative or 0)."""
|
|
41
|
+
# Step 1: Calculate daily asset returns safely
|
|
42
|
+
df = data.sort_values(["ticker", "date"]).copy()
|
|
43
|
+
df["asset_return"] = df.groupby("ticker")["price"].pct_change()
|
|
44
|
+
|
|
45
|
+
# Capture the full chronological timeline from your input data
|
|
46
|
+
all_dates = sorted(data["date"].unique())
|
|
47
|
+
if not all_dates:
|
|
48
|
+
return {"total_return": 0.0, "annualized_volatility": 0.0, "sharpe_ratio": 0.0, "max_drawdown": 0.0}
|
|
49
|
+
|
|
50
|
+
# Step 2: Compute weighted portfolio returns per day
|
|
51
|
+
df["weighted_return"] = df["asset_return"].fillna(0.0) * df["weight"]
|
|
52
|
+
daily_portfolio_returns = df.groupby("date")["weighted_return"].sum()
|
|
53
|
+
|
|
54
|
+
# Step 3: Reconstruct complete equity curve starting at 1.0 baseline
|
|
55
|
+
# We enforce 0.0 return on day 1 to act as the true investment anchor point
|
|
56
|
+
daily_portfolio_returns.loc[all_dates[0]] = 0.0
|
|
57
|
+
daily_portfolio_returns = daily_portfolio_returns.sort_index()
|
|
58
|
+
|
|
59
|
+
equity_curve = (1 + daily_portfolio_returns).cumprod()
|
|
60
|
+
total_return = equity_curve.iloc[-1] - 1.0
|
|
61
|
+
|
|
62
|
+
# Step 4: Annualized Volatility (exclude the padded day-one 0.0 row for clean variance)
|
|
63
|
+
active_returns = daily_portfolio_returns.iloc[1:]
|
|
64
|
+
daily_vol = active_returns.std() if len(active_returns) > 1 else 0.0
|
|
65
|
+
annualized_vol = daily_vol * np.sqrt(self.periods_per_year)
|
|
66
|
+
|
|
67
|
+
# Step 5: Sharpe Ratio
|
|
68
|
+
if daily_vol > 0:
|
|
69
|
+
daily_rf = self.risk_free_rate / self.periods_per_year
|
|
70
|
+
excess_returns = active_returns - daily_rf
|
|
71
|
+
sharpe_ratio = (excess_returns.mean() / daily_vol) * np.sqrt(self.periods_per_year)
|
|
72
|
+
else:
|
|
73
|
+
sharpe_ratio = 0.0
|
|
74
|
+
|
|
75
|
+
# Step 6: Maximum Drawdown
|
|
76
|
+
running_max = equity_curve.cummax()
|
|
77
|
+
drawdowns = (equity_curve - running_max) / running_max
|
|
78
|
+
max_drawdown = drawdowns.min()
|
|
79
|
+
|
|
80
|
+
return {
|
|
81
|
+
"total_return": float(total_return),
|
|
82
|
+
"annualized_volatility": float(annualized_vol),
|
|
83
|
+
"sharpe_ratio": float(sharpe_ratio),
|
|
84
|
+
"max_drawdown": float(max_drawdown),
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
def portfolio(self,data:pd.DataFrame) -> pd.DataFrame:
|
|
88
|
+
"""Daily rows: weighted_return and equity_curve (cumulative return, 0 = flat); the first date is dropped."""
|
|
89
|
+
df = data.sort_values(["ticker", "date"]).copy()
|
|
90
|
+
df["asset_return"] = df.groupby("ticker")["price"].pct_change()
|
|
91
|
+
|
|
92
|
+
# Step 2: Compute weighted portfolio returns per day
|
|
93
|
+
df["weighted_return"] = df["asset_return"].fillna(0.0) * df["weight"]
|
|
94
|
+
daily_df = df.groupby("date").agg({
|
|
95
|
+
"weighted_return":"sum"
|
|
96
|
+
}).reset_index()
|
|
97
|
+
daily_df = daily_df.sort_values("date").iloc[1:]
|
|
98
|
+
# Step 3: Reconstruct complete equity curve starting at 1.0 baseline
|
|
99
|
+
|
|
100
|
+
daily_df["equity_curve"] = (daily_df["weighted_return"] + 1).cumprod() - 1
|
|
101
|
+
return daily_df
|
|
102
|
+
|
|
103
|
+
def ticker_analysis(self, data: pd.DataFrame) -> pd.DataFrame:
|
|
104
|
+
"""
|
|
105
|
+
Analyzes and aggregates key historical statistics for each unique ticker,
|
|
106
|
+
returning a DataFrame indexed by ticker.
|
|
107
|
+
"""
|
|
108
|
+
# Step 1: Sort and calculate raw asset returns per ticker
|
|
109
|
+
df = data.sort_values(["ticker", "date"]).copy()
|
|
110
|
+
df["asset_return"] = df.groupby("ticker")["price"].pct_change()
|
|
111
|
+
|
|
112
|
+
analysis_records = []
|
|
113
|
+
|
|
114
|
+
# Step 2: Loop through each asset to compute historical metrics
|
|
115
|
+
for ticker in df["ticker"].unique():
|
|
116
|
+
ticker_history = df[df["ticker"] == ticker]
|
|
117
|
+
|
|
118
|
+
# Extract core arrays
|
|
119
|
+
prices = ticker_history["price"].values
|
|
120
|
+
returns = ticker_history["asset_return"].dropna().values
|
|
121
|
+
weights = ticker_history["weight"].values
|
|
122
|
+
|
|
123
|
+
if len(prices) == 0:
|
|
124
|
+
continue
|
|
125
|
+
|
|
126
|
+
# Calculate individual statistics
|
|
127
|
+
avg_return = float(np.mean(returns)) if len(returns) > 0 else 0.0
|
|
128
|
+
avg_weight = float(np.mean(weights)) if len(weights) > 0 else 0.0
|
|
129
|
+
|
|
130
|
+
# Annualized Volatility
|
|
131
|
+
daily_vol = float(np.std(returns, ddof=1)) if len(returns) > 1 else 0.0
|
|
132
|
+
volatility = daily_vol * np.sqrt(self.periods_per_year)
|
|
133
|
+
|
|
134
|
+
# Total Return (based on first and last available prices)
|
|
135
|
+
total_return = (prices[-1] / prices[0]) - 1.0 if prices[0] > 0 else 0.0
|
|
136
|
+
|
|
137
|
+
# Maximum Drawdown
|
|
138
|
+
running_max = np.maximum.accumulate(prices)
|
|
139
|
+
drawdowns = (prices - running_max) / running_max
|
|
140
|
+
max_drawdown = float(drawdowns.min()) if len(drawdowns) > 0 else 0.0
|
|
141
|
+
|
|
142
|
+
# Store stats in a dictionary
|
|
143
|
+
ticker_stats = {
|
|
144
|
+
"ticker": ticker,
|
|
145
|
+
"total_return": total_return,
|
|
146
|
+
"average_return": avg_return,
|
|
147
|
+
"volatility": volatility,
|
|
148
|
+
"max_drawdown": max_drawdown,
|
|
149
|
+
"average_weight": avg_weight
|
|
150
|
+
}
|
|
151
|
+
analysis_records.append(ticker_stats)
|
|
152
|
+
|
|
153
|
+
# Convert records into a final clean DataFrame
|
|
154
|
+
result_df = pd.DataFrame(analysis_records)
|
|
155
|
+
return result_df
|
|
File without changes
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"""AllocationType: which rows share one set of weights in a rebalance period.
|
|
2
|
+
|
|
3
|
+
INDEXING: all tickers together. PICKING: each value of a `group` column (e.g. a sector)
|
|
4
|
+
on its own, so weights sum to 1 within each group."""
|
|
5
|
+
from enum import Enum
|
|
6
|
+
|
|
7
|
+
class AllocationType(Enum):
|
|
8
|
+
"""Each member: a short name and the columns weights are grouped by (besides the period)."""
|
|
9
|
+
INDEXING=("index",["date"])
|
|
10
|
+
PICKING=("pick", ["date","group"])
|
|
11
|
+
|
|
12
|
+
def __init__(self,name_string,columns):
|
|
13
|
+
self.name_string = name_string
|
|
14
|
+
self.columns = columns
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"""BasePortfolio: the contract every portfolio meets; PortfolioSchema: its output (date, ticker, weight)."""
|
|
2
|
+
from abc import ABC, abstractmethod
|
|
3
|
+
from pandas import DataFrame
|
|
4
|
+
import pandera.pandas as pa
|
|
5
|
+
from pandera.typing import Series
|
|
6
|
+
from factorframe.utils.timeframe import TimeFrame
|
|
7
|
+
from factorframe.portfolio.weighting import WeightingType
|
|
8
|
+
from factorframe.portfolio.allocation_type import AllocationType
|
|
9
|
+
|
|
10
|
+
class PortfolioSchema(pa.DataFrameModel):
|
|
11
|
+
"""A portfolio's output: date, ticker, weight; no other columns."""
|
|
12
|
+
date: Series[pa.DateTime] = pa.Field()
|
|
13
|
+
ticker: Series[pa.String] = pa.Field()
|
|
14
|
+
weight: Series[pa.Float64] = pa.Field(nullable=False)
|
|
15
|
+
|
|
16
|
+
class Config:
|
|
17
|
+
coerce = True
|
|
18
|
+
strict = True
|
|
19
|
+
|
|
20
|
+
class BasePortfolio(ABC):
|
|
21
|
+
"""A portfolio turns factor rows into weights: timeframe (rebalance period), weighting, allocation,
|
|
22
|
+
and calculate(data) returning PortfolioSchema rows."""
|
|
23
|
+
|
|
24
|
+
@property
|
|
25
|
+
@abstractmethod
|
|
26
|
+
def timeframe(self) -> TimeFrame:
|
|
27
|
+
...
|
|
28
|
+
|
|
29
|
+
@property
|
|
30
|
+
@abstractmethod
|
|
31
|
+
def weighting(self) -> WeightingType:
|
|
32
|
+
...
|
|
33
|
+
|
|
34
|
+
@property
|
|
35
|
+
@abstractmethod
|
|
36
|
+
def allocation(self) -> AllocationType:
|
|
37
|
+
...
|
|
38
|
+
|
|
39
|
+
@abstractmethod
|
|
40
|
+
def calculate(self,data:DataFrame) -> DataFrame:
|
|
41
|
+
...
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"""FactorPortfolio: turns factor rows into portfolio weights per rebalance period."""
|
|
2
|
+
from abc import ABC, abstractmethod
|
|
3
|
+
from pandas import DataFrame
|
|
4
|
+
from factorframe.utils.data_processor import DataProcessor as dp
|
|
5
|
+
from factorframe.utils.timeframe import TimeFrame
|
|
6
|
+
from factorframe.portfolio.weighting import WeightingType
|
|
7
|
+
from factorframe.portfolio.base_portfolio import BasePortfolio, PortfolioSchema
|
|
8
|
+
from factorframe.portfolio.allocation_type import AllocationType
|
|
9
|
+
|
|
10
|
+
class FactorPortfolio(BasePortfolio):
|
|
11
|
+
"""
|
|
12
|
+
Weights factor rows: rows of one rebalance period (year + timeframe) and allocation group share
|
|
13
|
+
one set of weights, computed by the weighting.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
def __init__(
|
|
17
|
+
self,
|
|
18
|
+
timeframe: TimeFrame,
|
|
19
|
+
weighting: WeightingType,
|
|
20
|
+
allocation: AllocationType
|
|
21
|
+
) -> None:
|
|
22
|
+
self._timeframe = timeframe
|
|
23
|
+
self._weighting = weighting
|
|
24
|
+
self._allocation = allocation
|
|
25
|
+
|
|
26
|
+
@property
|
|
27
|
+
def timeframe(self) -> TimeFrame:
|
|
28
|
+
"""Returns the operational timeframe for the portfolio."""
|
|
29
|
+
return self._timeframe
|
|
30
|
+
|
|
31
|
+
@property
|
|
32
|
+
def weighting(self) -> WeightingType:
|
|
33
|
+
"""Returns the asset weighting strategy type used."""
|
|
34
|
+
return self._weighting
|
|
35
|
+
|
|
36
|
+
@property
|
|
37
|
+
def allocation(self) -> AllocationType:
|
|
38
|
+
"""Returns how rows are grouped for weighting (AllocationType)."""
|
|
39
|
+
return self._allocation
|
|
40
|
+
|
|
41
|
+
def _weight_groups(self) -> list:
|
|
42
|
+
"""A rebalance period: the same year + timeframe that Backtest joins on, not the exact date,
|
|
43
|
+
so a stock whose first trading day in the period is late is not weighted on its own."""
|
|
44
|
+
others = [col for col in self._allocation.columns if col != "date"]
|
|
45
|
+
return ["year", self._timeframe.value, *others]
|
|
46
|
+
|
|
47
|
+
def calculate(self, data:DataFrame) -> DataFrame:
|
|
48
|
+
"""Factor rows (date, ticker, factor [, group]) to weights per period and allocation group.
|
|
49
|
+
|
|
50
|
+
Returns PortfolioSchema rows. If the result fails the schema, prints the error and returns None."""
|
|
51
|
+
result = self.weighting.calculate(self._weight_groups(), dp.extract_calendar_horizons(data))
|
|
52
|
+
drops = [col for col in result.columns if col not in PortfolioSchema.to_schema().columns.keys()]
|
|
53
|
+
for drop in drops:
|
|
54
|
+
result.drop(drop,axis=1,inplace=True)
|
|
55
|
+
result.dropna(inplace=True)
|
|
56
|
+
try:
|
|
57
|
+
result = PortfolioSchema.validate(result)
|
|
58
|
+
return result
|
|
59
|
+
except Exception as e:
|
|
60
|
+
print(str(e))
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""Weighting functions and WeightingType, the enum that names them.
|
|
2
|
+
|
|
3
|
+
Each function takes (group columns, data) and returns data plus a `weight` column that sums
|
|
4
|
+
to 1 within each group. Add a weighting: write the function, add an enum member."""
|
|
5
|
+
from enum import Enum, unique
|
|
6
|
+
from typing import Callable
|
|
7
|
+
import pandas as pd
|
|
8
|
+
|
|
9
|
+
def equal_weighting(cols, data) -> pd.DataFrame:
|
|
10
|
+
"""Assigns equal weight to all rows within each cross-section. Total sum per group equals 1.0."""
|
|
11
|
+
if data.empty:
|
|
12
|
+
return data
|
|
13
|
+
|
|
14
|
+
df = data.copy()
|
|
15
|
+
# Group by the cross-section columns (e.g., 'date') and count assets to distribute weight evenly
|
|
16
|
+
df["weight"] = df.groupby(cols)["ticker"].transform(lambda x: 1 / len(x))
|
|
17
|
+
return df
|
|
18
|
+
|
|
19
|
+
## TODO switch to rank weighting in percentiles
|
|
20
|
+
def factor_weighting(cols, data) -> pd.DataFrame:
|
|
21
|
+
"""Assign long-only factor-proportional weights grouped by cross-section."""
|
|
22
|
+
if data.empty:
|
|
23
|
+
return data
|
|
24
|
+
|
|
25
|
+
df = data.copy()
|
|
26
|
+
|
|
27
|
+
df["factor_rank"] = (
|
|
28
|
+
df.groupby(cols)["factor"]
|
|
29
|
+
.rank(pct=True)
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
df["weight"] = (
|
|
33
|
+
df.groupby(cols)["factor_rank"]
|
|
34
|
+
.transform(lambda x: x / x.sum() if x.sum() != 0 else 0)
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
return df.drop(columns=["factor_rank"])
|
|
38
|
+
|
|
39
|
+
@unique
|
|
40
|
+
class WeightingType(Enum):
|
|
41
|
+
"""EQUAL: 1/n per ticker. FACTOR: proportional to the factor's percentile rank (long only)."""
|
|
42
|
+
EQUAL = ("equal", equal_weighting)
|
|
43
|
+
FACTOR = ("factor", factor_weighting)
|
|
44
|
+
|
|
45
|
+
def __init__(self, key: str, calculate: Callable):
|
|
46
|
+
self.key = key
|
|
47
|
+
self.calculate = calculate
|
|
File without changes
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"""BaseStressTest: the contract for running a portfolio through a stress scenario (no implementation yet)."""
|
|
2
|
+
from abc import ABC, abstractmethod
|
|
3
|
+
from factorframe.portfolio.base_portfolio import BasePortfolio
|
|
4
|
+
from pandas import DataFrame
|
|
5
|
+
|
|
6
|
+
class BaseStressTest(ABC):
|
|
7
|
+
"""Holds a portfolio; execute(data) returns the scenario's results."""
|
|
8
|
+
|
|
9
|
+
@property
|
|
10
|
+
@abstractmethod
|
|
11
|
+
def portfolio(self) -> BasePortfolio:
|
|
12
|
+
...
|
|
13
|
+
|
|
14
|
+
@abstractmethod
|
|
15
|
+
def execute(self,data:DataFrame) -> DataFrame:
|
|
16
|
+
...
|
|
File without changes
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
"""DataProcessor: date helpers (UTC days, calendar columns) and a merge that cannot multiply rows."""
|
|
2
|
+
from typing import List, Literal, Optional
|
|
3
|
+
import pandas as pd
|
|
4
|
+
from datetime import datetime, timedelta, timezone
|
|
5
|
+
|
|
6
|
+
class DataProcessor:
|
|
7
|
+
"""
|
|
8
|
+
A utility engine for standardizing timelines, extracting calendar horizons,
|
|
9
|
+
and executing safe alignment mergers across financial data tracking sets.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
@staticmethod
|
|
13
|
+
def last_market_date() -> datetime.date:
|
|
14
|
+
"""Today's UTC date, moved back to Friday on weekends (holidays are not handled)."""
|
|
15
|
+
date = datetime.now(timezone.utc).date()
|
|
16
|
+
|
|
17
|
+
while date.weekday() >= 5:
|
|
18
|
+
date -= timedelta(days=1)
|
|
19
|
+
|
|
20
|
+
return date
|
|
21
|
+
|
|
22
|
+
@staticmethod
|
|
23
|
+
def to_utc_date(df: pd.DataFrame, date_column: str = "date") -> pd.DataFrame:
|
|
24
|
+
"""Parses the date column to UTC timestamps at midnight; returns a copy."""
|
|
25
|
+
if date_column not in df.columns:
|
|
26
|
+
raise ValueError(f"Target column '{date_column}' not found in DataFrame.")
|
|
27
|
+
|
|
28
|
+
result = df.copy()
|
|
29
|
+
# Using dt.floor("D") strips the clock elements (HMS) while safely keeping the UTC timezone metadata
|
|
30
|
+
result[date_column] = pd.to_datetime(result[date_column], utc=True).dt.floor("D")
|
|
31
|
+
return result
|
|
32
|
+
|
|
33
|
+
@staticmethod
|
|
34
|
+
def extract_calendar_horizons(df: pd.DataFrame, date_column: str = "date") -> pd.DataFrame:
|
|
35
|
+
"""
|
|
36
|
+
Extracts categorical period codes (Week, Month, Quarter, Year) from a date column.
|
|
37
|
+
Useful for building dynamic multi-timeframe backtest rebalancing loops.
|
|
38
|
+
"""
|
|
39
|
+
if date_column not in df.columns:
|
|
40
|
+
raise ValueError(f"Target column '{date_column}' not found in DataFrame.")
|
|
41
|
+
|
|
42
|
+
result = df.copy()
|
|
43
|
+
# Ensure working column format is a recognized pandas timestamp structure
|
|
44
|
+
timestamps = pd.to_datetime(result[date_column])
|
|
45
|
+
|
|
46
|
+
# Extract period intervals using standardized financial tracking frequencies
|
|
47
|
+
# Extract native integers instead of string periods
|
|
48
|
+
result["week"] = timestamps.dt.isocalendar().week.astype(int)
|
|
49
|
+
result["month"] = timestamps.dt.month.astype(int)
|
|
50
|
+
result["quarter"] = timestamps.dt.quarter.astype(int)
|
|
51
|
+
result["year"] = timestamps.dt.year.astype(int)
|
|
52
|
+
|
|
53
|
+
return result
|
|
54
|
+
|
|
55
|
+
@staticmethod
|
|
56
|
+
def safe_merge(
|
|
57
|
+
left_df: pd.DataFrame,
|
|
58
|
+
right_df: pd.DataFrame,
|
|
59
|
+
on: List[str],
|
|
60
|
+
how: Literal["left", "right", "inner", "outer"] = "left"
|
|
61
|
+
) -> pd.DataFrame:
|
|
62
|
+
"""
|
|
63
|
+
Executes an assertive merge operation across two matrix horizons using a high-performance
|
|
64
|
+
sorted MultiIndex join.
|
|
65
|
+
|
|
66
|
+
Guarantees that merging data sets won't cause row explosion (e.g., unintended cartesian products).
|
|
67
|
+
If duplicate columns (outside of the join keys) exist, only the columns from the left_df are preserved.
|
|
68
|
+
"""
|
|
69
|
+
# 1. Defensive boundary checks to confirm target join parameters exist
|
|
70
|
+
for col in on:
|
|
71
|
+
if col not in left_df.columns:
|
|
72
|
+
raise KeyError(f"Merge column '{col}' is missing from the left DataFrame.")
|
|
73
|
+
if col not in right_df.columns:
|
|
74
|
+
raise KeyError(f"Merge column '{col}' is missing from the right DataFrame.")
|
|
75
|
+
|
|
76
|
+
# 2. Drop duplicate columns from right_df on-the-fly to keep only left_df's versions
|
|
77
|
+
duplicate_cols = [
|
|
78
|
+
col for col in right_df.columns
|
|
79
|
+
if col in left_df.columns and col not in on
|
|
80
|
+
]
|
|
81
|
+
right_df_filtered = (
|
|
82
|
+
right_df.drop(columns=duplicate_cols)
|
|
83
|
+
if duplicate_cols else right_df
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
# 3. High-Performance Index-Based Join
|
|
87
|
+
# Setting and sorting the MultiIndex avoids expensive hash table generations
|
|
88
|
+
left_indexed = left_df.set_index(on).sort_index()
|
|
89
|
+
right_indexed = right_df_filtered.set_index(on).sort_index()
|
|
90
|
+
|
|
91
|
+
# Join on the index and restore the join keys back to columns
|
|
92
|
+
return left_indexed.join(right_indexed, how=how).reset_index()
|
|
93
|
+
|
|
94
|
+
@staticmethod
|
|
95
|
+
def choose_merge_timeframe(
|
|
96
|
+
left_df: pd.DataFrame,
|
|
97
|
+
right_df: pd.DataFrame,
|
|
98
|
+
date_column: str = "date",
|
|
99
|
+
wiggle_room: float = 0.20,
|
|
100
|
+
) -> tuple[str, list[str]]:
|
|
101
|
+
"""
|
|
102
|
+
Select a merge timeframe based on observed records per year.
|
|
103
|
+
|
|
104
|
+
Starts at week and allows wiggle_room around expected annual
|
|
105
|
+
observation counts to accommodate missing trading days or records.
|
|
106
|
+
|
|
107
|
+
Returns
|
|
108
|
+
-------
|
|
109
|
+
tuple[str, list[str]]
|
|
110
|
+
Selected timeframe and its merge keys.
|
|
111
|
+
"""
|
|
112
|
+
timeframe_map = {
|
|
113
|
+
"year": 1,
|
|
114
|
+
"quarter": 4,
|
|
115
|
+
"month": 12,
|
|
116
|
+
"week": 52,
|
|
117
|
+
"date": 252,
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
left = DataProcessor.extract_calendar_horizons(
|
|
121
|
+
left_df, date_column
|
|
122
|
+
)
|
|
123
|
+
right = DataProcessor.extract_calendar_horizons(
|
|
124
|
+
right_df, date_column
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
# Estimate annual observation frequency for each DataFrame.
|
|
128
|
+
def observations_per_year(df: pd.DataFrame) -> float:
|
|
129
|
+
if df.empty:
|
|
130
|
+
return 0.0
|
|
131
|
+
|
|
132
|
+
years = df["year"].nunique()
|
|
133
|
+
return len(df) / max(years, 1)
|
|
134
|
+
|
|
135
|
+
left_frequency = observations_per_year(left)
|
|
136
|
+
right_frequency = observations_per_year(right)
|
|
137
|
+
|
|
138
|
+
# Use the less frequent dataset to determine the shared granularity.
|
|
139
|
+
frequency = min(left_frequency, right_frequency)
|
|
140
|
+
|
|
141
|
+
# Test from weekly to daily, then fall back to coarser intervals.
|
|
142
|
+
candidates = ["week", "date", "month", "quarter", "year"]
|
|
143
|
+
|
|
144
|
+
selected = "year"
|
|
145
|
+
|
|
146
|
+
for timeframe in candidates:
|
|
147
|
+
expected = timeframe_map[timeframe]
|
|
148
|
+
lower = expected * (1 - wiggle_room)
|
|
149
|
+
upper = expected * (1 + wiggle_room)
|
|
150
|
+
|
|
151
|
+
if lower <= frequency <= upper:
|
|
152
|
+
selected = timeframe
|
|
153
|
+
break
|
|
154
|
+
|
|
155
|
+
if selected == "week":
|
|
156
|
+
keys = ["year", "week", "ticker"]
|
|
157
|
+
elif selected == "date":
|
|
158
|
+
keys = ["date", "ticker"]
|
|
159
|
+
elif selected == "month":
|
|
160
|
+
keys = ["year", "month", "ticker"]
|
|
161
|
+
elif selected == "quarter":
|
|
162
|
+
keys = ["year", "quarter", "ticker"]
|
|
163
|
+
else:
|
|
164
|
+
keys = ["year", "ticker"]
|
|
165
|
+
|
|
166
|
+
return selected, keys
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"""TimeFrame: the rebalance period. Its value is also the calendar column Backtest and FactorPortfolio
|
|
2
|
+
group by (week, month, quarter, year, from DataProcessor.extract_calendar_horizons); DAY has no such
|
|
3
|
+
column yet."""
|
|
4
|
+
from enum import Enum
|
|
5
|
+
|
|
6
|
+
class TimeFrame(Enum):
|
|
7
|
+
|
|
8
|
+
DAY = "day"
|
|
9
|
+
WEEK = "week"
|
|
10
|
+
MONTH = "month"
|
|
11
|
+
QUARTER = "quarter"
|
|
12
|
+
YEAR = "year"
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: factorframe
|
|
3
|
+
Version: 0.1.1
|
|
4
|
+
Summary: Equity factor research framework on pandas DataFrames.
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
License-File: LICENSE
|
|
7
|
+
Keywords: finance,factor investing,quantitative finance,backtesting,pandas
|
|
8
|
+
Author: chung-ejy
|
|
9
|
+
Author-email: avocadoedevs@gmail.com
|
|
10
|
+
Requires-Python: >=3.13
|
|
11
|
+
Classifier: Development Status :: 3 - Alpha
|
|
12
|
+
Classifier: Intended Audience :: Financial and Insurance Industry
|
|
13
|
+
Classifier: Intended Audience :: Science/Research
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
16
|
+
Classifier: Topic :: Office/Business :: Financial :: Investment
|
|
17
|
+
Classifier: Operating System :: OS Independent
|
|
18
|
+
Requires-Dist: pandas (>=3.0.3,<4.0.0)
|
|
19
|
+
Requires-Dist: pandera (>=0.32.1,<0.33.0)
|
|
20
|
+
Requires-Dist: scikit-learn (>=1.6.0,<1.7.0)
|
|
21
|
+
Project-URL: Changelog, https://github.com/ejchungie/factorframe/blob/main/CHANGELOG.md
|
|
22
|
+
Project-URL: Homepage, https://github.com/ejchungie/factorframe
|
|
23
|
+
Project-URL: Issues, https://github.com/ejchungie/factorframe/issues
|
|
24
|
+
Project-URL: Repository, https://github.com/ejchungie/factorframe
|
|
25
|
+
Description-Content-Type: text/markdown
|
|
26
|
+
|
|
27
|
+
# factorframe
|
|
28
|
+
|
|
29
|
+
A small framework for equity factor research on pandas DataFrames: write a factor, turn its scores into
|
|
30
|
+
portfolio weights, backtest the weights on prices and measure the result. Every step checks its input
|
|
31
|
+
with a pandera schema, so a wrong column or type fails early with a clear message.
|
|
32
|
+
|
|
33
|
+
Status: early (0.x); the API can change between minor versions. MIT licence. Python 3.13+.
|
|
34
|
+
|
|
35
|
+
## Install
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
pip install factorframe
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
From source: `pip install git+https://github.com/ejchungie/factorframe.git@v0.1.1`.
|
|
42
|
+
|
|
43
|
+
## Quickstart
|
|
44
|
+
|
|
45
|
+
Runs as is on the package's dummy data:
|
|
46
|
+
|
|
47
|
+
```python
|
|
48
|
+
from pandas import DataFrame
|
|
49
|
+
|
|
50
|
+
from factorframe.backtest.backtest import Backtest
|
|
51
|
+
from factorframe.data_definitions.financials import generate_financial_dummy_data
|
|
52
|
+
from factorframe.factor.single_factor import SingleFactor
|
|
53
|
+
from factorframe.metric.metric import Metrics
|
|
54
|
+
from factorframe.portfolio.allocation_type import AllocationType
|
|
55
|
+
from factorframe.portfolio.factor_portfolio import FactorPortfolio
|
|
56
|
+
from factorframe.portfolio.weighting import WeightingType
|
|
57
|
+
from factorframe.utils.timeframe import TimeFrame
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class EquityToAssets(SingleFactor):
|
|
61
|
+
"""Example factor: book equity as a share of total assets."""
|
|
62
|
+
name = "equity_to_assets"
|
|
63
|
+
timeframe = TimeFrame.QUARTER
|
|
64
|
+
factor_delay = 1 # a quarter's filing is used the next quarter
|
|
65
|
+
factor_memory = 1
|
|
66
|
+
|
|
67
|
+
def factor_calculations(self, data: DataFrame) -> DataFrame:
|
|
68
|
+
data["factor"] = data["total_equity"] / data["total_assets"]
|
|
69
|
+
return data.dropna(subset=["date"])[["date", "ticker", "factor"]]
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
financials = generate_financial_dummy_data(num_tickers=10, num_years=5)
|
|
73
|
+
factors = EquityToAssets().calculate(financials)
|
|
74
|
+
prices = financials[["date", "ticker", "price"]].assign(volume=1000)
|
|
75
|
+
|
|
76
|
+
portfolio = FactorPortfolio(TimeFrame.QUARTER, WeightingType.FACTOR, AllocationType.INDEXING)
|
|
77
|
+
result = Backtest(portfolio).execute(factors, prices)
|
|
78
|
+
print(Metrics(periods_per_year=4).calculate(result.dropna(subset=["weight"])))
|
|
79
|
+
# {'total_return': ..., 'annualized_volatility': ..., 'sharpe_ratio': ..., 'max_drawdown': ...}
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
## How it fits together
|
|
83
|
+
|
|
84
|
+
```mermaid
|
|
85
|
+
flowchart LR
|
|
86
|
+
F["financials<br/>(FinancialsDataSchema)"] --> SF["SingleFactor.calculate"]
|
|
87
|
+
SF --> FS["factor rows<br/>date · ticker · factor"]
|
|
88
|
+
FS --> C["CompositeFactor<br/>(optional: combine factors)"]
|
|
89
|
+
FS --> P["FactorPortfolio.calculate<br/>weights per period"]
|
|
90
|
+
C --> P
|
|
91
|
+
P --> B["Backtest.execute<br/>weights joined onto daily prices"]
|
|
92
|
+
PR["prices<br/>(PriceDataSchema)"] --> B
|
|
93
|
+
B --> M["Metrics<br/>return · volatility · Sharpe · drawdown"]
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
| Concept | Class | In | Out |
|
|
97
|
+
|---|---|---|---|
|
|
98
|
+
| Factor | `BaseFactor`, `SingleFactor` | financial rows (date, ticker, fields) | `FactorSchema`: date, ticker, factor |
|
|
99
|
+
| Composite | `MeanCompositeFactor`, `CorrCompositeFactor`, `RegressionCompositeFactor` | date, ticker, one column per factor (+ `return`) | date, ticker, factor |
|
|
100
|
+
| Portfolio | `FactorPortfolio(timeframe, weighting, allocation)` | factor rows | `PortfolioSchema`: date, ticker, weight |
|
|
101
|
+
| Backtest | `Backtest(portfolio).execute(factors, prices)` | factor rows, daily prices | price rows + weight |
|
|
102
|
+
| Metrics | `Metrics(risk_free_rate, periods_per_year)` | backtest output | total return, volatility, Sharpe, max drawdown |
|
|
103
|
+
|
|
104
|
+
Rules that hold everywhere:
|
|
105
|
+
- Dates are UTC timestamps at midnight (`DataProcessor.to_utc_date` makes them).
|
|
106
|
+
- Tickers match `^[A-Z0-9.-]+$`.
|
|
107
|
+
- A rebalance period is a calendar year plus the `TimeFrame` (week, month, quarter or year). Weights are
|
|
108
|
+
set once per period and apply to every price row in it.
|
|
109
|
+
- `factor_delay` shifts a value forward that many rows per ticker, so it is used only once it would
|
|
110
|
+
have been known. Set it from when the data is published, not when it is dated.
|
|
111
|
+
|
|
112
|
+
## Extending it
|
|
113
|
+
|
|
114
|
+
- **A factor:** subclass `SingleFactor`; set `name`, `timeframe`, `factor_delay`, `factor_memory`;
|
|
115
|
+
write `factor_calculations(data)` returning date, ticker, factor. For data other than financial
|
|
116
|
+
statements, override the `dependency_schema` property with your own pandera schema.
|
|
117
|
+
- **A weighting:** write `fn(group_columns, data)` that adds a `weight` column summing to 1 per group,
|
|
118
|
+
and add a member to `WeightingType`.
|
|
119
|
+
- **Grouped weights (e.g. per sector):** add a `group` column to the factor rows and use
|
|
120
|
+
`AllocationType.PICKING`.
|
|
121
|
+
- **A composite:** subclass `CompositeFactor`; set `factor_delay` and `factor_memory`; write `calculate`.
|
|
122
|
+
|
|
123
|
+
## Known limits
|
|
124
|
+
|
|
125
|
+
- `RegressionCompositeFactor` steps 4 dates at a time; `standardize` and `min_periods_buffer` are not used yet.
|
|
126
|
+
- `TimeFrame.DAY` has no calendar column, so it cannot be a rebalance period yet.
|
|
127
|
+
- `FactorPortfolio.calculate` prints a schema error and returns `None` instead of raising.
|
|
128
|
+
- 5 tests are marked `xfail` (composite and index-portfolio cases) until they are fixed.
|
|
129
|
+
|
|
130
|
+
## More
|
|
131
|
+
|
|
132
|
+
- [CODEMAP.md](CODEMAP.md): every file and where to change what.
|
|
133
|
+
- [CHANGELOG.md](CHANGELOG.md): releases.
|
|
134
|
+
- Desk layer on top of this (strategies, paper broker, books): [eqdesk](https://github.com/ejchungie/eqdesk).
|
|
135
|
+
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
factorframe/__init__.py,sha256=TMXtyyyNqNVgYa1tSbcLB_hBY48d_mHZl72g0HqutKQ,61
|
|
2
|
+
factorframe/backtest/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
3
|
+
factorframe/backtest/backtest.py,sha256=vOJeQbxCmAW2iCB3px5wwCUzgaqGavKBGlLf-2i-93g,1662
|
|
4
|
+
factorframe/data_definitions/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
5
|
+
factorframe/data_definitions/financials.py,sha256=f-JyxI-pjQIzRvfVVHmwFpWDTPzJAZDs9jcGFa2hf2k,3626
|
|
6
|
+
factorframe/data_definitions/prices.py,sha256=PT7KKWOLYCbnHdb2h485APr2mcUjlHNQVfgeWFNgVwg,644
|
|
7
|
+
factorframe/data_definitions/stocks.py,sha256=DfZ0RLVnd_JUwmTBbQj7PSXYEpXUodZQ9QQAY1st-60,561
|
|
8
|
+
factorframe/factor/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
9
|
+
factorframe/factor/base_factor.py,sha256=Ol5fF5yEc4Z1qgqiwlXIrj0p2SCy1pkgo-GiKtsZVGs,998
|
|
10
|
+
factorframe/factor/composite/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
11
|
+
factorframe/factor/composite/composite_factor.py,sha256=NV5atBQsXx21ApoPZNBq-8jsGpZyJmGiRoUvT5B3PMg,661
|
|
12
|
+
factorframe/factor/composite/corr_composite.py,sha256=KDANckZkZWjgQPOr2og38jsPd2Qw1hMbrczJbP7AdjI,2902
|
|
13
|
+
factorframe/factor/composite/mean_composite.py,sha256=8AQGWf3LEIPpNPeLBtczv02vC9uexW8bM9b8iTJjJf8,1078
|
|
14
|
+
factorframe/factor/composite/regression_composite.py,sha256=wODupiMZim2j1NGdLAT5tdTm0XHvLx_TDIRjG0_edlk,3460
|
|
15
|
+
factorframe/factor/factor_schema.py,sha256=WQsOYWf9KvSz2xxfstXi2VJ0zC8hE20_Nl9OjREgSMw,534
|
|
16
|
+
factorframe/factor/single_factor.py,sha256=rVgof5-mB48qwiDGQVBkc5FnIy7nWyNY-g8oWOdxc7k,1637
|
|
17
|
+
factorframe/metric/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
18
|
+
factorframe/metric/metric.py,sha256=oLJqAOVwY2nvUwQ3BS0CBsfgz_iNnPlm3mnqOI8PcQU,6763
|
|
19
|
+
factorframe/portfolio/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
20
|
+
factorframe/portfolio/allocation_type.py,sha256=J9qQy-8EG5ENYKo4Mleu-1opEs5teR3KGTYMGzsj-7E,558
|
|
21
|
+
factorframe/portfolio/base_portfolio.py,sha256=5wSiuy2nBwSFRdnti2fMZYtzVDBAS97OkepnZiOL3PY,1287
|
|
22
|
+
factorframe/portfolio/factor_portfolio.py,sha256=s7nT9pCl_McfxmojyzB7wp8xdMFW5U6jwwF6jpsScKw,2525
|
|
23
|
+
factorframe/portfolio/weighting.py,sha256=Paz2E4oGisn-LSWKVNOA9nUFV2yT0S0S00SbrOTXxxc,1579
|
|
24
|
+
factorframe/stresstest/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
25
|
+
factorframe/stresstest/base_stresstest.py,sha256=yS5CkijUcZ-6owtGhxeu6Ed9KNK6bl82-BHQLOreb_M,513
|
|
26
|
+
factorframe/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
27
|
+
factorframe/utils/data_processor.py,sha256=YebcvRuITrqKobR2MsHN6OQEbQwtvZ-UoyG4Lu9cD3k,6342
|
|
28
|
+
factorframe/utils/timeframe.py,sha256=9-m9Jr-ZYxLEeP8XKkMAF2OXUmKSpG3rRSTCbJVQwOY,362
|
|
29
|
+
factorframe-0.1.1.dist-info/METADATA,sha256=DRxwoLlZCxEV57yU3NW9cXITSBY398BxO4427vt_wVw,6207
|
|
30
|
+
factorframe-0.1.1.dist-info/WHEEL,sha256=L-WvLdSBvJWHXv5zrQxDvNRnIgoBzLUpcbuiw19KCuQ,88
|
|
31
|
+
factorframe-0.1.1.dist-info/licenses/LICENSE,sha256=H6IiOwuZl0ziCWKmfAggFB44CrZxdaqG_1-X1mgwK9Q,1075
|
|
32
|
+
factorframe-0.1.1.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Eric Ji Yong Chung
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|