Factor Analysis API¶
FactorDataLoader
¶
Fetch Fama-French factor data from Kenneth French Data Library.
Uses pandas-datareader to download factor data and provides local caching to avoid repeated downloads. Supports US and international regional factors.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cache_dir
|
str
|
Directory for caching factor data. If None, uses a temp directory. |
None
|
Examples:
>>> loader = FactorDataLoader()
>>> ff3 = loader.get_ff3_factors('2015-01-01', '2023-12-31')
>>> print(ff3.columns.tolist())
['Mkt-RF', 'SMB', 'HML', 'RF']
Source code in portfolio_analysis/factors/data.py
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 | |
get_available_regions()
classmethod
¶
Return list of supported region names.
Returns:
| Type | Description |
|---|---|
list of str
|
Supported region names for use with the |
Source code in portfolio_analysis/factors/data.py
get_ff3_factors(start_date, end_date, frequency='daily', region='us')
¶
Get Fama-French 3-factor data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
start_date
|
str or datetime
|
Start date for data |
required |
end_date
|
str or datetime
|
End date for data |
required |
frequency
|
str
|
Data frequency: 'daily' or 'monthly' |
'daily'
|
region
|
str
|
Geographic region for factor data. Use
|
'us'
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with columns: Mkt-RF, SMB, HML, RF |
Source code in portfolio_analysis/factors/data.py
get_ff5_factors(start_date, end_date, frequency='daily', region='us')
¶
Get Fama-French 5-factor data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
start_date
|
str or datetime
|
Start date for data |
required |
end_date
|
str or datetime
|
End date for data |
required |
frequency
|
str
|
Data frequency: 'daily' or 'monthly' |
'daily'
|
region
|
str
|
Geographic region for factor data. Use
|
'us'
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with columns: Mkt-RF, SMB, HML, RMW, CMA, RF |
Source code in portfolio_analysis/factors/data.py
get_momentum_factor(start_date, end_date, frequency='daily', region='us')
¶
Get momentum factor data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
start_date
|
str or datetime
|
Start date for data |
required |
end_date
|
str or datetime
|
End date for data |
required |
frequency
|
str
|
Data frequency: 'daily' or 'monthly' |
'daily'
|
region
|
str
|
Geographic region for factor data. Use
|
'us'
|
Returns:
| Type | Description |
|---|---|
Series
|
Momentum factor (MOM or WML) |
Source code in portfolio_analysis/factors/data.py
get_carhart_factors(start_date, end_date, frequency='daily', region='us')
¶
Get Carhart 4-factor data (FF3 + Momentum).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
start_date
|
str or datetime
|
Start date for data |
required |
end_date
|
str or datetime
|
End date for data |
required |
frequency
|
str
|
Data frequency: 'daily' or 'monthly' |
'daily'
|
region
|
str
|
Geographic region for factor data. Use
|
'us'
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with columns: Mkt-RF, SMB, HML, MOM, RF |
Source code in portfolio_analysis/factors/data.py
FactorModel
¶
Bases: Enum
Supported factor models.
Attributes:
| Name | Type | Description |
|---|---|---|
CAPM |
Single-factor market model
|
|
FF3 |
Fama-French 3-factor model (Mkt-RF, SMB, HML)
|
|
FF5 |
Fama-French 5-factor model (+ RMW, CMA)
|
|
CARHART |
Carhart 4-factor model (FF3 + MOM)
|
|
Source code in portfolio_analysis/factors/models.py
RegressionResults
dataclass
¶
Results from a factor regression.
Attributes:
| Name | Type | Description |
|---|---|---|
alpha |
float
|
Jensen's alpha (annualized intercept) |
alpha_pvalue |
float
|
P-value for alpha significance test |
betas |
dict
|
Factor loadings (sensitivities) |
beta_pvalues |
dict
|
P-values for each beta |
beta_tstats |
dict
|
T-statistics for each beta |
r_squared |
float
|
R-squared (explained variance) |
adj_r_squared |
float
|
Adjusted R-squared |
residual_std |
float
|
Standard deviation of residuals (annualized) |
n_observations |
int
|
Number of observations used |
model |
str
|
Model name used for regression |
factors |
list
|
Factor names used in the model |
Source code in portfolio_analysis/factors/models.py
summary()
¶
Generate a text summary of regression results.
Source code in portfolio_analysis/factors/models.py
FactorRegression
¶
Run factor regressions on portfolio or asset returns.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
returns
|
Series
|
Portfolio or asset returns with datetime index |
required |
factor_data
|
DataFrame
|
Factor data from FactorDataLoader |
required |
annualization_factor
|
int
|
Number of periods per year (252 for daily, 12 for monthly) |
252
|
Examples:
>>> from portfolio_analysis.factors import FactorDataLoader, FactorRegression
>>> factor_loader = FactorDataLoader()
>>> ff3 = factor_loader.get_ff3_factors('2015-01-01', '2023-12-31')
>>> regression = FactorRegression(portfolio_returns, ff3)
>>> results = regression.run_regression('ff3')
>>> print(results.summary())
Source code in portfolio_analysis/factors/models.py
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 | |
run_regression(model='ff3')
¶
Run a factor regression.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
str or FactorModel
|
Factor model to use: 'capm', 'ff3', 'ff5', or 'carhart' |
'ff3'
|
Returns:
| Type | Description |
|---|---|
RegressionResults
|
Regression results with alpha, betas, and statistics |
Source code in portfolio_analysis/factors/models.py
run_rolling_regression(model='ff3', window=60)
¶
Run rolling factor regressions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
str or FactorModel
|
Factor model to use |
'ff3'
|
window
|
int
|
Rolling window size (number of periods) |
60
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with rolling alpha and betas, indexed by date |
Source code in portfolio_analysis/factors/models.py
compare_models()
¶
Compare different factor models.
Returns:
| Type | Description |
|---|---|
DataFrame
|
Comparison table with alpha, R-squared, and key betas for each model |
Source code in portfolio_analysis/factors/models.py
FactorExposures
¶
Calculate characteristic-based factor exposures for a portfolio.
This class estimates factor tilts based on security characteristics (market cap, valuation ratios, momentum, etc.) rather than regression.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tickers
|
list of str
|
List of ticker symbols in the portfolio |
required |
weights
|
list of float
|
Portfolio weights for each ticker (must sum to 1.0) |
required |
Examples:
>>> exposures = FactorExposures(['VTI', 'VBR', 'VTV'], [0.5, 0.25, 0.25])
>>> tilts = exposures.get_all_tilts()
>>> print(f"Size tilt: {tilts['size']:.2f}")
>>> print(f"Value tilt: {tilts['value']:.2f}")
Source code in portfolio_analysis/factors/exposures.py
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 | |
calculate_size_tilt()
¶
Calculate portfolio size tilt (SMB exposure).
Returns:
| Type | Description |
|---|---|
float
|
Size tilt from -1 (large cap) to +1 (small cap) 0 indicates market-neutral size exposure |
Source code in portfolio_analysis/factors/exposures.py
calculate_value_tilt()
¶
Calculate portfolio value tilt (HML exposure).
Returns:
| Type | Description |
|---|---|
float
|
Value tilt from -1 (growth) to +1 (value) 0 indicates market-neutral value exposure |
Source code in portfolio_analysis/factors/exposures.py
calculate_momentum_tilt()
¶
Calculate portfolio momentum tilt (MOM exposure).
Returns:
| Type | Description |
|---|---|
float
|
Momentum tilt from -1 (low momentum) to +1 (high momentum) |
Source code in portfolio_analysis/factors/exposures.py
calculate_quality_tilt()
¶
Calculate portfolio quality tilt (RMW-like exposure).
Quality is based on profitability and financial health.
Returns:
| Type | Description |
|---|---|
float
|
Quality tilt from -1 (low quality) to +1 (high quality) |
Source code in portfolio_analysis/factors/exposures.py
calculate_investment_tilt()
¶
Calculate portfolio investment tilt (CMA-like exposure).
Conservative investment (low asset growth) vs aggressive.
Returns:
| Type | Description |
|---|---|
float
|
Investment tilt from -1 (aggressive) to +1 (conservative) |
Source code in portfolio_analysis/factors/exposures.py
get_all_tilts()
¶
Calculate all factor tilts for the portfolio.
Returns:
| Type | Description |
|---|---|
dict
|
Dictionary with all factor tilts: - size: SMB-like exposure - value: HML-like exposure - momentum: MOM-like exposure - quality: RMW-like exposure - investment: CMA-like exposure |
Source code in portfolio_analysis/factors/exposures.py
get_characteristics_table()
¶
Get a table of fundamental characteristics for all holdings.
Returns:
| Type | Description |
|---|---|
DataFrame
|
Characteristics for each holding with portfolio weight |
Source code in portfolio_analysis/factors/exposures.py
summary()
¶
Generate a text summary of factor exposures.
Source code in portfolio_analysis/factors/exposures.py
FactorAttribution
¶
Decompose portfolio returns and risk into factor contributions.
This class uses factor regression to attribute portfolio performance to systematic factors and idiosyncratic (alpha) components.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
returns
|
Series
|
Portfolio returns with datetime index |
required |
factor_data
|
DataFrame
|
Factor data from FactorDataLoader |
required |
annualization_factor
|
int
|
Number of periods per year (252 for daily, 12 for monthly) |
252
|
Examples:
>>> from portfolio_analysis.factors import FactorAttribution, FactorDataLoader
>>> factor_loader = FactorDataLoader()
>>> ff3 = factor_loader.get_ff3_factors('2015-01-01', '2023-12-31')
>>> attribution = FactorAttribution(portfolio_returns, ff3)
>>> decomp = attribution.decompose_returns()
>>> print(f"Market contribution: {decomp['Mkt-RF']:.2%}")
>>> print(f"Alpha: {decomp['alpha']:.2%}")
Source code in portfolio_analysis/factors/attribution.py
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 | |
decompose_returns(model='ff3')
¶
Decompose total returns into factor contributions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
str or FactorModel
|
Factor model to use for decomposition |
'ff3'
|
Returns:
| Type | Description |
|---|---|
dict
|
Dictionary with: - 'total': Total annualized return - 'risk_free': Risk-free contribution - One key per factor with its return contribution - 'alpha': Idiosyncratic return (Jensen's alpha) |
Source code in portfolio_analysis/factors/attribution.py
decompose_risk(model='ff3')
¶
Decompose portfolio variance into factor contributions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
str or FactorModel
|
Factor model to use for decomposition |
'ff3'
|
Returns:
| Type | Description |
|---|---|
dict
|
Dictionary with: - 'total': Total annualized variance - One key per factor with its variance contribution - 'idiosyncratic': Residual (unexplained) variance - 'r_squared': Fraction explained by factors |
Source code in portfolio_analysis/factors/attribution.py
get_rolling_attribution(model='ff3', window=60)
¶
Calculate rolling return attribution over time.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
str or FactorModel
|
Factor model to use |
'ff3'
|
window
|
int
|
Rolling window size (number of periods) |
60
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with rolling factor contributions, indexed by date |
Source code in portfolio_analysis/factors/attribution.py
get_attribution_summary(model='ff3')
¶
Get a summary table of return and risk attribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
str or FactorModel
|
Factor model to use |
'ff3'
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Summary table with return and risk contributions |
Source code in portfolio_analysis/factors/attribution.py
from_composite(composite_results, returns_dict, factor_data_dict)
classmethod
¶
Decompose composite portfolio returns into factor contributions.
Computes a weighted-average return attribution across all constituents, each using its own regional factor data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
composite_results
|
CompositeRegressionResults
|
Results from |
required |
returns_dict
|
dict[str, Series]
|
Per-ticker return series ({ticker: returns}). |
required |
factor_data_dict
|
dict[str, DataFrame]
|
Per-region factor data ({region: factor_df}). |
required |
Returns:
| Type | Description |
|---|---|
dict[str, float]
|
Decomposition with keys: total, risk_free, each factor name, alpha. |
Source code in portfolio_analysis/factors/attribution.py
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 | |
summary(model='ff3')
¶
Generate a text summary of factor attribution.
Source code in portfolio_analysis/factors/attribution.py
FactorOptimizer
¶
Factor-aware portfolio optimization.
Optimize portfolios to achieve target factor exposures, minimize factor exposure, or generate factor-efficient frontiers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
price_data
|
DataFrame
|
Historical price data with datetime index and tickers as columns |
required |
factor_data
|
DataFrame
|
Factor data from FactorDataLoader |
required |
risk_free_rate
|
float
|
Annual risk-free rate for Sharpe calculations |
0.02
|
Examples:
>>> from portfolio_analysis.factors import FactorOptimizer, FactorDataLoader
>>> factor_loader = FactorDataLoader()
>>> ff3 = factor_loader.get_ff3_factors('2015-01-01', '2023-12-31')
>>> optimizer = FactorOptimizer(price_data, ff3)
>>> result = optimizer.optimize_target_exposures(
... target_betas={'Mkt-RF': 1.0, 'SMB': 0.3, 'HML': 0.2}
... )
>>> print(result['weights'])
Source code in portfolio_analysis/factors/optimization.py
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 | |
optimize_target_exposures(target_betas, weight_bounds=(0, 1), tolerance=0.1)
¶
Optimize portfolio to achieve target factor exposures.
Minimizes tracking error to target betas while maximizing Sharpe ratio.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
target_betas
|
dict
|
Target factor exposures (e.g., {'Mkt-RF': 1.0, 'SMB': 0.3}) |
required |
weight_bounds
|
tuple
|
Min and max weight for each asset |
(0, 1)
|
tolerance
|
float
|
Allowed deviation from target betas |
0.1
|
Returns:
| Type | Description |
|---|---|
dict
|
Optimal weights, achieved betas, return, volatility, and Sharpe ratio |
Source code in portfolio_analysis/factors/optimization.py
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 | |
optimize_factor_neutral(factors, weight_bounds=(0, 1), tolerance=0.05)
¶
Optimize portfolio to be neutral to specified factors.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
factors
|
list of str
|
Factors to neutralize (e.g., ['SMB', 'HML']) |
required |
weight_bounds
|
tuple
|
Min and max weight for each asset |
(0, 1)
|
tolerance
|
float
|
Maximum allowed absolute beta for neutral factors |
0.05
|
Returns:
| Type | Description |
|---|---|
dict
|
Optimal weights with near-zero exposure to specified factors |
Source code in portfolio_analysis/factors/optimization.py
optimize_max_alpha(model='ff3', weight_bounds=(0, 1))
¶
Optimize portfolio to maximize expected alpha.
Uses pre-computed asset alphas to find the highest-alpha portfolio.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
str or FactorModel
|
Factor model for alpha calculation |
'ff3'
|
weight_bounds
|
tuple
|
Min and max weight for each asset |
(0, 1)
|
Returns:
| Type | Description |
|---|---|
dict
|
Portfolio weights maximizing expected alpha |
Source code in portfolio_analysis/factors/optimization.py
generate_factor_frontier(factor, n_points=20, weight_bounds=(0, 1))
¶
Generate efficient frontier varying one factor's exposure.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
factor
|
str
|
Factor to vary (e.g., 'SMB', 'HML') |
required |
n_points
|
int
|
Number of points on the frontier |
20
|
weight_bounds
|
tuple
|
Min and max weight for each asset |
(0, 1)
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Frontier with columns: factor_beta, return, volatility, sharpe_ratio |
Source code in portfolio_analysis/factors/optimization.py
get_asset_betas()
¶
Get factor betas for all individual assets.
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with assets as rows and factors as columns |
Source code in portfolio_analysis/factors/optimization.py
summary()
¶
Generate a summary of optimization capabilities and asset betas.
Source code in portfolio_analysis/factors/optimization.py
FactorVisualization
¶
Static methods for visualizing factor analysis results.
Examples:
>>> from portfolio_analysis.factors import FactorVisualization
>>> FactorVisualization.plot_factor_exposures(regression_results)
>>> FactorVisualization.plot_rolling_betas(rolling_data)
>>> FactorVisualization.plot_return_attribution(attribution_dict)
Source code in portfolio_analysis/factors/visualization.py
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 | |
plot_factor_exposures(results, figsize=(10, 6), show_significance=True)
staticmethod
¶
Plot factor exposures (betas) as a bar chart.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
results
|
RegressionResults
|
Results from FactorRegression |
required |
figsize
|
tuple
|
Figure size |
(10, 6)
|
show_significance
|
bool
|
Color bars by statistical significance |
True
|
Source code in portfolio_analysis/factors/visualization.py
plot_rolling_betas(rolling_data, figsize=(12, 8), factors=None)
staticmethod
¶
Plot rolling factor betas over time.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rolling_data
|
DataFrame
|
Output from FactorRegression.run_rolling_regression() |
required |
figsize
|
tuple
|
Figure size |
(12, 8)
|
factors
|
list of str
|
Specific factors to plot. If None, plots all. |
None
|
Source code in portfolio_analysis/factors/visualization.py
plot_return_attribution(attribution, figsize=(10, 6))
staticmethod
¶
Plot return attribution as a waterfall chart.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
attribution
|
dict
|
Output from FactorAttribution.decompose_returns() |
required |
figsize
|
tuple
|
Figure size |
(10, 6)
|
Source code in portfolio_analysis/factors/visualization.py
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 | |
plot_factor_tilts(tilts, figsize=(8, 8))
staticmethod
¶
Plot characteristic-based factor tilts as a radar chart.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tilts
|
dict
|
Output from FactorExposures.get_all_tilts() |
required |
figsize
|
tuple
|
Figure size |
(8, 8)
|
Source code in portfolio_analysis/factors/visualization.py
plot_model_comparison(comparison_df, figsize=(12, 5))
staticmethod
¶
Plot comparison of different factor models.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
comparison_df
|
DataFrame
|
Output from FactorRegression.compare_models() |
required |
figsize
|
tuple
|
Figure size |
(12, 5)
|
Source code in portfolio_analysis/factors/visualization.py
plot_factor_frontier(frontier_df, factor, figsize=(10, 6))
staticmethod
¶
Plot factor-efficient frontier.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
frontier_df
|
DataFrame
|
Output from FactorOptimizer.generate_factor_frontier() |
required |
factor
|
str
|
Name of the factor |
required |
figsize
|
tuple
|
Figure size |
(10, 6)
|
Source code in portfolio_analysis/factors/visualization.py
plot_risk_attribution(risk_decomp, figsize=(10, 6))
staticmethod
¶
Plot risk (variance) attribution as a stacked bar or pie chart.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
risk_decomp
|
dict
|
Output from FactorAttribution.decompose_risk() |
required |
figsize
|
tuple
|
Figure size |
(10, 6)
|
Source code in portfolio_analysis/factors/visualization.py
plot_regional_comparison(comparison_df, figsize=(14, 5))
staticmethod
¶
Plot side-by-side R² and alpha comparison of US vs regional factors.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
comparison_df
|
DataFrame
|
Output from |
required |
figsize
|
tuple
|
Figure size. |
(14, 5)
|
Source code in portfolio_analysis/factors/visualization.py
510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 | |
plot_composite_exposures(composite_results, baseline_results=None, figsize=(12, 6))
staticmethod
¶
Plot composite weighted-average factor betas, optionally vs a baseline.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
composite_results
|
CompositeRegressionResults
|
Output from |
required |
baseline_results
|
RegressionResults
|
Single-region baseline (e.g. US-only regression) for comparison. |
None
|
figsize
|
tuple
|
Figure size. |
(12, 6)
|
Source code in portfolio_analysis/factors/visualization.py
598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 | |