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]
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)
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 # Convert Excel serial dates to datetime if needed 95 if pd.api.types.is_numeric_dtype(df["date"]): 96 df["date"] = df["date"].apply(excel_date_to_datetime) 97 98 with tempfile.NamedTemporaryFile(suffix=".csv", delete=False) as tmp: 99 df.to_csv(tmp.name, index=False) 100 result = api.forecasting( 101 file_path=tmp.name, 102 base_model=base_model, 103 n_hidden_features=n_hidden_features, 104 lags=lags, 105 type_pi=type_pi, 106 replications=replications, 107 h=h, 108 ) 109 output_dates = result["date"] 110 if df.shape[1] == 2: # univariate time series 111 res_df = pd.DataFrame(result.pop("sims")) 112 if return_sims: 113 res2_df = pd.DataFrame([]) 114 res2_df["date"] = output_dates 115 sims_df = res_df.transpose() 116 sims_df.columns = [(i + 1) for i in range(sims_df.shape[1])] 117 return pd.concat([res2_df, sims_df], axis=1) 118 return pd.DataFrame(result) 119 else: # multivariate time series 120 n_series = len(result["mean"][0]) 121 series_names = [col for col in df.columns if col != "date"] 122 if len(series_names) != n_series: 123 series_names = [f"series_{i+1}" for i in range(n_series)] 124 125 # If series_choice is provided and valid, extract its index and return as univariate 126 if series_choice is not None and series_choice in series_names: 127 idx = series_names.index(series_choice) 128 # Extract only the selected series from each stat 129 summary_df = pd.DataFrame( 130 { 131 "date": output_dates, 132 "mean": [x[idx] for x in result["mean"]], 133 "lower": [x[idx] for x in result["lower"]], 134 "upper": [x[idx] for x in result["upper"]], 135 } 136 ) 137 if return_sims: 138 # sims: shape (replications, horizon, n_series) 139 # list of replications, each is list of horizon, each is list of n_series 140 sims = result["sims"] 141 # For each replication, extract the selected series only 142 sims_selected = [ 143 [h[idx] for h in rep] 144 # shape: (replications, horizon) 145 for rep in sims 146 ] 147 sims_df = pd.DataFrame(sims_selected).transpose() 148 sims_df.columns = [ 149 f"sim_{i+1}_{series_choice}" 150 for i in range(sims_df.shape[1]) 151 ] 152 res2_df = pd.DataFrame({"date": output_dates}) 153 return pd.concat([res2_df, sims_df], axis=1) 154 return summary_df 155 156 # Otherwise, return the full multivariate summary as before 157 summary_data = {"date": output_dates} 158 for stat in ["mean", "lower", "upper"]: 159 for s in range(n_series): 160 summary_data[f"{stat}_{series_names[s]}"] = [ 161 x[s] for x in result[stat] 162 ] 163 summary_df = pd.DataFrame(summary_data) 164 if return_sims: 165 # sims: shape (replications, horizon, n_series) 166 sims = result["sims"] 167 flat = [] 168 for rep in sims: 169 for s in range(n_series): 170 flat.append([h[s] for h in rep]) 171 sims_df = pd.DataFrame(flat).transpose() 172 colnames = [] 173 for r in range(len(sims)): 174 for s in range(n_series): 175 colnames.append(f"sim_{r+1}_{series_names[s]}") 176 sims_df.columns = colnames 177 sims_df.insert(0, "date", output_dates) 178 return sims_df 179 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.
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 with tempfile.NamedTemporaryFile(suffix=".csv", delete=False) as tmp: 62 df.to_csv(tmp.name, index=False) 63 result = api.mlclassification( 64 file_path=tmp.name, 65 base_model=base_model, 66 n_hidden_features=n_hidden_features, 67 predict_proba=predict_proba, 68 ) 69 # Adjust keys as needed based on API response 70 if predict_proba and "proba" in result: 71 return pd.DataFrame(result["proba"]) 72 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.
75@func 76@arg("df", index=False, doc="Excel range with columns for features and target.") 77@arg("base_model", doc='Regression model (default: "ElasticNet")') 78@arg("n_hidden_features", doc="Number of hidden features (default: 5)") 79@arg("return_pi", doc="If TRUE, return prediction intervals (default: TRUE)") 80@ret(index=False, doc="Regression predictions as a table for Excel") 81def techto_mlregression( 82 df: pd.DataFrame, 83 base_model: str = "ElasticNet", 84 n_hidden_features: int = 5, 85 return_pi: bool = True, 86) -> pd.DataFrame: 87 """ 88 Regression: pass a tabular dataset as a DataFrame from Excel, return predictions. 89 90 Excel/xlwings custom function: Regression on a table from Excel using the Techtonique API. 91 92 Parameters 93 ---------- 94 95 df : pd.DataFrame 96 The input data as a DataFrame (from Excel range). 97 98 base_model : str, default "ElasticNet" 99 The regression model to use. 100 101 n_hidden_features : int, default 5 102 Number of hidden features for the model. 103 104 return_pi : bool, default True 105 If True, return prediction intervals. 106 107 Returns 108 ------- 109 pd.DataFrame 110 Regression predictions (and intervals if requested) as a DataFrame for Excel. 111 112 --- 113 xlwings lite docstring (for Excel help): 114 Regression on a table from Excel using the Techtonique API. 115 - df: Excel range with columns for features and target. 116 - base_model: Regression model (default: ElasticNet). 117 - n_hidden_features: Number of hidden features (default: 5). 118 - return_pi: If TRUE, return prediction intervals (default: TRUE). 119 Returns: Regression predictions as a table for Excel. 120 """ 121 with tempfile.NamedTemporaryFile(suffix=".csv", delete=False) as tmp: 122 df.to_csv(tmp.name, index=False) 123 result = api.mlregression( 124 file_path=tmp.name, 125 base_model=base_model, 126 n_hidden_features=n_hidden_features, 127 return_pi=return_pi, 128 ) 129 if return_pi: 130 return pd.DataFrame( 131 { 132 "prediction": result["y_pred"], 133 "lower": result["pi_lower"], 134 "upper": result["pi_upper"], 135 } 136 ) 137 return pd.DataFrame({"prediction": result["y_pred"]})
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.
62@func 63@arg("df", index=False, doc="Excel range with reserving triangle data.") 64@arg("method", doc='ML reserving method (default: "RidgeCV")') 65@ret(index=False, doc="ML reserving results as a table for Excel") 66def techto_mlreserving( 67 df: pd.DataFrame, 68 method: str = "RidgeCV", 69) -> pd.DataFrame: 70 """ 71 ML Reserving: pass a triangle as a DataFrame from Excel, return ML reserving results. 72 73 Excel/xlwings custom function: ML reserving on a triangle from Excel using the Techtonique API. 74 75 Parameters 76 ---------- 77 78 df : pd.DataFrame 79 The input triangle data as a DataFrame (from Excel range). 80 81 method : str, default "RidgeCV" 82 ML reserving method to use. 83 84 Returns 85 ------- 86 87 pd.DataFrame 88 ML reserving results as a DataFrame for Excel. 89 90 --- 91 xlwings lite docstring (for Excel help): 92 ML reserving on a triangle from Excel using the Techtonique API. 93 - df: Excel range with reserving triangle data. 94 - method: ML reserving method (default: RidgeCV). 95 Returns: ML reserving results as a table for Excel. 96 """ 97 with tempfile.NamedTemporaryFile(suffix=".csv", delete=False) as tmp: 98 df.to_csv(tmp.name, index=False) 99 result = api.mlreserving( 100 file_path=tmp.name, 101 method=method, 102 ) 103 return pd.DataFrame( 104 { 105 "origin": result["Origin"], 106 "IBNR": result["IBNR"], 107 "IBNR 95": result["IBNR 95%"], 108 } 109 )
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.
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 with tempfile.NamedTemporaryFile(suffix=".csv", delete=False) as tmp: 55 df.to_csv(tmp.name, index=False) 56 result = api.survival_curve( 57 file_path=tmp.name, 58 method=method, 59 patient_id=patient_id, 60 ) 61 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.