top of page
Writer's pictureAlan Campbell

Mastering Analytics with Python & Power Apps - Part 5

Updated: Oct 30, 2023

Welcome to the grand finale of our immersive blog series where we have been methodically building towards the powerful convergence of Python and Microsoft Power Apps to unlock unprecedented predictive analytics capabilities for your business.


In this pivotal fifth installment, we undertake the significant task of synthesizing the various components meticulously assembled in the previous blogs to construct a dynamic Microsoft Power App, fundamentally powered by the statistical might of Python scripts.


this image shows the historical sales and future trend of business central item number 1968-S by using a Power App calling a Python Script Functional App  through a custom connector
Sales Trend of Business Central Item Number 1968-S

Our focus narrows down to the practical application of predictive analytics, as we guide you step by step to deploy the slope and intercept in envisioning future sales trends with an uncanny precision. The compass guiding this expedition is the 'Statistics custom connector' that we carefully crafted in our prior discussions, poised to interface with the Python script we previously developed, thereby calling upon the rich functionalities of the scipy.stats.linregress library and functions to derive critical data points such as slope, intercept, and r-value.


As we steer through this tutorial, we will be:

  • Integrating essential connectors into your Power App to bridge with vital databases, including the pivotal 'Statistics custom connector' and the 'Business Central ItemLedgerEntries connector'.

  • Setting up a dynamic OnStart trigger, orchestrating the preparatory steps to create a repository of item ledger data and item list collection, essential in facilitating user interactions.

  • Incorporating user interface elements such as a ComboBox to aid in user selections, powered by the rich data harnessed from the item list collection.

  • Constructing a 'Submit' button endowed with an array of functionalities to streamline data for Python script interaction, facilitate data retrieval post Python script execution, and meticulously forecast future sales spanning a half-year period using the derived slope and intercept values.

  • Embedding a visually appealing and data-rich line chart, geared to present your predictive data in an insightful and accessible manner, thereby serving as a powerful tool in your decision-making arsenal.

At each phase, we delve into the core of Power Apps scripting, illustrating the potent integration of Power App’s native functions with Python’s computational might to churn out actionable business insights grounded in historical data.


Join us in this culmination of our series as we harness the true potential of Python in tandem with Power Apps to craft an analytic powerhouse, steering your business endeavors with data-driven precision and foresight.


Step into a realm where predictive analytics is no longer a complex term but a tangible tool in your business toolkit, as we demystify the intricate workings of predictive analytics, one script at a time.


Let’s dive in, as we embark on this final chapter, pulling together the threads of expertise garnered through our series, paving a path to predictive mastery with Python and Microsoft Power Apps.


1. The Connectors


In your Power App click on the Data button in the left navigation pane and search for and add:

  • The Statistics custom connector

  • The Business Central ItemLedgerEntries connector

the image shows the left navigation pane in Power Apps where you click on the Data button to add connectors
Click the Data button and Add Your Power Apps Connectors

2. OnStart Trigger. Add the following code to your App's Onstart trigger. This code will first prepare the item ledger data and then create a list of the items found in the item ledger.


// Create the ItemLedger Collection as a master
ClearCollect(
    ItemLedger,
    ForAll(
        Filter(
            'itemLedgerEntries (v2.0)',
            'Entry Type' = "Sale"
        ),
        {
            itemNumber: 'Item No.',
            salesAmount: Round(
                ThisRecord.'Sales Amount (Actual)',
                0
            ),
            postingDate: DateValue(ThisRecord.'Posting Date'),
            documentNumber: ThisRecord.'Document No.'
        }
    )
);
// Create an Item Number Collection
ClearCollect(
    ItemList,
    Distinct(
        ItemLedger,
        itemNumber
    )
);

3. ComboBox. Insert and add a ComboBox to your screen. Use ItemList as your Datasource.


4. Submit Button. Insert and add a Buttom to your screen. Name the button Submit. Add the following code to the OnSelect trigger. This code will take the selected item number and total the sales by month. The App will then submit the data to the Python script through the custom connector we built in prior blogs. The script will return the slope, intercept, and rvalue back to the App. The App will then forecast sales for the next 6 months using the slope and intercept.


// Set the forecast to 6 months
UpdateContext({monthsToForecast: 6});
// Create the data for the Transactions tab
ClearCollect(
    TransactionData,
    ForAll(
        Filter(
            ItemLedger,
            itemNumber = ComboBox1.Selected.Value
        ),
        {
            itemNumber: itemNumber,
            documentNumber: documentNumber,
            postingDate: postingDate,
            salesAmount: salesAmount
        }
    )
);
// Determine the min and max dates 
UpdateContext(
    {
        firstDate: Min(
            TransactionData,
            postingDate
        ),
        lastDate: Max(
            TransactionData,
            postingDate
        )
    }
);
// Determine the difference in months
UpdateContext(
    {
        monthDifference: DateDiff(
            Date(
                Year(firstDate),
                Month(firstDate),
                1
            ),
            Date(
                Year(lastDate),
                Month(lastDate),
                1
            ),
            TimeUnit.Months
        ) + 1
    }
);
// Sumarize the Item Ledger Data by Month
ClearCollect(
    MonthlyData,
    ForAll(
        Sequence(
            monthDifference,
            0
        ),
        {
            y: Sum(
                Filter(
                    TransactionData,
                    postingDate >= DateAdd(
                        firstDate,
                        Value,
                        TimeUnit.Months
                    ),
                    postingDate <= DateAdd(
                        firstDate,
                        Value + 1,
                        TimeUnit.Months
                    )
                ),
                salesAmount
            ),
            x: Value
        }
    )
);
// Call the connection
UpdateContext(
    {
        statisticsResponse: Statistics.GetStatistics(
            Concat(
                MonthlyData,
                x,
                ","
            ),
            Concat(
                MonthlyData,
                y,
                ","
            )
        )
    }
);
// Save the connection response
UpdateContext(
    {
        slope: statisticsResponse.slope,
        intercept: statisticsResponse.intercept,
        r: statisticsResponse.r
    }
);
// Build the forecast data for Line Chart tab.  The Slope-Intercept Formula     y = mx + b  
ClearCollect(
    LineChartData,
    ForAll(
        Sequence(
            monthDifference + monthsToForecast + 1,
            0
        ),
        {
            Amount1: If(
                Value < monthDifference,
                Index(
                    MonthlyData,
                    Value + 1
                ).y,
                Round(
                    slope * Value + intercept,
                    0
                )
            ),
            Amount2: Round(
                slope * Value + intercept,
                0
            ),
            Month: Text(
                DateAdd(
                    firstDate,
                    Value,
                    TimeUnit.Months
                ),
                "yy-mm"
            )
        }
    )
);

5. Line Chart. Insert a line chart into your screen.

- Set the Items property to LineChartData.

- Set the Number of Series to 2.

- Set the Labels to Month

- Set the Series 1 to Amount 1

- Set the Series 2 to Amount 2

- Set the ItemColorSet to something you like


Run the App. Select an item from the ComboBox and click the Submit button. You should see something like this. You now can see the historical monthly sales in red and the trend line projecting out 6 months in advance in orange.

This image shows Microsoft Dynamics 365 Business Central Item number 1928-S historical sales and trend line projecting 6 months into the future
Item 1928-S Historical Sales and Trend Line

Conclusion


As we wrap up this detailed walkthrough, we hope to have illuminated the pathway to leveraging the powerful combination of Python and Microsoft Power Apps to bring predictive analytics into your business ecosystem.


Over the span of this enlightening series, we have guided you from establishing the foundational elements to building a sophisticated analytics application step-by-step. It has been an enriching journey of creating and optimizing a Microsoft Power App that harnesses the potential of predictive analytics to envisage sales trends.


In this final installment, we have focused on mobilizing the components created in earlier blogs. Through meticulous assembly and integrated functioning, these elements have manifested into a Power App, equipped to channel Python's computational strength via a custom connector we cultivated earlier. Together, they facilitate the dynamic forecasting of sales leveraging the slope and intercept derived from historical sales data.


Here, we introduced you to the specifics of:

  • Engaging connectors to tap into pivotal databases and carve out user-friendly interfaces, all set to facilitate intuitive user interactions.

  • Crafting a ‘Submit’ button, a catalyst orchestrating the function of initiating Python script interactions and translating derived statistics into predictive insights.

  • Constructing an interactive line chart, an aesthetic representation of your predictive data, enabling you to visualize the prospective sales landscape over the next six months.

As we conclude our series, we have not only unraveled the intricate processes lying at the heart of predictive analytics but have also empowered you with a tangible toolkit to explore and capitalize on future business opportunities.


Before we bid farewell, we encourage you to run the app, utilizing the actionable insights garnered to steer your business endeavors with renewed foresight and precision. As you select an item from the ComboBox and click the submit button, you are not just triggering a series of scripted actions but embarking on a path of data-driven decision-making, armed with a tool that stands as a testimony to the boundless potential lying at the convergence of Python and Power Apps.


We thank you for being an integral part of this journey towards predictive mastery. As we reach this series’ summit, we leave you with an app ripe with potential, a beacon guiding you towards a future of informed strategies and dynamic business growth.


As you stand on the brink of a transformative business approach, we urge you to dive deeper, explore further, and continue innovating with the robust toolkit you have now mastered.


Here's to the incredible avenues you are set to forge, utilizing the prowess of predictive analytics, Python, and Microsoft Power Apps — the power trio of modern business intelligence. Thank you for joining us on this journey of discovery and innovation; may your business reach new pinnacles of success through data-driven foresight and strategizing.



81 views0 comments

Comments


bottom of page