techtonique_apis

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

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

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

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='ML reserving method (default: "RidgeCV")')
@ret(index=False, doc='ML reserving results as a table for Excel')
def techto_mlreserving(df: pandas.DataFrame, method: str = 'RidgeCV') -> pandas.DataFrame:
 65@func
 66@arg("df", index=False, doc="Excel range with reserving triangle data.")
 67@arg("method", doc='ML reserving method (default: "RidgeCV")')
 68@ret(index=False, doc="ML reserving results as a table for Excel")
 69def techto_mlreserving(
 70    df: pd.DataFrame,
 71    method: str = "RidgeCV",
 72) -> pd.DataFrame:
 73    """
 74    ML Reserving: pass a triangle as a DataFrame from Excel, return ML reserving results.
 75
 76    Excel/xlwings custom function: ML reserving on a triangle from Excel using the Techtonique API.
 77
 78    Parameters
 79    ----------
 80
 81    df : pd.DataFrame
 82        The input triangle data as a DataFrame (from Excel range).
 83
 84    method : str, default "RidgeCV"
 85        ML reserving method to use.
 86
 87    Returns
 88    -------
 89
 90    pd.DataFrame
 91        ML reserving results as a DataFrame for Excel.
 92
 93    ---
 94    xlwings lite docstring (for Excel help):
 95    ML reserving on a triangle from Excel using the Techtonique API.
 96    - df: Excel range with reserving triangle data.
 97    - method: ML reserving method (default: RidgeCV).
 98    Returns: ML reserving results as a table for Excel.
 99    """
100    try:
101        with tempfile.NamedTemporaryFile(suffix=".csv", delete=False) as tmp:
102            df.to_csv(tmp.name, index=False)
103            result = api.mlreserving(
104                file_path=tmp.name,
105                method=method,
106            )
107        return pd.DataFrame(
108            {
109                "origin": result["Origin"],
110                "IBNR": result["IBNR"],
111                "IBNR 95": result["IBNR 95%"],
112            }
113        )
114    except Exception as e:
115        return pd.DataFrame({"error": [str(e)]})

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('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.DataFrame, method: str = 'km', patient_id: int = None) -> pandas.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(
14    "patient_id",
15    doc="(For machine learning 'method's) Patient ID for individual survival curve",
16)
17@ret(index=False, doc="Survival curve results as a table for Excel")
18def techto_survival(
19    df: pd.DataFrame,
20    method: str = "km",
21    patient_id: int = None,
22) -> pd.DataFrame:
23    """
24    Survival analysis: pass a survival dataset as a DataFrame from Excel, return survival curve.
25
26    Excel/xlwings custom function: Survival analysis on a table from Excel using the Techtonique API.
27
28    Parameters
29    ----------
30
31    df : pd.DataFrame
32        The input survival data as a DataFrame (from Excel range).
33
34    method : str, default "km"
35        Survival analysis method to use.
36
37    patient_id : int, optional
38        For machine learning methods, patient ID for individual survival curve.
39
40    Returns
41    -------
42
43    pd.DataFrame
44        Survival curve results as a DataFrame for Excel.
45
46    ---
47    xlwings lite docstring (for Excel help):
48    Survival analysis on a table from Excel using the Techtonique API.
49    - df: Excel range with columns for survival data.
50    - method: Survival analysis method (default: km).
51    - patient_id: (For machine learning methods) Patient ID for individual survival curve.
52    Returns: Survival curve results as a table for Excel.
53    """
54    try:
55        with tempfile.NamedTemporaryFile(suffix=".csv", delete=False) as tmp:
56            df.to_csv(tmp.name, index=False)
57            result = api.survival_curve(
58                file_path=tmp.name,
59                method=method,
60                patient_id=patient_id,
61            )
62        return pd.DataFrame(result)
63    except Exception as e:
64        return pd.DataFrame({"error": [str(e)]})

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.