techtonique_apis

 1from .techtonique_apis import TechtoniqueAPI
 2from .techto_forecast import techto_forecast
 3from .techto_ml import techto_mlclassification, techto_mlregression
 4from .techto_reserving import techto_reserving, techto_mlreserving
 5from .techto_simulation import techto_simulation
 6from .techto_survival import techto_survival
 7
 8__all__ = ["TechtoniqueAPI",
 9           "techto_forecast",
10           "techto_mlclassification",
11           "techto_mlregression",
12           "techto_reserving",
13           "techto_mlreserving",
14           "techto_simulation",
15           "techto_survival"]
class TechtoniqueAPI:
 12class TechtoniqueAPI:
 13
 14    def __init__(self):
 15        self.token = get_token()
 16        self.BASE_URL = BASE_URL
 17        self.headers = {
 18            "Authorization": f"Bearer {self.token}"
 19        }
 20
 21    def _post_file(
 22        self,
 23        endpoint: str,
 24        file_path: str,
 25        params: Optional[Dict[str, Any]] = None,
 26    ) -> Dict[str, Any]:
 27        """Send a POST request with a file upload."""
 28        url = f"{self.BASE_URL}{endpoint}"
 29        with open(file_path, "rb") as f:
 30            files = {"file": (file_path, f, "text/csv")}
 31            response = requests.post(url, headers=self.headers,
 32                                     files=files, params=params)
 33        response.raise_for_status()
 34        return response.json()
 35
 36    def _get(
 37        self,
 38        endpoint: str,
 39        params: Optional[Dict[str, Any]] = None,
 40    ) -> Dict[str, Any]:
 41        """Send a GET request."""
 42        url = f"{self.BASE_URL}{endpoint}"
 43        headers = self.headers.copy()
 44        headers["accept"] = "application/json"
 45        response = requests.get(url, headers=headers, params=params)
 46        response.raise_for_status()
 47        return response.json()
 48
 49    # 1 - Forecasting -----
 50
 51    def forecasting(
 52        self,
 53        file_path: str,
 54        base_model: str = "RidgeCV",
 55        n_hidden_features: int = 5,
 56        lags: int = 25,
 57        type_pi: str = "kde",
 58        replications: int = 10,
 59        h: int = 5,
 60    ) -> Dict[str, Any]:
 61        params = {
 62            "base_model": base_model,
 63            "n_hidden_features": n_hidden_features,
 64            "lags": lags,
 65            "type_pi": type_pi,
 66            "replications": replications,
 67            "h": h,
 68        }
 69        return self._post_file("/forecasting", file_path, params)
 70
 71    # 2 - Machine Learning  -----
 72
 73    def mlclassification(
 74        self,
 75        file_path: str,
 76        base_model: str = "RandomForestClassifier",
 77        n_hidden_features: int = 5,
 78        predict_proba: bool = False,
 79    ) -> Dict[str, Any]:
 80        params = {
 81            "base_model": base_model,
 82            "n_hidden_features": n_hidden_features,
 83            "predict_proba": str(predict_proba).lower(),
 84        }
 85        return self._post_file("/mlclassification", file_path, params)
 86
 87    def mlregression(
 88        self,
 89        file_path: str,
 90        base_model: str = "ElasticNet",
 91        n_hidden_features: int = 5,
 92        return_pi: bool = True,  # default True as in example
 93    ) -> Dict[str, Any]:
 94        params = {
 95            "base_model": base_model,
 96            "n_hidden_features": n_hidden_features,
 97            "return_pi": str(return_pi).lower(),
 98        }
 99        return self._post_file("/mlregression", file_path, params)
100
101    def gbdt_regression(
102        self,
103        file_path: str,
104        model_type: str = "lightgbm",
105        return_pi: bool = False,
106    ) -> Dict[str, Any]:
107        params = {
108            "model_type": model_type,
109            "return_pi": str(return_pi).lower(),
110        }
111        return self._post_file("/gbdtregression", file_path, params)
112
113    def gbdt_classification(
114        self,
115        file_path: str,
116        model_type: str = "lightgbm",
117    ) -> Dict[str, Any]:
118        params = {
119            "model_type": model_type,
120        }
121        return self._post_file("/gbdtclassification", file_path, params)
122
123    # 3 - Reserving -----
124
125    def reserving(
126        self,
127        file_path: str,
128        method: str = "chainladder",  # default as in example
129    ) -> Dict[str, Any]:
130        params = {"method": method}
131        return self._post_file("/reserving", file_path, params)
132
133    def mlreserving(
134        self,
135        file_path: str,
136        method: str = "RidgeCV",
137    ) -> Dict[str, Any]:
138        params = {"method": method}
139        return self._post_file("/mlreserving", file_path, params)
140
141    # 4 - Survival Analysis -----
142
143    def survival_curve(
144        self,
145        file_path: str,
146        method: str = "km",  # default as in example
147        patient_id: Optional[int] = None,
148    ) -> Dict[str, Any]:
149        params = {"method": method}
150        if patient_id is not None:
151            params["patient_id"] = patient_id
152        return self._post_file("/survivalcurve", file_path, params)
153
154    # 5 - Simulation -----
155
156    def simulate_scenario(
157        self,
158        model: str = "GBM",  # default as in example
159        n: int = 10,
160        horizon: int = 5,
161        frequency: str = "quarterly",
162        x0: Optional[Union[int, float]] = 1.0,  # required for GBM, default 1.0
163        theta1: Optional[float] = 0.0,
164        theta2: Optional[float] = 0.5,
165        theta3: Optional[float] = None,
166        seed: Optional[int] = None,
167    ) -> Dict[str, Any]:
168        params = {
169            "model": model,
170            "n": n,
171            "horizon": horizon,
172            "frequency": frequency,
173        }
174        if x0 is not None:
175            params["x0"] = x0
176        if theta1 is not None:
177            params["theta1"] = theta1
178        if theta2 is not None:
179            params["theta2"] = theta2
180        if theta3 is not None:
181            params["theta3"] = theta3
182        if seed is not None:
183            params["seed"] = seed
184        return self._get("/scenarios/simulate/", params)
@func
@arg('df', index=False, doc="Excel range with columns 'date' and one or more series.")
@arg('base_model', doc='Forecasting model (default: "RidgeCV")')
@arg('n_hidden_features', doc='Number of hidden features (default: 5)')
@arg('lags', doc='Number of lags (default: 25)')
@arg('type_pi', doc='Prediction interval type (default: "kde")')
@arg('replications', doc='Number of simulation replications (default: 10)')
@arg('h', doc='Forecast horizon (default: 5)')
@arg('return_sims', doc='If TRUE, return simulation matrix; else, return forecast summary (default: FALSE)')
@arg('series_choice', doc='(Optional) Name of the series to forecast if multiple are present')
@ret(index=False, doc='Forecast or simulation results as a table for Excel')
def techto_forecast( df: pandas.core.frame.DataFrame, base_model: str = 'RidgeCV', n_hidden_features: int = 5, lags: int = 25, type_pi: str = 'kde', replications: int = 10, h: int = 5, return_sims: bool = False, series_choice: str = None) -> pandas.core.frame.DataFrame:
 19@func
 20@arg("df", index=False, doc="Excel range with columns 'date' and one or more series.")
 21@arg("base_model", doc='Forecasting model (default: "RidgeCV")')
 22@arg("n_hidden_features", doc="Number of hidden features (default: 5)")
 23@arg("lags", doc="Number of lags (default: 25)")
 24@arg("type_pi", doc='Prediction interval type (default: "kde")')
 25@arg("replications", doc="Number of simulation replications (default: 10)")
 26@arg("h", doc="Forecast horizon (default: 5)")
 27@arg("return_sims", doc="If TRUE, return simulation matrix; else, return forecast summary (default: FALSE)")
 28@arg("series_choice", doc="(Optional) Name of the series to forecast if multiple are present")
 29@ret(index=False, doc="Forecast or simulation results as a table for Excel")
 30def techto_forecast(
 31    df: pd.DataFrame,
 32    base_model: str = "RidgeCV",
 33    n_hidden_features: int = 5,
 34    lags: int = 25,
 35    type_pi: str = "kde",
 36    replications: int = 10,
 37    h: int = 5,
 38    return_sims: bool = False,
 39    series_choice: str = None
 40) -> pd.DataFrame:
 41    """Forecasting: pass a time series as a DataFrame from Excel, return forecast.
 42
 43    Excel/xlwings custom function: Forecast a time series passed as a DataFrame from Excel, using the Techtonique API.
 44
 45    Parameters
 46    ----------
 47
 48    df : pd.DataFrame
 49        The input time series data as a DataFrame (from Excel range).
 50
 51    base_model : str, default "RidgeCV"
 52        The base model to use for forecasting.
 53
 54    n_hidden_features : int, default 5
 55        Number of hidden features for the model.
 56
 57    lags : int, default 25
 58        Number of lags to use in the model.
 59
 60    type_pi : str, default "kde"
 61        Type of prediction interval ("kde" or other supported types).
 62
 63    replications : int, default 10
 64        Number of simulation replications.
 65
 66    h : int, default 5
 67        Forecast horizon (number of periods ahead to forecast).
 68
 69    return_sims : bool, default False
 70        If True, return the simulation matrix; otherwise, return the forecast summary bounds.
 71
 72    series_choice : str, optional
 73        If provided, specifies which series to forecast from the DataFrame.
 74
 75    Returns
 76    -------
 77
 78    pd.DataFrame
 79        The forecast results or simulation matrix as a DataFrame for Excel.
 80
 81    """
 82    # Convert Excel serial dates to datetime if needed
 83    if pd.api.types.is_numeric_dtype(df['date']):
 84        df['date'] = df['date'].apply(excel_date_to_datetime)
 85
 86    with tempfile.NamedTemporaryFile(suffix=".csv", delete=False) as tmp:
 87        df.to_csv(tmp.name, index=False)
 88        result = api.forecasting(
 89            file_path=tmp.name,
 90            base_model=base_model,
 91            n_hidden_features=n_hidden_features,
 92            lags=lags,
 93            type_pi=type_pi,
 94            replications=replications,
 95            h=h,
 96        )
 97    output_dates = result["date"]
 98    if df.shape[1] == 2:  # univariate time series
 99        res_df = pd.DataFrame(result.pop('sims'))
100        if return_sims:
101            res2_df = pd.DataFrame([])
102            res2_df["date"] = output_dates
103            sims_df = res_df.transpose()
104            sims_df.columns = [(i + 1) for i in range(sims_df.shape[1])]
105            return pd.concat([res2_df, sims_df], axis=1)
106        return pd.DataFrame(result)
107    else:  # multivariate time series
108        n_series = len(result["mean"][0])
109        series_names = [col for col in df.columns if col != "date"]
110        if len(series_names) != n_series:
111            series_names = [f"series_{i+1}" for i in range(n_series)]
112
113        # If series_choice is provided and valid, extract its index and return as univariate
114        if series_choice is not None and series_choice in series_names:
115            idx = series_names.index(series_choice)
116            # Extract only the selected series from each stat
117            summary_df = pd.DataFrame({
118                "date": output_dates,
119                "mean": [x[idx] for x in result["mean"]],
120                "lower": [x[idx] for x in result["lower"]],
121                "upper": [x[idx] for x in result["upper"]],
122            })
123            if return_sims:
124                # sims: shape (replications, horizon, n_series)
125                # list of replications, each is list of horizon, each is list of n_series
126                sims = result["sims"]
127                # For each replication, extract the selected series only
128                sims_selected = [[h[idx] for h in rep]
129                                 for rep in sims]  # shape: (replications, horizon)
130                sims_df = pd.DataFrame(sims_selected).transpose()
131                sims_df.columns = [
132                    f"sim_{i+1}_{series_choice}" for i in range(sims_df.shape[1])]
133                res2_df = pd.DataFrame({"date": output_dates})
134                return pd.concat([res2_df, sims_df], axis=1)
135            return summary_df
136
137        # Otherwise, return the full multivariate summary as before
138        summary_data = {"date": output_dates}
139        for stat in ["mean", "lower", "upper"]:
140            for s in range(n_series):
141                summary_data[f"{stat}_{series_names[s]}"] = [x[s]
142                                                             for x in result[stat]]
143        summary_df = pd.DataFrame(summary_data)
144        if return_sims:
145            # sims: shape (replications, horizon, n_series)
146            sims = result["sims"]
147            flat = []
148            for rep in sims:
149                for s in range(n_series):
150                    flat.append([h[s] for h in rep])
151            sims_df = pd.DataFrame(flat).transpose()
152            colnames = []
153            for r in range(len(sims)):
154                for s in range(n_series):
155                    colnames.append(f"sim_{r+1}_{series_names[s]}")
156            sims_df.columns = colnames
157            sims_df.insert(0, "date", output_dates)
158            return sims_df
159        return summary_df

Forecasting: pass a time series as a DataFrame from Excel, return forecast.

Excel/xlwings custom function: Forecast a time series passed as a DataFrame from Excel, using the Techtonique API.

Parameters

df : pd.DataFrame The input time series data as a DataFrame (from Excel range).

base_model : str, default "RidgeCV" The base model to use for forecasting.

n_hidden_features : int, default 5 Number of hidden features for the model.

lags : int, default 25 Number of lags to use in the model.

type_pi : str, default "kde" Type of prediction interval ("kde" or other supported types).

replications : int, default 10 Number of simulation replications.

h : int, default 5 Forecast horizon (number of periods ahead to forecast).

return_sims : bool, default False If True, return the simulation matrix; otherwise, return the forecast summary bounds.

series_choice : str, optional If provided, specifies which series to forecast from the DataFrame.

Returns

pd.DataFrame The forecast results or simulation matrix as a DataFrame for Excel.

@func
@arg('df', index=False, doc='Excel range with columns for features and target.')
@arg('base_model', doc='Classification model (default: "RandomForestClassifier")')
@arg('n_hidden_features', doc='Number of hidden features (default: 5)')
@arg('predict_proba', doc='If TRUE, return class probabilities (default: FALSE)')
@ret(index=False, doc='Classification predictions as a table for Excel')
def techto_mlclassification( df: pandas.core.frame.DataFrame, base_model: str = 'RandomForestClassifier', n_hidden_features: int = 5, predict_proba: bool = False) -> pandas.core.frame.DataFrame:
10@func
11@arg("df", index=False, doc="Excel range with columns for features and target.")
12@arg("base_model", doc='Classification model (default: "RandomForestClassifier")')
13@arg("n_hidden_features", doc="Number of hidden features (default: 5)")
14@arg("predict_proba", doc="If TRUE, return class probabilities (default: FALSE)")
15@ret(index=False, doc="Classification predictions as a table for Excel")
16def techto_mlclassification(
17    df: pd.DataFrame,
18    base_model: str = "RandomForestClassifier",
19    n_hidden_features: int = 5,
20    predict_proba: bool = False,
21) -> pd.DataFrame:
22    """
23    Classification: pass a tabular dataset as a DataFrame from Excel, return predictions.
24
25    Excel/xlwings custom function: Classification on a table from Excel using the Techtonique API.
26
27    Parameters
28    ----------
29
30    df : pd.DataFrame
31        The input data as a DataFrame (from Excel range).
32
33    base_model : str, default "RandomForestClassifier"
34        The classification model to use.
35
36    n_hidden_features : int, default 5
37        Number of hidden features for the model.
38
39    predict_proba : bool, default False
40        If True, return class probabilities.
41
42    Returns
43    -------
44
45    pd.DataFrame
46        Classification predictions (and probabilities if requested) as a DataFrame for Excel.
47
48    ---
49    xlwings lite docstring (for Excel help):
50    Classification on a table from Excel using the Techtonique API.
51    - df: Excel range with columns for features and target.
52    - base_model: Classification model (default: RandomForestClassifier).
53    - n_hidden_features: Number of hidden features (default: 5).
54    - predict_proba: If TRUE, return class probabilities (default: FALSE).
55    Returns: Classification predictions as a table for Excel.
56    """
57    with tempfile.NamedTemporaryFile(suffix=".csv", delete=False) as tmp:
58        df.to_csv(tmp.name, index=False)
59        result = api.mlclassification(
60            file_path=tmp.name,
61            base_model=base_model,
62            n_hidden_features=n_hidden_features,
63            predict_proba=predict_proba,
64        )
65    # Adjust keys as needed based on API response
66    if predict_proba and "proba" in result:
67        return pd.DataFrame(result["proba"])
68    return pd.DataFrame(result["y_pred"])

Classification: pass a tabular dataset as a DataFrame from Excel, return predictions.

Excel/xlwings custom function: Classification on a table from Excel using the Techtonique API.

Parameters

df : pd.DataFrame The input data as a DataFrame (from Excel range).

base_model : str, default "RandomForestClassifier" The classification model to use.

n_hidden_features : int, default 5 Number of hidden features for the model.

predict_proba : bool, default False If True, return class probabilities.

Returns

pd.DataFrame Classification predictions (and probabilities if requested) as a DataFrame for Excel.


xlwings lite docstring (for Excel help): Classification on a table from Excel using the Techtonique API.

  • df: Excel range with columns for features and target.
  • base_model: Classification model (default: RandomForestClassifier).
  • n_hidden_features: Number of hidden features (default: 5).
  • predict_proba: If TRUE, return class probabilities (default: FALSE). Returns: Classification predictions as a table for Excel.
@func
@arg('df', index=False, doc='Excel range with columns for features and target.')
@arg('base_model', doc='Regression model (default: "ElasticNet")')
@arg('n_hidden_features', doc='Number of hidden features (default: 5)')
@arg('return_pi', doc='If TRUE, return prediction intervals (default: TRUE)')
@ret(index=False, doc='Regression predictions as a table for Excel')
def techto_mlregression( df: pandas.core.frame.DataFrame, base_model: str = 'ElasticNet', n_hidden_features: int = 5, return_pi: bool = True) -> pandas.core.frame.DataFrame:
 71@func
 72@arg("df", index=False, doc="Excel range with columns for features and target.")
 73@arg("base_model", doc='Regression model (default: "ElasticNet")')
 74@arg("n_hidden_features", doc="Number of hidden features (default: 5)")
 75@arg("return_pi", doc="If TRUE, return prediction intervals (default: TRUE)")
 76@ret(index=False, doc="Regression predictions as a table for Excel")
 77def techto_mlregression(
 78    df: pd.DataFrame,
 79    base_model: str = "ElasticNet",
 80    n_hidden_features: int = 5,
 81    return_pi: bool = True,
 82) -> pd.DataFrame:
 83    """
 84    Regression: pass a tabular dataset as a DataFrame from Excel, return predictions.
 85
 86    Excel/xlwings custom function: Regression on a table from Excel using the Techtonique API.
 87
 88    Parameters
 89    ----------
 90
 91    df : pd.DataFrame
 92        The input data as a DataFrame (from Excel range).
 93
 94    base_model : str, default "ElasticNet"
 95        The regression model to use.
 96
 97    n_hidden_features : int, default 5
 98        Number of hidden features for the model.
 99
100    return_pi : bool, default True
101        If True, return prediction intervals.
102
103    Returns
104    -------
105    pd.DataFrame
106        Regression predictions (and intervals if requested) as a DataFrame for Excel.
107
108    ---
109    xlwings lite docstring (for Excel help):
110    Regression on a table from Excel using the Techtonique API.
111    - df: Excel range with columns for features and target.
112    - base_model: Regression model (default: ElasticNet).
113    - n_hidden_features: Number of hidden features (default: 5).
114    - return_pi: If TRUE, return prediction intervals (default: TRUE).
115    Returns: Regression predictions as a table for Excel.
116    """
117    with tempfile.NamedTemporaryFile(suffix=".csv", delete=False) as tmp:
118        df.to_csv(tmp.name, index=False)
119        result = api.mlregression(
120            file_path=tmp.name,
121            base_model=base_model,
122            n_hidden_features=n_hidden_features,
123            return_pi=return_pi,
124        )
125    if return_pi:
126        return (pd.DataFrame({
127            "prediction": result["y_pred"],
128            "lower": result["pi_lower"],
129            "upper": result["pi_upper"],
130        }))
131    return (pd.DataFrame({
132        "prediction": result["y_pred"]
133    }))

Regression: pass a tabular dataset as a DataFrame from Excel, return predictions.

Excel/xlwings custom function: Regression on a table from Excel using the Techtonique API.

Parameters

df : pd.DataFrame The input data as a DataFrame (from Excel range).

base_model : str, default "ElasticNet" The regression model to use.

n_hidden_features : int, default 5 Number of hidden features for the model.

return_pi : bool, default True If True, return prediction intervals.

Returns

pd.DataFrame Regression predictions (and intervals if requested) as a DataFrame for Excel.


xlwings lite docstring (for Excel help): Regression on a table from Excel using the Techtonique API.

  • df: Excel range with columns for features and target.
  • base_model: Regression model (default: ElasticNet).
  • n_hidden_features: Number of hidden features (default: 5).
  • return_pi: If TRUE, return prediction intervals (default: TRUE). Returns: Regression predictions as a table for Excel.
@func
@arg('df', index=False, doc='Excel range with reserving triangle data.')
@arg('method', doc='Reserving method (default: "chainladder")')
@ret(index=False, doc='Reserving results as a table for Excel')
def techto_reserving( df: pandas.core.frame.DataFrame, method: str = 'chainladder') -> pandas.core.frame.DataFrame:
10@func
11@arg("df", index=False, doc="Excel range with reserving triangle data.")
12@arg("method", doc='Reserving method (default: "chainladder")')
13@ret(index=False, doc="Reserving results as a table for Excel")
14def techto_reserving(
15    df: pd.DataFrame,
16    method: str = "chainladder",
17) -> pd.DataFrame:
18    """
19    Reserving: pass a triangle as a DataFrame from Excel, return reserving results.
20
21    Excel/xlwings custom function: Classical reserving on a triangle from Excel using the Techtonique API.
22
23    Parameters
24    ----------
25
26    df : pd.DataFrame
27        The input triangle data as a DataFrame (from Excel range).
28
29    method : str, default "chainladder"
30        Reserving method to use.
31
32    Returns
33    -------
34
35    pd.DataFrame
36        Reserving results as a DataFrame for Excel.
37
38    ---
39    xlwings lite docstring (for Excel help):
40    Classical reserving on a triangle from Excel using the Techtonique API.
41    - df: Excel range with reserving triangle data.
42    - method: Reserving method (default: chainladder).
43    Returns: Reserving results as a table for Excel.
44    """
45    with tempfile.NamedTemporaryFile(suffix=".csv", delete=False) as tmp:
46        df.to_csv(tmp.name, index=False)
47        result = api.reserving(
48            file_path=tmp.name,
49            method=method,
50        )
51    if method == "chainladder":
52        return pd.DataFrame(result)
53    return pd.DataFrame({"origin": result["Origin"],
54                         "IBNR": result["IBNR"],
55                         "IBNR 95": result["IBNR 95%"]})

Reserving: pass a triangle as a DataFrame from Excel, return reserving results.

Excel/xlwings custom function: Classical reserving on a triangle from Excel using the Techtonique API.

Parameters

df : pd.DataFrame The input triangle data as a DataFrame (from Excel range).

method : str, default "chainladder" Reserving method to use.

Returns

pd.DataFrame Reserving results as a DataFrame for Excel.


xlwings lite docstring (for Excel help): Classical reserving on a triangle from Excel using the Techtonique API.

  • df: Excel range with reserving triangle data.
  • method: Reserving method (default: chainladder). Returns: Reserving results as a table for Excel.
@func
@arg('df', index=False, doc='Excel range with reserving triangle data.')
@arg('method', doc='ML reserving method (default: "RidgeCV")')
@ret(index=False, doc='ML reserving results as a table for Excel')
def techto_mlreserving( df: pandas.core.frame.DataFrame, method: str = 'RidgeCV') -> pandas.core.frame.DataFrame:
 58@func
 59@arg("df", index=False, doc="Excel range with reserving triangle data.")
 60@arg("method", doc='ML reserving method (default: "RidgeCV")')
 61@ret(index=False, doc="ML reserving results as a table for Excel")
 62def techto_mlreserving(
 63    df: pd.DataFrame,
 64    method: str = "RidgeCV",
 65) -> pd.DataFrame:
 66    """
 67    ML Reserving: pass a triangle as a DataFrame from Excel, return ML reserving results.
 68
 69    Excel/xlwings custom function: ML reserving on a triangle from Excel using the Techtonique API.
 70
 71    Parameters
 72    ----------
 73
 74    df : pd.DataFrame
 75        The input triangle data as a DataFrame (from Excel range).
 76
 77    method : str, default "RidgeCV"
 78        ML reserving method to use.
 79
 80    Returns
 81    -------
 82
 83    pd.DataFrame
 84        ML reserving results as a DataFrame for Excel.
 85
 86    ---
 87    xlwings lite docstring (for Excel help):
 88    ML reserving on a triangle from Excel using the Techtonique API.
 89    - df: Excel range with reserving triangle data.
 90    - method: ML reserving method (default: RidgeCV).
 91    Returns: ML reserving results as a table for Excel.
 92    """
 93    with tempfile.NamedTemporaryFile(suffix=".csv", delete=False) as tmp:
 94        df.to_csv(tmp.name, index=False)
 95        result = api.mlreserving(
 96            file_path=tmp.name,
 97            method=method,
 98        )
 99    return pd.DataFrame({"origin": result["Origin"],
100                         "IBNR": result["IBNR"],
101                         "IBNR 95": result["IBNR 95%"]})

ML Reserving: pass a triangle as a DataFrame from Excel, return ML reserving results.

Excel/xlwings custom function: ML reserving on a triangle from Excel using the Techtonique API.

Parameters

df : pd.DataFrame The input triangle data as a DataFrame (from Excel range).

method : str, default "RidgeCV" ML reserving method to use.

Returns

pd.DataFrame ML reserving results as a DataFrame for Excel.


xlwings lite docstring (for Excel help): ML reserving on a triangle from Excel using the Techtonique API.

  • df: Excel range with reserving triangle data.
  • method: ML reserving method (default: RidgeCV). Returns: ML reserving results as a table for Excel.
@func
@arg('model', doc='Simulation model (default: "GBM")')
@arg('n', doc='Number of scenarios (default: 10)')
@arg('horizon', doc='Simulation horizon (default: 5)')
@arg('frequency', doc='Frequency (default: "quarterly")')
@arg('x0', doc='Initial value (default: 1.0)')
@arg('theta1', doc='Model parameter theta1 (default: 0.0)')
@arg('theta2', doc='Model parameter theta2 (default: 0.5)')
@arg('theta3', doc='Model parameter theta3 (optional)')
@arg('seed', doc='Random seed (optional)')
@ret(index=False, doc='Simulation results as a table for Excel')
def techto_simulation( model: str = 'GBM', n: int = 10, horizon: int = 5, frequency: str = 'quarterly', x0: float = 1.0, theta1: float = 0.0, theta2: float = 0.5, theta3: float = None, seed: int = None) -> pandas.core.frame.DataFrame:
 9@func
10@arg("model", doc='Simulation model (default: "GBM")')
11@arg("n", doc="Number of scenarios (default: 10)")
12@arg("horizon", doc="Simulation horizon (default: 5)")
13@arg("frequency", doc='Frequency (default: "quarterly")')
14@arg("x0", doc="Initial value (default: 1.0)")
15@arg("theta1", doc="Model parameter theta1 (default: 0.0)")
16@arg("theta2", doc="Model parameter theta2 (default: 0.5)")
17@arg("theta3", doc="Model parameter theta3 (optional)")
18@arg("seed", doc="Random seed (optional)")
19@ret(index=False, doc="Simulation results as a table for Excel")
20def techto_simulation(
21    model: str = "GBM",
22    n: int = 10,
23    horizon: int = 5,
24    frequency: str = "quarterly",
25    x0: float = 1.0,
26    theta1: float = 0.0,
27    theta2: float = 0.5,
28    theta3: float = None,
29    seed: int = None,
30) -> pd.DataFrame:
31    """
32    Simulation: run scenario simulation using the Techtonique API.
33
34    Excel/xlwings custom function: Run scenario simulation from Excel using the Techtonique API.
35
36    Parameters
37    ----------
38
39    model : str, default "GBM"
40        Simulation model to use.
41
42    n : int, default 10
43        Number of scenarios.
44
45    horizon : int, default 5
46        Simulation horizon.
47
48    frequency : str, default "quarterly"
49        Frequency of simulation.
50
51    x0 : float, default 1.0
52        Initial value.
53
54    theta1 : float, default 0.0
55        Model parameter theta1.
56
57    theta2 : float, default 0.5
58        Model parameter theta2.
59
60    theta3 : float, optional
61        Model parameter theta3.
62
63    seed : int, optional
64        Random seed.
65
66    Returns
67    -------
68
69    pd.DataFrame
70        Simulation results as a DataFrame for Excel.
71
72    ---
73    xlwings lite docstring (for Excel help):
74    Run scenario simulation from Excel using the Techtonique API.
75    - model: Simulation model (default: GBM).
76    - n: Number of scenarios (default: 10).
77    - horizon: Simulation horizon (default: 5).
78    - frequency: Frequency (default: quarterly).
79    - x0: Initial value (default: 1.0).
80    - theta1: Model parameter theta1 (default: 0.0).
81    - theta2: Model parameter theta2 (default: 0.5).
82    - theta3: Model parameter theta3 (optional).
83    - seed: Random seed (optional).
84    Returns: Simulation results as a table for Excel.
85    """
86    result = api.simulate_scenario(
87        model=model,
88        n=n,
89        horizon=horizon,
90        frequency=frequency,
91        x0=x0,
92        theta1=theta1,
93        theta2=theta2,
94        theta3=theta3,
95        seed=seed,
96    )
97    # Adjust as needed based on API response structure
98    return pd.DataFrame(result["sims"])

Simulation: run scenario simulation using the Techtonique API.

Excel/xlwings custom function: Run scenario simulation from Excel using the Techtonique API.

Parameters

model : str, default "GBM" Simulation model to use.

n : int, default 10 Number of scenarios.

horizon : int, default 5 Simulation horizon.

frequency : str, default "quarterly" Frequency of simulation.

x0 : float, default 1.0 Initial value.

theta1 : float, default 0.0 Model parameter theta1.

theta2 : float, default 0.5 Model parameter theta2.

theta3 : float, optional Model parameter theta3.

seed : int, optional Random seed.

Returns

pd.DataFrame Simulation results as a DataFrame for Excel.


xlwings lite docstring (for Excel help): Run scenario simulation from Excel using the Techtonique API.

  • model: Simulation model (default: GBM).
  • n: Number of scenarios (default: 10).
  • horizon: Simulation horizon (default: 5).
  • frequency: Frequency (default: quarterly).
  • x0: Initial value (default: 1.0).
  • theta1: Model parameter theta1 (default: 0.0).
  • theta2: Model parameter theta2 (default: 0.5).
  • theta3: Model parameter theta3 (optional).
  • seed: Random seed (optional). Returns: Simulation results as a table for Excel.
@func
@arg('df', index=False, doc='Excel range with columns for survival data.')
@arg('method', doc='Survival analysis method (default: "km")')
@arg('patient_id', doc="(For machine learning 'method's) Patient ID for individual survival curve")
@ret(index=False, doc='Survival curve results as a table for Excel')
def techto_survival( df: pandas.core.frame.DataFrame, method: str = 'km', patient_id: int = None) -> pandas.core.frame.DataFrame:
10@func
11@arg("df", index=False, doc="Excel range with columns for survival data.")
12@arg("method", doc='Survival analysis method (default: "km")')
13@arg("patient_id", doc="(For machine learning 'method's) Patient ID for individual survival curve")
14@ret(index=False, doc="Survival curve results as a table for Excel")
15def techto_survival(
16    df: pd.DataFrame,
17    method: str = "km",
18    patient_id: int = None,
19) -> pd.DataFrame:
20    """
21    Survival analysis: pass a survival dataset as a DataFrame from Excel, return survival curve.
22
23    Excel/xlwings custom function: Survival analysis on a table from Excel using the Techtonique API.
24
25    Parameters
26    ----------
27
28    df : pd.DataFrame
29        The input survival data as a DataFrame (from Excel range).
30
31    method : str, default "km"
32        Survival analysis method to use.
33
34    patient_id : int, optional
35        For machine learning methods, patient ID for individual survival curve.
36
37    Returns
38    -------
39
40    pd.DataFrame
41        Survival curve results as a DataFrame for Excel.
42
43    ---
44    xlwings lite docstring (for Excel help):
45    Survival analysis on a table from Excel using the Techtonique API.
46    - df: Excel range with columns for survival data.
47    - method: Survival analysis method (default: km).
48    - patient_id: (For machine learning methods) Patient ID for individual survival curve.
49    Returns: Survival curve results as a table for Excel.
50    """
51    with tempfile.NamedTemporaryFile(suffix=".csv", delete=False) as tmp:
52        df.to_csv(tmp.name, index=False)
53        result = api.survival_curve(
54            file_path=tmp.name,
55            method=method,
56            patient_id=patient_id,
57        )
58    return pd.DataFrame(result)

Survival analysis: pass a survival dataset as a DataFrame from Excel, return survival curve.

Excel/xlwings custom function: Survival analysis on a table from Excel using the Techtonique API.

Parameters

df : pd.DataFrame The input survival data as a DataFrame (from Excel range).

method : str, default "km" Survival analysis method to use.

patient_id : int, optional For machine learning methods, patient ID for individual survival curve.

Returns

pd.DataFrame Survival curve results as a DataFrame for Excel.


xlwings lite docstring (for Excel help): Survival analysis on a table from Excel using the Techtonique API.

  • df: Excel range with columns for survival data.
  • method: Survival analysis method (default: km).
  • patient_id: (For machine learning methods) Patient ID for individual survival curve. Returns: Survival curve results as a table for Excel.