Multiregression beta

import pandas as pd
from qcs import AllocationSnapshot, Context

currency = "EUR"
positions = [
    {"ticker": "EQUITYEUR68", "size": 10.0},
    {"ticker": "EQUITYEUR70", "size": 200.0},
]

benchmark_snapshot = AllocationSnapshot(currency=currency, positions=positions)
snapshot = AllocationSnapshot(
    currency=currency, positions=positions, benchmark=benchmark_snapshot
)

factors_all = ["<EQUITYEUR68>", "GBP", "CHF", "USD", "DKK", "KRW"]

assets = [
    {
        "code": "<EQUITYEUR68>",
        "label": "Equity EUR n. 68",
        "type": "EQT",
        "currency": "EUR",
        "alias1": "EQUITYEUR68",
        "formula": "RTHST([CODE],[LABEL],[CURRENCY],[HISTORY],'116',[OTHER])",
        "country": "USA",
        "sector": "Materials",
        "history": "EQUITYEUR68",
    },
    {
        "code": "<EQUITYEUR70>",
        "label": "Equity EUR n. 70",
        "type": "EQT",
        "currency": "EUR",
        "alias1": "EQUITYEUR70",
        "formula": "RTHST([CODE],[LABEL],[CURRENCY],[HISTORY],'116',[OTHER])",
        "country": "USA",
        "sector": "Information Technology",
        "history": "EQUITYEUR70",
    },
]

histories = [
    {
        "code": "EQUITYEUR68",
        "label": "EQUITYEUR68",
        "currency": "EUR",
        "time_series": [
            {"date": "2021-09-27", "value": 800.1},
            {"date": "2021-09-28", "value": 802.1},
            {"date": "2021-09-29", "value": 780.56},
        ],
    },
    {
        "code": "EQUITYEUR70",
        "label": "EQUITYEUR70",
        "currency": "EUR",
        "time_series": [
            {"date": "2021-09-27", "value": 45.26},
            {"date": "2021-09-28", "value": 48.22},
            {"date": "2021-09-29", "value": 47.11},
        ],
    },
]

context = Context(
    date="2023-10-19",
    horizon="1d",
    local_db={"assets": assets, "histories": histories},
)

# Find top factors
top_factors, r2, trace = snapshot.top_factors(
    context,
    factors=factors_all,
    max_size=10,
    replication_method="enhanced_stepwise",
    epsilon=0.01,
    trace=True,
)

print("top_factors:", top_factors)
print("r2:", r2)
print("trace:", trace)

# add top factors asset and update context
assets.append(
    {
        "code": "#TOP_FACTORS",
        "label": "top_factors",
        "formula": f"RTLIST([CODE],[LABEL],'{';'.join(top_factors)}')",
    },
)
context = Context(
    date="2023-10-19",
    horizon="1d",
    local_db={"assets": assets, "histories": histories},
)

pivot_fields = ["sector", "ticker"]
fields = ["MAV", "\\\\div(STD,MAV)", "REG[T='#TOP_FACTORS']"]

pivot_view = snapshot.pivot_view(context, pivot_fields)
df_risks = pivot_view.get_risks(fields)

print("\nFull table:")
print(df_risks)

print("\nMultiregression beta:")
df_multiregression_beta = df_risks["REG[T='#TOP_FACTORS']"].apply(
    lambda x: pd.Series(x)
)
df_multiregression_beta.columns = [*top_factors, "R^2", "regression constant"]
print(df_multiregression_beta)