factorframe 0.1.1__tar.gz

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.
Files changed (32) hide show
  1. factorframe-0.1.1/LICENSE +21 -0
  2. factorframe-0.1.1/PKG-INFO +135 -0
  3. factorframe-0.1.1/README.md +108 -0
  4. factorframe-0.1.1/pyproject.toml +43 -0
  5. factorframe-0.1.1/src/factorframe/__init__.py +1 -0
  6. factorframe-0.1.1/src/factorframe/backtest/__init__.py +0 -0
  7. factorframe-0.1.1/src/factorframe/backtest/backtest.py +29 -0
  8. factorframe-0.1.1/src/factorframe/data_definitions/__init__.py +0 -0
  9. factorframe-0.1.1/src/factorframe/data_definitions/financials.py +87 -0
  10. factorframe-0.1.1/src/factorframe/data_definitions/prices.py +20 -0
  11. factorframe-0.1.1/src/factorframe/data_definitions/stocks.py +20 -0
  12. factorframe-0.1.1/src/factorframe/factor/__init__.py +0 -0
  13. factorframe-0.1.1/src/factorframe/factor/base_factor.py +32 -0
  14. factorframe-0.1.1/src/factorframe/factor/composite/__init__.py +0 -0
  15. factorframe-0.1.1/src/factorframe/factor/composite/composite_factor.py +17 -0
  16. factorframe-0.1.1/src/factorframe/factor/composite/corr_composite.py +72 -0
  17. factorframe-0.1.1/src/factorframe/factor/composite/mean_composite.py +30 -0
  18. factorframe-0.1.1/src/factorframe/factor/composite/regression_composite.py +80 -0
  19. factorframe-0.1.1/src/factorframe/factor/factor_schema.py +15 -0
  20. factorframe-0.1.1/src/factorframe/factor/single_factor.py +40 -0
  21. factorframe-0.1.1/src/factorframe/metric/__init__.py +0 -0
  22. factorframe-0.1.1/src/factorframe/metric/metric.py +155 -0
  23. factorframe-0.1.1/src/factorframe/portfolio/__init__.py +0 -0
  24. factorframe-0.1.1/src/factorframe/portfolio/allocation_type.py +14 -0
  25. factorframe-0.1.1/src/factorframe/portfolio/base_portfolio.py +41 -0
  26. factorframe-0.1.1/src/factorframe/portfolio/factor_portfolio.py +60 -0
  27. factorframe-0.1.1/src/factorframe/portfolio/weighting.py +47 -0
  28. factorframe-0.1.1/src/factorframe/stresstest/__init__.py +0 -0
  29. factorframe-0.1.1/src/factorframe/stresstest/base_stresstest.py +16 -0
  30. factorframe-0.1.1/src/factorframe/utils/__init__.py +0 -0
  31. factorframe-0.1.1/src/factorframe/utils/data_processor.py +166 -0
  32. factorframe-0.1.1/src/factorframe/utils/timeframe.py +12 -0
@@ -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.
@@ -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,108 @@
1
+ # factorframe
2
+
3
+ A small framework for equity factor research on pandas DataFrames: write a factor, turn its scores into
4
+ portfolio weights, backtest the weights on prices and measure the result. Every step checks its input
5
+ with a pandera schema, so a wrong column or type fails early with a clear message.
6
+
7
+ Status: early (0.x); the API can change between minor versions. MIT licence. Python 3.13+.
8
+
9
+ ## Install
10
+
11
+ ```bash
12
+ pip install factorframe
13
+ ```
14
+
15
+ From source: `pip install git+https://github.com/ejchungie/factorframe.git@v0.1.1`.
16
+
17
+ ## Quickstart
18
+
19
+ Runs as is on the package's dummy data:
20
+
21
+ ```python
22
+ from pandas import DataFrame
23
+
24
+ from factorframe.backtest.backtest import Backtest
25
+ from factorframe.data_definitions.financials import generate_financial_dummy_data
26
+ from factorframe.factor.single_factor import SingleFactor
27
+ from factorframe.metric.metric import Metrics
28
+ from factorframe.portfolio.allocation_type import AllocationType
29
+ from factorframe.portfolio.factor_portfolio import FactorPortfolio
30
+ from factorframe.portfolio.weighting import WeightingType
31
+ from factorframe.utils.timeframe import TimeFrame
32
+
33
+
34
+ class EquityToAssets(SingleFactor):
35
+ """Example factor: book equity as a share of total assets."""
36
+ name = "equity_to_assets"
37
+ timeframe = TimeFrame.QUARTER
38
+ factor_delay = 1 # a quarter's filing is used the next quarter
39
+ factor_memory = 1
40
+
41
+ def factor_calculations(self, data: DataFrame) -> DataFrame:
42
+ data["factor"] = data["total_equity"] / data["total_assets"]
43
+ return data.dropna(subset=["date"])[["date", "ticker", "factor"]]
44
+
45
+
46
+ financials = generate_financial_dummy_data(num_tickers=10, num_years=5)
47
+ factors = EquityToAssets().calculate(financials)
48
+ prices = financials[["date", "ticker", "price"]].assign(volume=1000)
49
+
50
+ portfolio = FactorPortfolio(TimeFrame.QUARTER, WeightingType.FACTOR, AllocationType.INDEXING)
51
+ result = Backtest(portfolio).execute(factors, prices)
52
+ print(Metrics(periods_per_year=4).calculate(result.dropna(subset=["weight"])))
53
+ # {'total_return': ..., 'annualized_volatility': ..., 'sharpe_ratio': ..., 'max_drawdown': ...}
54
+ ```
55
+
56
+ ## How it fits together
57
+
58
+ ```mermaid
59
+ flowchart LR
60
+ F["financials<br/>(FinancialsDataSchema)"] --> SF["SingleFactor.calculate"]
61
+ SF --> FS["factor rows<br/>date · ticker · factor"]
62
+ FS --> C["CompositeFactor<br/>(optional: combine factors)"]
63
+ FS --> P["FactorPortfolio.calculate<br/>weights per period"]
64
+ C --> P
65
+ P --> B["Backtest.execute<br/>weights joined onto daily prices"]
66
+ PR["prices<br/>(PriceDataSchema)"] --> B
67
+ B --> M["Metrics<br/>return · volatility · Sharpe · drawdown"]
68
+ ```
69
+
70
+ | Concept | Class | In | Out |
71
+ |---|---|---|---|
72
+ | Factor | `BaseFactor`, `SingleFactor` | financial rows (date, ticker, fields) | `FactorSchema`: date, ticker, factor |
73
+ | Composite | `MeanCompositeFactor`, `CorrCompositeFactor`, `RegressionCompositeFactor` | date, ticker, one column per factor (+ `return`) | date, ticker, factor |
74
+ | Portfolio | `FactorPortfolio(timeframe, weighting, allocation)` | factor rows | `PortfolioSchema`: date, ticker, weight |
75
+ | Backtest | `Backtest(portfolio).execute(factors, prices)` | factor rows, daily prices | price rows + weight |
76
+ | Metrics | `Metrics(risk_free_rate, periods_per_year)` | backtest output | total return, volatility, Sharpe, max drawdown |
77
+
78
+ Rules that hold everywhere:
79
+ - Dates are UTC timestamps at midnight (`DataProcessor.to_utc_date` makes them).
80
+ - Tickers match `^[A-Z0-9.-]+$`.
81
+ - A rebalance period is a calendar year plus the `TimeFrame` (week, month, quarter or year). Weights are
82
+ set once per period and apply to every price row in it.
83
+ - `factor_delay` shifts a value forward that many rows per ticker, so it is used only once it would
84
+ have been known. Set it from when the data is published, not when it is dated.
85
+
86
+ ## Extending it
87
+
88
+ - **A factor:** subclass `SingleFactor`; set `name`, `timeframe`, `factor_delay`, `factor_memory`;
89
+ write `factor_calculations(data)` returning date, ticker, factor. For data other than financial
90
+ statements, override the `dependency_schema` property with your own pandera schema.
91
+ - **A weighting:** write `fn(group_columns, data)` that adds a `weight` column summing to 1 per group,
92
+ and add a member to `WeightingType`.
93
+ - **Grouped weights (e.g. per sector):** add a `group` column to the factor rows and use
94
+ `AllocationType.PICKING`.
95
+ - **A composite:** subclass `CompositeFactor`; set `factor_delay` and `factor_memory`; write `calculate`.
96
+
97
+ ## Known limits
98
+
99
+ - `RegressionCompositeFactor` steps 4 dates at a time; `standardize` and `min_periods_buffer` are not used yet.
100
+ - `TimeFrame.DAY` has no calendar column, so it cannot be a rebalance period yet.
101
+ - `FactorPortfolio.calculate` prints a schema error and returns `None` instead of raising.
102
+ - 5 tests are marked `xfail` (composite and index-portfolio cases) until they are fixed.
103
+
104
+ ## More
105
+
106
+ - [CODEMAP.md](CODEMAP.md): every file and where to change what.
107
+ - [CHANGELOG.md](CHANGELOG.md): releases.
108
+ - Desk layer on top of this (strategies, paper broker, books): [eqdesk](https://github.com/ejchungie/eqdesk).
@@ -0,0 +1,43 @@
1
+ [project]
2
+ name = "factorframe"
3
+ version = "0.1.1"
4
+ description = "Equity factor research framework on pandas DataFrames."
5
+ license = "MIT"
6
+ readme = "README.md"
7
+ authors = [{name = "chung-ejy", email = "avocadoedevs@gmail.com"}]
8
+ keywords = ["finance", "factor investing", "quantitative finance", "backtesting", "pandas"]
9
+ classifiers = [
10
+ "Development Status :: 3 - Alpha",
11
+ "Intended Audience :: Financial and Insurance Industry",
12
+ "Intended Audience :: Science/Research",
13
+ "Programming Language :: Python :: 3",
14
+ "Programming Language :: Python :: 3.13",
15
+ "Topic :: Office/Business :: Financial :: Investment",
16
+ "Operating System :: OS Independent",
17
+ ]
18
+ requires-python = ">=3.13"
19
+ dependencies = [
20
+ "pandas>=3.0.3,<4.0.0",
21
+ "pandera>=0.32.1,<0.33.0",
22
+ "scikit-learn>=1.6.0,<1.7.0",
23
+ ]
24
+
25
+ [project.urls]
26
+ Homepage = "https://github.com/ejchungie/factorframe"
27
+ Repository = "https://github.com/ejchungie/factorframe"
28
+ Issues = "https://github.com/ejchungie/factorframe/issues"
29
+ Changelog = "https://github.com/ejchungie/factorframe/blob/main/CHANGELOG.md"
30
+
31
+ [tool.poetry]
32
+ packages = [{include = "factorframe", from = "src"}]
33
+
34
+ [build-system]
35
+ requires = ["poetry-core>=2.0.0,<3.0.0"]
36
+ build-backend = "poetry.core.masonry.api"
37
+
38
+ [dependency-groups]
39
+ dev = ["pytest>=9.1.1,<10.0.0"]
40
+
41
+ [tool.pytest.ini_options]
42
+ pythonpath = ["src"]
43
+ testpaths = ["tests"]
@@ -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
@@ -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
+ ...
@@ -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"]]