---
title: "Using Custom Calculations"
date: "2024-03-24T09:22:36+00:00"
summary: "Learn to build custom calculations in CDP Studio to track customer returns, save scores, and apply insights to Campaigns, Metrics, and 360 Profiles."
image:
type: "page"
url: "/customer-data-platform/using-custom-calculations"
id: "120e4b6a-eca8-4076-843c-935001797a79"
---

This page provides information about how to use custom calculations for the following scenario:
===============================================================================================

Data analysts want to create data calculations to enhance the marketing strategy. The focus is on creating custom calculations to track customer returns over the past 15 days and save this data as scores to improve marketing decisions. The aim is to apply insights to Campaigns, Metrics, and 360 Profiles.

Checklist for using custom calculations
---------------------------------------

Complete the following tasks to use custom calculations for the given scenario:

S.No.

Task

1

[Create a custom calculation file](#create-custom-calculation-file)

2

[Design the layout the custom calculation file](#design-layout-custom-calculation%20file)

3

[Construct the execution layout using Markdown](#construct-execution-layout)

4

[Add execution code for Markdown steps](#add-execution-code-markdown)

5

[Verify the newly added custom attribute](#verify-newly-added-custom-attribute)

6

[Schedule calculation execution](#schedule-calculation-execution)

7

[Learn about essential Python commands](#essential-python-commands)

Creating a custom calculation file
----------------------------------

1.  [Sign in to your CDP user interface](../../getting-started/signin-cdp.html).
2.  Click **CDP Studio**.
    
    The CDP Studio landing page only displays the features that you can access.
    
3.  Click **Launch Custom Calculations**.
    
    The application displays the Jupyter notebook landing page.
    
    ![cdp_jupyter-notebook-landing-page.png](https://acquia.widen.net/content/volf1wi5sl/web/cdp_jupyter-notebook-landing-page.png?w=720&v=11744860-d76e-4417-b2af-b8484f73a4ec&itok=FbmkRFm9)
    
4.  Click the **New** dropdown menu and select **Folder**.
    
5.  Click the checkbox to select the folder. 
    
6.  Click **Rename** and change the name from `Untitled Folder` to `All_Custom_Cals_Test`.
    
7.  Click **All\_Custom\_Cals\_Test**.
    
8.  Click the **New** dropdown menu and select **cdp-studio**.
    
    The application creates the `Untitled.ipynb` calculation file on the Jupyter notebook landing page and opens it in a new tab.
    
9.  Click **Untitled.ipynb** and change the name from `Untitled.ipynb` to `custom_calculations_return_order_calculation_sample.ipynb`.
    

Designing the layout the custom calculation file
------------------------------------------------

1.  In the custom calculation file, click the default cell and change it from **Code** to **Markdown**. 
    

![cdp_markdown.png](https://acquia.widen.net/content/131gvfwffc/web/cdp_markdown.png?v=3a278b6b-edc3-4a65-97ae-fc732cd35c08)

2.  Copy the following content in the cell:
    
        # Return Orders Calculation
        In this notebook we will go through an example of how to use the CustomCalculationsClient to perform a simple custom calculation for return orders in last 15 days.
        ## Description
        The goal of this notebook is to compute the number of **return orders per customer in the last 15 days** using CDP Customer data, and **store the scores** in CDP for further integrations.
    
3.  Verify that the content is displayed as follows:
    
    ![cdp_before-execution.png](https://acquia.widen.net/content/b0itoq7wzu/web/cdp_before-execution.png?w=720&v=6e7c188a-c0ad-473a-95a1-f643de11eeb8&itok=LCXz8Q2R)
    
4.  Click **Run** or use the keyboard shortcut `Shift+Enter` to run the cell.
    
    The application displays the content in Markdown and also displays a new cell.
    
    ![cdp_after-execution.png](https://acquia.widen.net/content/jfz4cwu3iv/web/cdp_after-execution.png?w=720&v=f8ada230-c33c-4016-a923-ec218a607f46&itok=fMxvMRWo)
    
5.  Double-click the cell to edit its content.
    

Constructing the execution layout using Markdown
------------------------------------------------

Use Markdown to organize your notebook with clear and structured sections for ease of understanding. Select the cell and change it from **Code** to **Markdown**.   
To perform custom calculations, follow these steps and execute the given text at each stage:

1.  Initialize SDK and create a new project in the data model. 
    
        ### STEP 1 - Import the CustomCalculationsClient and libraries <a class="anchor" id="step-1"></a>
        This step involves importing the A1 `CustomCalculationsClient` and initializing it.
    
2.  Write the SQL statement and run the query to retrieve the results.
    
        ### STEP 2 - Prepare the SQL query and retrieve the data <a class="anchor" id="step-2"></a>
        This step involves preparation of SQL query and it's execution to retrieve the desired data from CDP.
    
3.  Verify the SQL results to ensure that they align with the business logic.
    
4.  Save and integrate the results into the Snowflake data model for the new calculation project.
    
        ### STEP 3 - Saving scores to the CDP<a class="anchor" id="step-3"></a>
        In this step, we save the dataframe of scores back to the CDP.
    
    The system publishes and distributes your custom calculation to Actions, Metrics, and 360 Profiles for integration.
    
        ### STEP 4 - Surface Scored Data to the CDP<a class="anchor" id="step-4"></a>
        * The model scores will still be surfaced to all modules of the application after the CDP pipeline refresh is complete.
    
5.  Provide a display name and description for your calculation.
    
    Cells before execution:
    
    ![cdp_cells-before-execution.png](https://acquia.widen.net/content/3bdropf1sh/web/cdp_cells-before-execution.png?w=720&v=d8e79edb-1637-4f76-9d95-956938c8ed25&itok=OuDtzP46)
    
    Cells after execution:
    
    ![cdp_cells-after-execution.png](https://acquia.widen.net/content/9ryjcqpylq/web/cdp_cells-after-execution.png?w=720&v=2e3a656a-37ae-4495-a82e-b7a744812bdf&itok=2r6BXFJM)
    
6.  Set your custom calculation to synchronize and run daily to ensure consistent data updates.
    

Adding execution code for Markdown steps
----------------------------------------

Note

*   Insert a code for each step. To execute a cell, click **Run** or press `Shift+Enter`, and proceed in a sequence from steps 1 to 5.
*   Select **Code** to convert the cell into a code environment.

1.  Create a code cell and enter the following Python code to import libraries:
    
        from a1mlclient import CustomCalculationsClient
        client = CustomCalculationsClient(project_name="return-orders-calculation")
    
    **Import Libraries**
    

![cdp_import-libraries.png](https://acquia.widen.net/content/ntwvroepyk/web/cdp_import-libraries.png?w=1090&v=8d48db0c-00e8-4270-b8c3-2e187e7526ca&itok=KNYtQPhx)

2.  Create a code cell and enter the following SQL query:
    
        query = '''
        SELECT 
          MASTERCUSTOMERID,
          COUNT(*) AS SCORE, 
          CASE 
            WHEN SCORE > 15 THEN 'HIGH'
            WHEN SCORE BETWEEN 10 AND 15 THEN 'MEDIUM' 
            ELSE 'LOW' 
          END AS VALUE_NAME
        FROM STUDIO_TRANSACTIONSUMMARY
        WHERE SUBTYPE = 'Returned' AND TRANSACTIONTIMESTAMP >= DATEADD(day, -15, GETDATE())
        GROUP BY MASTERCUSTOMERID ORDER BY SCORE DESC;
        '''
        df = client.query_data(query)
        df.head(25)    
    
    **SQL Query Execution** 
    

![cdp_sql-query-execution.png](https://acquia.widen.net/content/0rtldk1vrh/web/cdp_sql-query-execution.png?w=1090&v=ed7066a9-905f-4440-8412-1bf8988437e3&itok=syQ9VDoV)

3.  Create a code cell and enter the following code to save data:
    
        # Write the data to CDP
        client.write_output_data(df = df, description = 'ML Studio Simple Custom Calculation')
    

    **Saving Scores to CDP**

![cdp_saving-scores-to-cdp.png](https://acquia.widen.net/content/tx5hlwgdle/web/cdp_saving-scores-to-cdp.png?w=1090&v=3f6071bd-bcf4-4ed8-a038-22c9d9b26961&itok=fUvLH7xf)

4.  This step is automated.   
    Code is not required to surface CDP data.     
    
5.  Create a code cell and add the following code:
    
        client.update_output_name(
            display_name="ML Studio Custom Calculation Demo",
            description="ML Studio Custom Calculation Demo Description"
        )
    
    **Update Display Names for Surfaced Models in CDP**
    

![cdp_update-display-names.png](https://acquia.widen.net/content/ak7vunuc2q/web/cdp_update-display-names.png?w=1090&v=e048f0a8-f0ea-4a0b-876d-508117bbebb3&itok=A-pZkasg)

Verifying the newly added custom attribute
------------------------------------------

1.  Log in to the CDP user interface and [create a new campaign](https://docs.acquia.com/customer-data-platform/getting-started/data-activation-getting-started#section-creating-a-campaign). 
    
2.  In **Include customers who**, click the **Add Group** icon.  
    The system displays the Add Rule page.
3.  Search the **ML Studio Custom Calculation Sample** filter.
    
    You can see the newly added custom attribute **ML Studio Custom Calculation Sample** calculation filter.
    

![cdp_ml-studio-custom-calculation-sample.png](https://acquia.widen.net/content/kpwwuxlof4/web/cdp_ml-studio-custom-calculation-sample.png?w=720&v=dba876ae-95ea-42c5-ad2d-d830cbc251a4&itok=kJXuBMPf)

Scheduling calculation execution
--------------------------------

1.  Create a new markdown cell.
    
2.  Run the following text:
    
        ### Step 7(Optional): Schedule Calculation ExecutionCreate a New Code Cell.
    
3.  Create a new code cell.
    
4.  Run the following code:
    

    client.add_schedule(
        frequency="daily",
        time="10:00",
        notebook_path="All Custom Cals Test/custom_calculations_return_order_calculation_sample.ipynb",
        schedule_name="sample_return_order_calculation_schedule"
    )

 **Frequency Setting**: Choose from daily, weekly, or monthly intervals.

 **Time Setting**: Specify the time in 24-hour HH:MM format, UTC (e.g., 18:00 = 6 PM UTC).

 **Notebook Path Setting**: Define the path for the notebook to execute as per your chosen frequency and time.

 **Schedule Name Setting**: Assign a name to your schedule for easy identification

Important

Locate the notebook path parameter after `notebooks/` in your browser's URL. Copy and paste the value `All_Custom_Cals_Test/custom_calculations_return_order_calculation_sample.ipynb` into the `notebook_path` field of the Python object.

![cdp_schedule.png](https://acquia.widen.net/content/dkukvjbbuw/web/cdp_schedule.png?w=1090&v=f13e58ba-a5c6-45e2-b7e3-28d008558f97&itok=UAaFmy2h)

5.  Insert and run the following code in a new code cell to stop the schedule:
    
        #delete the schedule
        client.delete_schedule(notebook_path = 'All_Custom_Cals_Test/custom_calculations_return_order_calculation_sample.ipynb')
        client.delete_schedule(schedule_name = "sample_return_order_calculation_schedule")
    

![cdp_delete-schedule.png](https://acquia.widen.net/content/bjon7acwdg/web/cdp_delete-schedule.png?v=f1766bb0-e0fc-4a6f-9ba6-cab99a86e4d4)

6.  Insert and run the following code in a new code cell to confirm the schedule removal:
    
        #check schedule
        client.describe_schedule(schedule_name="sample_return_order_calculation_schedule")
    

![cdp_check-schedule.png](https://acquia.widen.net/content/t1zccjjp8s/web/cdp_check-schedule.png?v=2e3b09ba-05de-40bf-9bb1-9cd3c1966165)

The following message indicates that the schedule has been removed:

![cdp_schedulenotfound-exception.png](https://acquia.widen.net/content/ojhohsdaok/web/cdp_schedulenotfound-exception.png?w=1090&v=e1302a7e-985c-4b7d-a3ba-76f7f6b40abc&itok=ZeEmW0TF)

Essential Python commands
-------------------------

For more Python command functions, see [Custom Calculations Developer Documentation](https://docs.acquia.com/customer-data-platform/add-on/machine-learning/custom-calculations/custom-calculations-developer "https://docs.acquia.com/customer-data-platform/add-on/machine-learning/custom-calculations/custom-calculations-developer").  
 

### Reading current calculation output

You can examine the output data. The following command loads the current calculation results into a DataFrame for inspection:

    #Reading Current Calculation Output
    read_df = client.read_output_data()
    print(read_df)

![cdp_reading-current-calculation.png](https://acquia.widen.net/content/sboh46lru5/web/cdp_reading-current-calculation.png?v=1af8b51f-f7a9-4f68-bf3a-6d8a1a0e1d24)

### Listing available tables

You can identify available tables for SQL queries. The following command returns a DataFrame listing all accessible tables:

    #Listing Available Tables
    tbl_df = client.list_available_tables()
    print(tbl_df)

![cdp_listing-available-table.png](https://acquia.widen.net/content/naifqui0cd/web/cdp_listing-available-table.png?v=87dd5794-7f07-4e55-a27c-f100c99228c4)

### Viewing Projects in Use

You can identify the scope and potential project interactions. The following command returns a list of active projects and retrieves the project names: 

    #Viewing Projects in Use
    proj_names = client.list_project_names()
    print(proj_names)

![cdp_viewing-projects.png](https://acquia.widen.net/content/xar4aswqeu/web/cdp_viewing-projects.png?v=83a7ff19-1954-4fc4-bd75-bdca3b21e34e)

### Checking Project Metadata

You can gain insights into a specific project. The following command returns previous outputs and metadata:

    #Checking Project Metadata
    Client_view = CustomCalculationsClient(project_name="YourProjectName")
    proj_metadata = Client_view.describe_project()
    print(proj_metadata)

Replace `"YourProjectName"` with your project's actual name to understand its structure and computational history.

![cdp_checking-project-metadata.png](https://acquia.widen.net/content/vcid2hbnpo/web/cdp_checking-project-metadata.png?v=a74a324c-5868-439d-a7de-a189277e7ac2)