<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.10.0">Jekyll</generator><link href="https://alkalaji.github.io/feed.xml" rel="self" type="application/atom+xml" /><link href="https://alkalaji.github.io/" rel="alternate" type="text/html" /><updated>2025-10-07T21:04:28+00:00</updated><id>https://alkalaji.github.io/feed.xml</id><title type="html">Alkalaji</title><subtitle>One step at a time</subtitle><entry><title type="html">You’re up and running!</title><link href="https://alkalaji.github.io/test/" rel="alternate" type="text/html" title="You’re up and running!" /><published>2025-10-07T00:00:00+00:00</published><updated>2025-10-07T00:00:00+00:00</updated><id>https://alkalaji.github.io/test</id><content type="html" xml:base="https://alkalaji.github.io/test/"><![CDATA[<p>2.0 Objectives
The primary objectives for implementing the Product Analytics &amp; Engagement Platform are to:
Empower Business Teams: Provide our Product, Marketing, and UX teams with self-service tools to analyze user behavior, reducing dependency on data and engineering teams and shortening the time from question to insight.
Gain Deep Behavioral Insights: Move beyond high-level metrics to understand the “why” behind user actions. This includes identifying friction points in key user journeys, understanding feature adoption, and discovering patterns in user behavior.
Enhance Application Stability and Performance: Proactively monitor, identify, and diagnose technical issues, including application crashes, errors, and performance bottlenecks, to ensure a seamless and reliable user experience.
Capture Qualitative User Feedback: Implement mechanisms to collect direct customer feedback through contextual surveys, Net Promoter Score (NPS), and other rating systems to complement quantitative behavioral data.
Drive User Engagement and Retention: Leverage insights to create personalized, real-time engagement campaigns (e.g., push notifications, in-app messages) that improve user conversion, satisfaction, and long-term loyalty.
Foster a Culture of Experimentation: Enable rapid, data-driven decision-making by equipping teams with A/B testing and remote configuration capabilities, allowing them to test hypotheses and optimize the user experience continuously.
3.0 Success Criteria
The success of this project will be measured by the achievement of new organizational capabilities. We will consider the implementation successful when our teams can demonstrate the following:
Self-Service Analytics: Product managers and marketers can independently and regularly answer their own business questions (e.g., build funnels, segment users, create dashboards) without filing a ticket with data or engineering teams.
Actionable Insight Generation: Teams can move beyond reporting on what happened to articulating why it happened, using the platform’s tools to identify specific points of user friction and opportunity.
Continuous Optimization Workflow: Product teams are regularly and independently running A/B tests to validate hypotheses, leading to a measurable, data-informed product development lifecycle.
Proactive Technical Monitoring: Technical teams can use the platform to significantly reduce the time-to-diagnosis for crashes and performance issues by correlating them with user actions.
Personalized Engagement Capability: Marketing and product teams can successfully design, implement, and automate behavior-triggered communication campaigns directly within the platform.
4.0 Background and Current State
The Bank currently relies on a combination of general application performance monitoring and a centralized data warehouse. While useful, this setup presents several challenges:
Data Latency: Insights are often delayed due to ETL processes, preventing real-time decision-making.
Lack of Self-Service: Business teams (Product, Marketing) have a high dependency on data and engineering teams to answer critical questions, slowing down the innovation cycle.
Limited Behavioral Insight: Our current tools tell us what happened but lack the specialized features to help us understand user actions, friction points, and conversion drop-offs.
5.0 Scope of Work
The selected vendor will be responsible for providing a solution that includes, but is not to be limited to, the following:
Platform &amp; Licensing: Provide access to a robust, secure, and scalable Product Analytics &amp; Engagement Platform for on-premise deployment.
Implementation &amp; Onboarding: Assist with the technical integration of the platform’s SDKs into our iOS, Android, and Web platforms. This includes guiding the setup of initial events, user properties, dashboards, and reports.
Strategic Services &amp; Use Case Implementation: Collaborate with our business teams to assess our key digital products. This includes leading workshops on data modeling for events, defining critical user funnels and journeys, and implementing a set of initial, high-value use cases on the platform.
Training: Provide comprehensive training for both technical and business users to ensure effective adoption and utilization of the platform.
Ongoing Support: Offer technical support, maintenance, and strategic guidance post-implementation.
6.0 Functional &amp; Technical Requirements
Proposals must detail how the solution addresses the following core requirements, which are grouped into three key themes:
6.1 Part 1: Data Capture &amp; Management
User &amp; Session Analytics: Automatic capture of user sessions, device data (OS, version, model), location, and other standard metrics across all digital platforms.
Custom Event Tracking: Ability to define and track a wide range of custom events and user actions within the apps and websites without limitation.
Rich User Profiles: Ability to create persistent user profiles that aggregate all attributes and behavioral events for each user. The platform must support the ability to associate these profiles with a unique, persistent customer identifier provided by the Bank (e.g., from our CRM or core banking system), effectively linking anonymous behavior to known customers.
Crash, Error, and Performance Reporting: Real-time collection and detailed reporting of application crashes and technical errors, including stack traces, user context, and performance monitoring (e.g., ANRs, network latency).
SDKs: Provide well-documented, lightweight, and stable SDKs for iOS, Android, and Web (JavaScript). The SDKs must have a minimal and verifiable impact on application performance, CPU usage, and battery life.
6.2 Part 2: Analysis &amp; Insights
Funnels Analysis: Ability to build and analyze multi-step funnels to understand conversion rates and identify user drop-off points.
Retention &amp; Cohort Analysis: Tools to analyze user retention over time by grouping users into cohorts based on start date or specific behaviors.
Path &amp; Flow Analysis: Visual tools to explore the most common paths and sequences of events that users take through the applications and websites.
Behavioral Segmentation: A powerful segmentation engine to group users based on their attributes, actions (or inaction), and sequences of behavior. Segments should be usable across all analysis and engagement tools.
Dashboards &amp; Reporting: Customizable, shareable dashboards that allow for the visualization of key metrics and trends.
6.3 Part 3: Action &amp; Engagement
Multi-Channel Messaging: Ability to create, target, and send push notifications and in-app messages to user segments.
Behavior-Driven Campaign Automation: A visual workflow builder to create automated, multi-step user journeys and campaigns triggered by user behavior (e.g., an onboarding sequence for new users, a re-engagement campaign for lapsed users).
A/B Testing: A framework for A/B testing user interfaces, features, and messaging to optimize for specific goals across mobile and web.
Surveys &amp; Feedback (NPS, CSAT): Ability to create and trigger a variety of contextual in-app and on-site surveys, including Net Promoter Score (NPS), Customer Satisfaction (CSAT), and open-ended feedback forms.
Remote Configuration: Ability for business teams to change app features, promotions, or UI elements remotely without requiring a new app store release or web deployment.
7.0 Non-Functional Requirements
Security &amp; Compliance: As a financial institution operating in the Kingdom of Saudi Arabia, the platform must adhere to the highest standards of data security and regulatory compliance. Proposals must explicitly detail compliance with the Saudi Personal Data Protection Law (PDPL) and all other relevant local security and regulatory requirements. In addition, please detail any international certifications (e.g., ISO 27001, GDPR compliance).
Deployment Model: The solution must be deployed fully on-premise within the Bank’s own data centers in the Kingdom of Saudi Arabia. Proposals must detail the technical requirements, architecture, and support model for an on-premise deployment. SaaS or Cloud-hosted solutions will not be considered.
Required Environments: The vendor must provide a licensing and support model that includes separate, fully isolated environments for Production and Development/Testing.
Production Environment: For live user data from the official release of our applications and websites.
Development/Testing Environment: A sandbox for developers and QA to test SDK integrations, new event tracking, and platform features without contaminating production data. This environment is also crucial for training purposes.
Scalability &amp; Performance: The solution must be architected to support millions of monthly active users and an unlimited number of monthly events, processing all data with minimal latency.
Integration &amp; APIs: The platform must provide robust APIs for both data import and export. Specifically, describe the ability to integrate with our enterprise systems, including a Data Warehouse, a Customer Data Platform (CDP), and a CRM.
Reliability: Provide details on service level agreements (SLAs), uptime guarantees, and disaster recovery procedures for the on-premise software.
8.0 Proposal Submission Requirements
Vendors are requested to structure their proposals as follows:
Executive Summary: A brief overview of your proposed solution and its key benefits for the Bank.
Company Profile: Company history, relevant experience, and financial stability.
Functional &amp; Technical Response: A detailed, point-by-point response to all requirements listed in Sections 6.0 and 7.0.
Case Studies: At least two case studies of implementations with clients in the banking, financial services, or fintech industry, with a preference for on-premise deployments.
Detailed Project Plan: Provide a comprehensive project plan that includes a proposed timeline with key milestones, a resource allocation plan (detailing both vendor and required Bank personnel), a communication plan for project stakeholders, and a go-live strategy. This plan should cover the full scope outlined in Section 5.0.
Pricing Model: A detailed breakdown of all costs, including licensing, implementation, training, and support. The model should be transparent (e.g., based on events, users, or another metric).
References: Contact information for at least three enterprise clients who can be contacted as references.</p>]]></content><author><name></name></author><summary type="html"><![CDATA[2.0 Objectives The primary objectives for implementing the Product Analytics &amp; Engagement Platform are to: Empower Business Teams: Provide our Product, Marketing, and UX teams with self-service tools to analyze user behavior, reducing dependency on data and engineering teams and shortening the time from question to insight. Gain Deep Behavioral Insights: Move beyond high-level metrics to understand the “why” behind user actions. This includes identifying friction points in key user journeys, understanding feature adoption, and discovering patterns in user behavior. Enhance Application Stability and Performance: Proactively monitor, identify, and diagnose technical issues, including application crashes, errors, and performance bottlenecks, to ensure a seamless and reliable user experience. Capture Qualitative User Feedback: Implement mechanisms to collect direct customer feedback through contextual surveys, Net Promoter Score (NPS), and other rating systems to complement quantitative behavioral data. Drive User Engagement and Retention: Leverage insights to create personalized, real-time engagement campaigns (e.g., push notifications, in-app messages) that improve user conversion, satisfaction, and long-term loyalty. Foster a Culture of Experimentation: Enable rapid, data-driven decision-making by equipping teams with A/B testing and remote configuration capabilities, allowing them to test hypotheses and optimize the user experience continuously. 3.0 Success Criteria The success of this project will be measured by the achievement of new organizational capabilities. We will consider the implementation successful when our teams can demonstrate the following: Self-Service Analytics: Product managers and marketers can independently and regularly answer their own business questions (e.g., build funnels, segment users, create dashboards) without filing a ticket with data or engineering teams. Actionable Insight Generation: Teams can move beyond reporting on what happened to articulating why it happened, using the platform’s tools to identify specific points of user friction and opportunity. Continuous Optimization Workflow: Product teams are regularly and independently running A/B tests to validate hypotheses, leading to a measurable, data-informed product development lifecycle. Proactive Technical Monitoring: Technical teams can use the platform to significantly reduce the time-to-diagnosis for crashes and performance issues by correlating them with user actions. Personalized Engagement Capability: Marketing and product teams can successfully design, implement, and automate behavior-triggered communication campaigns directly within the platform. 4.0 Background and Current State The Bank currently relies on a combination of general application performance monitoring and a centralized data warehouse. While useful, this setup presents several challenges: Data Latency: Insights are often delayed due to ETL processes, preventing real-time decision-making. Lack of Self-Service: Business teams (Product, Marketing) have a high dependency on data and engineering teams to answer critical questions, slowing down the innovation cycle. Limited Behavioral Insight: Our current tools tell us what happened but lack the specialized features to help us understand user actions, friction points, and conversion drop-offs. 5.0 Scope of Work The selected vendor will be responsible for providing a solution that includes, but is not to be limited to, the following: Platform &amp; Licensing: Provide access to a robust, secure, and scalable Product Analytics &amp; Engagement Platform for on-premise deployment. Implementation &amp; Onboarding: Assist with the technical integration of the platform’s SDKs into our iOS, Android, and Web platforms. This includes guiding the setup of initial events, user properties, dashboards, and reports. Strategic Services &amp; Use Case Implementation: Collaborate with our business teams to assess our key digital products. This includes leading workshops on data modeling for events, defining critical user funnels and journeys, and implementing a set of initial, high-value use cases on the platform. Training: Provide comprehensive training for both technical and business users to ensure effective adoption and utilization of the platform. Ongoing Support: Offer technical support, maintenance, and strategic guidance post-implementation. 6.0 Functional &amp; Technical Requirements Proposals must detail how the solution addresses the following core requirements, which are grouped into three key themes: 6.1 Part 1: Data Capture &amp; Management User &amp; Session Analytics: Automatic capture of user sessions, device data (OS, version, model), location, and other standard metrics across all digital platforms. Custom Event Tracking: Ability to define and track a wide range of custom events and user actions within the apps and websites without limitation. Rich User Profiles: Ability to create persistent user profiles that aggregate all attributes and behavioral events for each user. The platform must support the ability to associate these profiles with a unique, persistent customer identifier provided by the Bank (e.g., from our CRM or core banking system), effectively linking anonymous behavior to known customers. Crash, Error, and Performance Reporting: Real-time collection and detailed reporting of application crashes and technical errors, including stack traces, user context, and performance monitoring (e.g., ANRs, network latency). SDKs: Provide well-documented, lightweight, and stable SDKs for iOS, Android, and Web (JavaScript). The SDKs must have a minimal and verifiable impact on application performance, CPU usage, and battery life. 6.2 Part 2: Analysis &amp; Insights Funnels Analysis: Ability to build and analyze multi-step funnels to understand conversion rates and identify user drop-off points. Retention &amp; Cohort Analysis: Tools to analyze user retention over time by grouping users into cohorts based on start date or specific behaviors. Path &amp; Flow Analysis: Visual tools to explore the most common paths and sequences of events that users take through the applications and websites. Behavioral Segmentation: A powerful segmentation engine to group users based on their attributes, actions (or inaction), and sequences of behavior. Segments should be usable across all analysis and engagement tools. Dashboards &amp; Reporting: Customizable, shareable dashboards that allow for the visualization of key metrics and trends. 6.3 Part 3: Action &amp; Engagement Multi-Channel Messaging: Ability to create, target, and send push notifications and in-app messages to user segments. Behavior-Driven Campaign Automation: A visual workflow builder to create automated, multi-step user journeys and campaigns triggered by user behavior (e.g., an onboarding sequence for new users, a re-engagement campaign for lapsed users). A/B Testing: A framework for A/B testing user interfaces, features, and messaging to optimize for specific goals across mobile and web. Surveys &amp; Feedback (NPS, CSAT): Ability to create and trigger a variety of contextual in-app and on-site surveys, including Net Promoter Score (NPS), Customer Satisfaction (CSAT), and open-ended feedback forms. Remote Configuration: Ability for business teams to change app features, promotions, or UI elements remotely without requiring a new app store release or web deployment. 7.0 Non-Functional Requirements Security &amp; Compliance: As a financial institution operating in the Kingdom of Saudi Arabia, the platform must adhere to the highest standards of data security and regulatory compliance. Proposals must explicitly detail compliance with the Saudi Personal Data Protection Law (PDPL) and all other relevant local security and regulatory requirements. In addition, please detail any international certifications (e.g., ISO 27001, GDPR compliance). Deployment Model: The solution must be deployed fully on-premise within the Bank’s own data centers in the Kingdom of Saudi Arabia. Proposals must detail the technical requirements, architecture, and support model for an on-premise deployment. SaaS or Cloud-hosted solutions will not be considered. Required Environments: The vendor must provide a licensing and support model that includes separate, fully isolated environments for Production and Development/Testing. Production Environment: For live user data from the official release of our applications and websites. Development/Testing Environment: A sandbox for developers and QA to test SDK integrations, new event tracking, and platform features without contaminating production data. This environment is also crucial for training purposes. Scalability &amp; Performance: The solution must be architected to support millions of monthly active users and an unlimited number of monthly events, processing all data with minimal latency. Integration &amp; APIs: The platform must provide robust APIs for both data import and export. Specifically, describe the ability to integrate with our enterprise systems, including a Data Warehouse, a Customer Data Platform (CDP), and a CRM. Reliability: Provide details on service level agreements (SLAs), uptime guarantees, and disaster recovery procedures for the on-premise software. 8.0 Proposal Submission Requirements Vendors are requested to structure their proposals as follows: Executive Summary: A brief overview of your proposed solution and its key benefits for the Bank. Company Profile: Company history, relevant experience, and financial stability. Functional &amp; Technical Response: A detailed, point-by-point response to all requirements listed in Sections 6.0 and 7.0. Case Studies: At least two case studies of implementations with clients in the banking, financial services, or fintech industry, with a preference for on-premise deployments. Detailed Project Plan: Provide a comprehensive project plan that includes a proposed timeline with key milestones, a resource allocation plan (detailing both vendor and required Bank personnel), a communication plan for project stakeholders, and a go-live strategy. This plan should cover the full scope outlined in Section 5.0. Pricing Model: A detailed breakdown of all costs, including licensing, implementation, training, and support. The model should be transparent (e.g., based on events, users, or another metric). References: Contact information for at least three enterprise clients who can be contacted as references.]]></summary></entry><entry><title type="html">Starbucks Customers and Offers Interaction Analysis</title><link href="https://alkalaji.github.io/starbucks-data-analysis-final/" rel="alternate" type="text/html" title="Starbucks Customers and Offers Interaction Analysis" /><published>2021-03-19T00:00:00+00:00</published><updated>2021-03-19T00:00:00+00:00</updated><id>https://alkalaji.github.io/starbucks-data-analysis-final</id><content type="html" xml:base="https://alkalaji.github.io/starbucks-data-analysis-final/"><![CDATA[<p>Offers are an important tool for engaging your customers, promoting new offerings, or increasing loyalty. However, targeting a customer with the wrong offer could be useless, or in some cases could bring a negative outcome. Therefore, it is very important to understand the interaction between customers and offers.</p>

<p><img src="https://s11284.pcdn.co/wp-content/uploads/2019/01/starbucks-customer-holding-coffee-cup-700x466.jpg.webp" alt="_config.yml" /></p>

<h2 id="1-project-overview">1. Project Overview</h2>

<p>Starbucks is the world’s largest coffehouse chain in the world. With thousands of stores, and millions of customers, it is important to engage with your customers and understand them. Therefore, Starbucks has an application that makes it easier to know customers better, make it easier for them to order, and to send offers.</p>

<p>However, with the huge number of customers, and multitude of offer options, it is a challenge to understand how customer interact with the offers, and how the offers affct customers behavior.</p>

<p>Therefore, Starbucks provided a simulated dataset that mimics real life offers and customer behavior.</p>

<p>The data contains scio-demographic information about customers, the transactions of customers, and the different types of offers which are:</p>
<ul>
  <li>Informational: An advertisement informing customers about a product</li>
  <li>BOGO: Buy one get one,  where auser needs to spend a certain amount to get a reward equal to that threshold amount</li>
  <li>Discount: a user gains a reward equal to a fraction of the amount spent</li>
</ul>

<p>In this writeup, we document the challenges and motivation behind this problem. Then, we define a a problem statement that will guide our efforts throughout the analysis. After that, we outline the methodology that we will use to solve the defined problem, and what metrics we will use assess the outcomes. Overall, we follow the CRISP-DM approach in our analysis.</p>

<h2 id="2-challenge-and-motivation">2. Challenge and Motivation</h2>

<p>Given the millions of customers and the limitless options of offers, it is a challenge to know which offer to send to what customer. Furthermore, sending the wrong offer to a customer might impact customer’s loyalty, or change the perception of a customer into thinking that those offers are more like spam.</p>

<p>Even from a financial perspective, usually an offer means cost for Starbucks, whether directly or indirectly as outlined above. This uncertainty is what makes this problem challenging, and gives us a great motive to tackle in order to know what to send to whom and understand the dynamics of offer and customers and how they interact and affect each other.</p>

<h2 id="3-problem-statement">3. Problem Statement</h2>

<p>With the outlined challenges that we have, and using the simulated data provided by Starbucks, we need to answer the following question:</p>
<h4 id="1-how-did-starbucks-customers-engage-with-the-different-offers">1. <em>How did Starbucks customers engage with the different offers?</em></h4>
<p>Or put another way, we want to know how our offers performed, the level of engagement they had, and whether they had some utility.</p>

<p><strong>Methodology:</strong> We will build an offer lifecycle, or a customer journey through an offer, if we look at it from the other way around. For Each offer, we will identify all individual transactions that were targetd with that offer. Then we capture all interaction events (receiving, viewing, completing, or ignoring) an offer. After that we calculate percentages for each event types for each offer.</p>

<h4 id="2-how-did-the-offers-affect-or-change-customer-behavior">2. <em>How did the offers affect or change customer behavior?</em></h4>
<p>This differs by offer type, and the change in behavior could be in terms of spending or frequency of transactions.</p>

<p><strong>Methodology:</strong> First of all, we will identify all customer transactions that are not within an offer period. From that we get transaction amounts. Then of those, we identify the consecutive transactions and calculate the time between transactions.</p>

<p>The second part applies to BOGO and discount offers, we do the same but for transactions within an offer where we calculate transaction amounts and time between consecutive transactions.</p>

<p>For informational offers, we calculate the time between the first transaction that the customer commits after viewing the offer and the previous transaction. The idea is to see whether the information offer urged the customer to perform a transaction.</p>

<p>Finally, we use a statistical test, specifically z-test, to assess whether there is a statistical significance in the duration between transactions within and without offers on one hand, and the transaction amount on the other hand.</p>

<h4 id="3-can-we-predict-if-a-customer-will-interact-with-an-offer-and-what-are-the-determining-factors">3. <em>Can we predict if a customer will interact with an offer? and what are the determining factors?</em></h4>
<p>We need to predict given some user info and offer info whether this combination will give a positive outcome. Meaning that offer x suits person y. Furthermore, identify the features are most important to consider when targeting a customer with an offer.</p>

<p><strong>Methodology:</strong> We will start by building a dataset that has customer information, some spending info and offer information. The target variable would be whether the offer was viewed and completed by the customer. This is what we want to train our model on. Then after preparing and processig the data, we spilt to train a random forest classifier to predict whether given information about a custmer and a potential offer what is the likelihood of the customer engagng with the offer.</p>

<p>We will tackle those questions one by one throughout the analysis. But before that we need to define the metrics that will be used to assess viability or success of our proposed solutions.</p>

<h2 id="4-metrics">4. Metrics</h2>

<p>Following are the metrics through which will assess the methodologies and results of the questions in our problem statement:</p>
<h4 id="1-how-did-starbucks-customers-engage-with-the-different-offers-1">1. <em>How did Starbucks customers engage with the different offers?</em></h4>
<p>For each offer, we will identify all individual transactions that were targetd with that offer. Then we will calculate different metrics.</p>

<p><strong>Metrics:</strong> The percentages that will be calculated will be our metrics to assess how the offers performed. Namely, we will have the following metrics to asess, for each offer:</p>
<ul>
  <li>
    <p>Viewing percentage: What percentage has the offer been viewed. Higher value means that at least the offer reached the customer
<strong>&lt;div align="center"&gt; viewing% = views_count/sent_count &lt;/div&gt;</strong></p>
  </li>
  <li>
    <p>Completed percentage: The percentage an offer has been completed. This will be further broken down in the following two metrics
<strong>&lt;div align="center"&gt; completed% = completed_count/sent_count &lt;/div&gt;</strong></p>
  </li>
  <li>
    <p>Viewed and completed percentage: The percentage an offer has been completed after being viewed. This is important because it means that we had a fruitful engagement to some extent.
<strong>&lt;div align="center"&gt; viewed_and_completed% = viewed_and_completed_count/sent_count &lt;/div&gt;</strong></p>
  </li>
  <li>
    <p>Completed but NOT viewed percentage: The percentage an offer has been completed without being viewed. High percentage indicates that the offer was too easy to complete, and that customers completed it unintentionally even. So it might have limited impact.
<strong>&lt;div align="center"&gt; completed_not_viewed% = (completed_count - viewed_and_completed_count)/sent_count &lt;/div&gt;</strong></p>
  </li>
  <li>
    <p>Viewed and ignored percentage: The percentage an offer has been viewed, but the customer did not complete. This is also important because it means that despite seeing the offer, to some extent the customer either had no interest in the offer, or it was too difficult to complete.
<strong>&lt;div align="center"&gt; viewed_and_ignored% = (views_count-viewed_and_completed_count)/sent_count &lt;/div&gt;</strong></p>
  </li>
</ul>

<h4 id="2-how-did-the-offers-affect-or-change-customer-behavior-1">2. <em>How did the offers affect or change customer behavior?</em></h4>
<p>Here we go through all transactions to identify those within an offer and those outside. Then we statistically test if there is some significant differnece between the two.</p>

<p><strong>Metrics:</strong> Given that we are using z-test we will on two main values:</p>
<ul>
  <li>p-value: where if p-value &lt; 0.05, then there is a statistically significant difference. Meaning that there is a significant impact by the offer on customer behavior</li>
  <li>z-score: This is what gives us the magnitude of difference in terms of standard deviations difference, and whether it is positive or negative</li>
</ul>

<h4 id="3-can-we-predict-if-a-customer-will-interact-with-an-offer-and-what-are-the-determining-factors-1">3. <em>Can we predict if a customer will interact with an offer? and what are the determining factors?</em></h4>
<p>In comparison to the previous one, this is straight forward.</p>

<p><strong>Metrics:</strong> Since this is a classification problem we will be looking at the following metrics:</p>
<ul>
  <li>Accuracy: to get an overall sense of how the model has preformed. However, this is not a conclusive metric especially with imbalance</li>
  <li>F1 score: since this metric takes precision and recall into consideration. So it is necessary to look at this metric along with accuracy</li>
  <li>Precision and recall: just to get an idea of where might be some bias or other fitting issues with the model</li>
</ul>

<h2 id="5-data-understanding">5. Data Understanding</h2>
<p><strong>Note: The source of the description below comes from the provided information about the datasets</strong></p>

<p>The data that will be used is provided in the following three files:</p>
<ul>
  <li>portfolio.json - containing offer ids and meta data about each offer (duration, type, etc.)</li>
  <li>profile.json - demographic data for each customer</li>
  <li>transcript.json - records for transactions, offers received, offers viewed, and offers completed</li>
</ul>

<p>Here is the schema and explanation of each variable in the files. We also look at the head of each of the three data files, their shape and if there is any missing values</p>

<p><strong>portfolio.json</strong></p>
<ul>
  <li>id (string) - offer id</li>
  <li>offer_type (string) - type of offer ie BOGO, discount, informational</li>
  <li>difficulty (int) - minimum required spend to complete an offer</li>
  <li>reward (int) - reward given for completing an offer</li>
  <li>duration (int) - time for offer to be open, in days</li>
  <li>channels (list of strings)</li>
</ul>

<p><img src="/images/starbucks/1.png" alt="_config.yml" /></p>

<p><strong>profile.json</strong></p>
<ul>
  <li>age (int) - age of the customer</li>
  <li>became_member_on (int) - date when customer created an app account</li>
  <li>gender (str) - gender of the customer (note some entries contain ‘O’ for other rather than M or F)</li>
  <li>id (str) - customer id</li>
  <li>income (float) - customer’s income</li>
</ul>

<p>It was mentioned that missing age values where encded as 118 in the dataset. Hence, we will set those values to nan</p>

<p><img src="/images/starbucks/2.png" alt="_config.yml" /></p>

<p>Only profile dataset contains missing values. We can see that around 12.8% of demographics data is missing. We will decide how to handle this as we have a further look at the data</p>

<p><strong>transcript.json</strong></p>
<ul>
  <li>event (str) - record description (ie transaction, offer received, offer viewed, etc.)</li>
  <li>person (str) - customer id</li>
  <li>time (int) - time in hours since start of test. The data begins at time t=0</li>
  <li>value - (dict of strings) - either an offer id or transaction amount depending on the record</li>
</ul>

<p><img src="/images/starbucks/3.png" alt="_config.yml" /></p>

<h2 id="6-data-preparation-and-exploration">6. Data preparation and exploration</h2>
<p>In this section we will perform the following data processing steps on each dataset:</p>

<h3 id="a-portfolio-dataset">a. “portfolio” dataset</h3>
<p>The portfolio data is quite straight forward having only 10 rows corresponding to the 10 offers. We do some basic feature engineering. This makes it easier for any modelling step later on. We do the following steps:</p>
<ul>
  <li>One-hot-encode channels</li>
  <li>One-hot-encode offers</li>
  <li>Give code names for offers for easier readability</li>
</ul>

<p><img src="/images/starbucks/4.png" alt="_config.yml" /></p>

<p>Then we look at how many times each channel was used and the offer types:</p>

<p><img src="/images/starbucks/5.png" alt="_config.yml" /></p>

<p>We can see that email channel is used with all offers, so it loses value in terms of modelling, because it does not carry any discriminatory value!</p>

<p>This should not be confused with the potential importance of it as a channel, but again not for modelling purposes.</p>

<p><img src="/images/starbucks/6.png" alt="_config.yml" /></p>

<p>Clearly we have 4 buy-one-get-one, 4 discount offers, and 2 informational</p>

<h3 id="b-profile-dataset">b. “profile” dataset</h3>
<p>First, for preprocessing we will perform the following steps:</p>
<ul>
  <li>Convert ‘became_member_on’ to datetime</li>
  <li>Replace ‘became_member_on’ with ‘year_of_membership’</li>
  <li>Replace missing gender values with ‘U’ for unknown</li>
</ul>

<h4 id="looking-at-the-dstribution-of-each-column-and-seeing-if-there-are-outliers-within-the-data">Looking at the dstribution of each column, and seeing if there are outliers within the data</h4>

<p><img src="/images/starbucks/7.png" alt="_config.yml" /></p>

<p>We will decide what to do with the missing values denoted as ‘U’ later on. 
However, looking at M and F values, there is some imbalance, but it is not severe. However we will have to be careful when splitting the data and modelling</p>

<p><img src="/images/starbucks/8.png" alt="_config.yml" /></p>

<p>The data seems to be normally distributed with some skewness. One reason is that the application contains ages starting from 18 years old. Then we look at the boxplot to see if there are any outliers:</p>

<p><img src="/images/starbucks/9.png" alt="_config.yml" /></p>

<p>We don’t see any extreme valus or severe skewness other than slight skewness to the right. 
Also, from the above boxplot, we can see that 50% of our customers fall between ages around 42 and 65</p>

<p>Then we look at Histogram for our newly created feature ‘year_of_membership’</p>

<p><img src="/images/starbucks/10.png" alt="_config.yml" /></p>

<p>We can see that 50% of customers are in their first year of membership. 40% are in their 2nd or 3rd year</p>

<p>Next, we look at Income histogram ignoring nan values:</p>

<p><img src="/images/starbucks/11.png" alt="_config.yml" /></p>

<p>Now we examine for outliers:</p>

<p><img src="/images/starbucks/12.png" alt="_config.yml" /></p>

<p>Again here we don’t outliers and there is some skewness slightly to the right. 50% of customers have an income between 50k to 80k.</p>

<h4 id="data-correlations">Data correlations</h4>
<p>Now, we can start looking at the correlation matrix for profile features</p>

<p><img src="/images/starbucks/13.png" alt="_config.yml" /></p>

<p>The correlation heatmap suggests some positive correlation between age and income, which is expected and can be seen better in the next set of charts. However, neither age nor income show correlation with year_of_membership feature.</p>

<p>Then we look at the scatterplot matrix to gain further insights</p>

<p><img src="/images/starbucks/14.png" alt="_config.yml" /></p>

<p>Given the charts above, I have the following comments:</p>
<ul>
  <li>The age vs income charts show a positive correlation. However, clearly it shows how synthetic this dataset is. As in real life we won’t have those clear borders.</li>
  <li>Male income is right skewed</li>
  <li>For higher incomes, it seems that female customers or more prominent</li>
  <li>There is nothing much noticeable regarding O and null gender records distributions. Therefore, we will drop records with nan value for demographic info</li>
</ul>

<h5 id="as-mentioned-we-will-be-removing-customer-records-with-missing-data-however-better-way-to-do-it-is-to-check-using-a-statistical-test-specifically-the-distribution-of-those-records-with-missing-values-vs-with-non-missing-values-and-see-if-there-is-any-statistical-significance-in-the-difference-between-the-two">As mentioned, we will be removing customer records with missing data. However, better way to do it is to check using a statistical test specifically the distribution of those records with missing values vs with non-missing values and see if there is any statistical significance in the difference between the two</h5>

<h3 id="c-transcript-dataset">c. “transcript” dataset</h3>
<p>This is where the bulk of the preprocessing work was done as we were deling with the transactions. First we did some initial preprocessing steps by replacing ‘amount’ column and creating 3 columns: offer_id, amount, reward</p>

<h4 id="looking-at-the-dstribution-of-each-column-and-seeing-if-there-are-outliers-within-the-data-1">Looking at the dstribution of each column, and seeing if there are outliers within the data</h4>

<p>Starting with transaction amounts</p>

<p><img src="/images/starbucks/15.png" alt="_config.yml" /></p>

<p>The shape of this histogram suggests that we have some extreme values. Therefore, we create a boxplot</p>

<p><img src="/images/starbucks/16.png" alt="_config.yml" /></p>

<p>We can clearly see that there are extreme values in the data. Having another look without those extreme values:</p>

<p><img src="/images/starbucks/17.png" alt="_config.yml" /></p>

<p>Given the a value of 45 to be a reasonable cutoff value for transaction amount, we found that there are 863 extreme values (above 45). Thereforem, given the small number of outliers in comparison to 306534 transaction, we will drop those values. Now we have another look at the histogram:</p>

<p><img src="/images/starbucks/18.png" alt="_config.yml" /></p>

<p>This diagram has an interesting shape. I believe it is mostly due to the pricing of items at Starbucks, and the bump in the chart could be attributed to combination of items purchased. To confirm or refute some pricing data would be required.</p>

<h4 id="data-correlations-1">Data correlations</h4>
<p>To get a better picture, we look at the correlation between the different features. However, before that we join the transactions with some socio-demographic data:</p>

<p><img src="/images/starbucks/19.png" alt="_config.yml" /></p>

<p>From the above correlation matrix we can observe the follwing:</p>
<ul>
  <li>There’s a very strong positive correlation between income and the transaction amount mean value</li>
  <li>However, there’s a negative correlation with less magnitude between income and number of transactions</li>
  <li>The year of membership feature shows a positive correlation with the umber of transactions (remomber that this transactions data is for 1 month only)</li>
  <li>Age is positively correlated with the mean transaction amount value. This is expected since we observed earlier that age is positively correlated with income positively</li>
</ul>

<p>We take things a tep further by looking at the scatterplot matrix:</p>

<p><img src="/images/starbucks/20.png" alt="_config.yml" /></p>

<p>The scatterplot matrix above highlights some of the observations we noticed in the correlation matrix above, in addition to highlighting the following:</p>
<ul>
  <li>Male total transaction amount is extremely right skewed, whereas for female customers it shows less skewness. We observe that a majority of the male customers fall in the lower end of the total amount spent spectrum</li>
  <li>The same applies to avergae transaction amount where male are the lower end of the spectrum and females exceeding them on the higher end</li>
  <li>When it come to number of transactions the distribution seems to be very similar. The higher shaded area for males can be attributed to the data imbalance</li>
  <li>Regarding users which are not labelled as ‘M’ or ‘F’, this includes ‘O’ and nan, most transactions amount and count are on the very lower end of the spectrum</li>
</ul>

<h2 id="7-data-analysis-modelling-and-evaluation">7. Data Analysis, modelling, and evaluation</h2>
<p>In this section we will analyze the data in order to answer the different business questions that were posed earlier. However, before we get to the questions one by one, we will need to process transcript data to identify how customers interact with the offers, and how offers affect customer behavior.</p>

<p>For that we built a rigorous function to process transactions. The logic in the ‘process_transactions’ function produces two main data frames, and 5 other data frames containing raw transaction metrics:</p>
<ol>
  <li><strong>offers_trx_details:</strong> This DataFrame is concerned with offers, how users interact with them, and the transactions that we assume are associated with them, as follows:
    <ul>
      <li>For all offers received we calculate how long it took to view the offer and how long to complete if applicable</li>
      <li>For each person for each offer (bogo or discount) we get all the transactions that happened between offer reception and completion. For those specific transactions we calculate avg time between transactions, mean transaction amount, and how many</li>
      <li>For informational offers we calculate the time from last transaction before the offer was viewed to the first transaction after the offer is viewed</li>
    </ul>
  </li>
  <li><strong>normal_trx_details:</strong> Those are transactions that took place outside the conditions outlined above. So they do not fall between an offer view and completion</li>
  <li><strong>raw_within_offer_trx_amounts:</strong> individual transaction amounts that took place during an offer</li>
  <li><strong>raw_within_offer_trx_durations:</strong> duration between consecutive transactions during an offer</li>
  <li><strong>raw_first_trx_from_last_durations:</strong> the duration between first commited transaction after receiving an information offer and last transaction</li>
  <li><strong>raw_without_offer_trx_amounts:</strong> individual transaction amounts that took place outside any offer</li>
  <li><strong>raw_without_offer_trx_durations:</strong> duration between consecutive transactions that took place outside offers</li>
</ol>

<p>The columns description for each of the two main dataframes is as follows:</p>
<ol>
  <li>offers_trx_details:
    <ul>
      <li><strong>person_id</strong>: Person id</li>
      <li><strong>offer_id</strong>: Offer id</li>
      <li><strong>viewed_time</strong>: the time difference between viewing and offer and receiving it. If not viewed it would be nan</li>
      <li><strong>completed_time</strong>: the time difference between completing an offer and viewing it, in case it was viewed. If not, then from receiving it. If not completed it would be nan</li>
      <li><strong>first_trx_time_from_last_trx</strong>: the time from last transaction before the offer was viewed to the first transaction after the offer is viewed</li>
      <li><strong>trx_count</strong>: # of transactions between view/reception and completion</li>
      <li><strong>avg_trx_amount</strong>: avergae transaction amount for the aforementioned transactions</li>
      <li><strong>avg_time_btwn_trx</strong>: average time between transactions for the aforementioned transactions</li>
    </ul>
  </li>
  <li>normal_trx_details:
    <ul>
      <li><strong>person_id</strong>: Person id</li>
      <li><strong>trx_count</strong>: # of transactions that are not between view/reception and completion</li>
      <li><strong>avg_trx_amount</strong>: avergae transaction amount for the aforementioned transactions</li>
      <li><strong>avg_time_btwn_consec_trx</strong>: average time between only consecutive transactions for the aforementioned transactions</li>
    </ul>
  </li>
</ol>

<p>Now we can start the analysis, modeling and evaluation for each one of our questions.</p>

<h2 id="q1-how-did-starbucks-customers-engage-with-the-different-offers">Q1. How did Starbucks customers engage with the different offers?</h2>
<p>Each offer has a lifecycle, and goes through different stages depending on the offer type, from being received to viewed or ignore, to completed. Also, we need to measure the effectivess of an offer. This can be measured in many ways, whether financial, or impact on future purchases, or just the engagement of customers.</p>

<p>For the purpose of this question, we will focus on customer engagement, and how customers interacted with each offer in terms of viewing and completing.</p>

<p>We will start by creating an aggregated dataframe from ‘aggregated_offers_trx_details’. For each offer we will calculate the number of receipients, views, completion, or lack thereof. We create offer level aggregation for the transaction details metrics related to:</p>
<ul>
  <li>Vieweing counts and percentages</li>
  <li>Completion counts and percentages</li>
  <li>Transaction amounts</li>
  <li>Duration between transactions</li>
</ul>

<p>Now we create a bunch of charts to look at the different metrics mentioned above:</p>

<p>Starting with the viewing percentage for each offer:</p>

<p><img src="/images/starbucks/viewed.png" alt="_config.yml" /></p>

<p>We can notice that 6 out of 10 offers were viewed by around 80% or more of customers which seems very good. However, the offers (bogo_3, discount_1, and discount_4) had less than 50% viewing, which suggests that it did not attract customers as the other ones did.</p>

<p>Then we look at the performance of offers in terms of being viewed and completed, and being completed WITHOUT having been viewed:</p>

<p><img src="/images/starbucks/viewed_completed.png" alt="_config.yml" /></p>

<p><img src="/images/starbucks/completed_not_viewed.png" alt="_config.yml" /></p>

<p>We notice that around 30% of those who completed bogo_3, discount_1, and discount_4 did it without even viewing the offer. This means that either way customers would have continued with their purchaing habits without the business spending money on those offers. However, this cannot be concluded unless we know the motivation of this offer. It might not be purely financial, there might be loyalty aspects, or some utility function that is used to measure success of an offer.</p>

<p>Furthermore, surprisingly, those three offers (bogo_3, discount_1, and discount_4) that were viewed the least (less than 50%), are the ones that were completed without being viewed the most. This is unclear and could be due to the way the data was synthesized or some other factors that require clarification from business, because the difficulty of those offers is above average.</p>

<p>After all, the offer that seems to have done the best in terms of engagement is “discount_3”. Customers seem to have engaged with it in terms of views, completion, and the relatively lower number of those who viewed it and ignored it. On the other hand, “discount_1” seems to have done the poorest in terms of customer engagement, and being completed without customers even noticing it.</p>

<p>To put it all together, from the charts above we can observe the following:</p>
<ul>
  <li>6 out of 10 offers were viewed by around 80% or more of customers which seems very good</li>
  <li>Around 30% of those who completed bogo_3, discount_1, and discount_4 did it without even viewing the offer. This means that either way customers would have continued with their purchaing habits without the business spending money on those offers. However, this cannot be concluded unless we know the motivation of this offer. It might not be purely financial, there might be loyalty aspects, or some utility function that is used to measure success of an offer</li>
  <li>Surprisingly, those three offers (bogo_3, discount_1, and discount_4) that were viewed the least (less than 50%), are the ones that were completed without being viewed the most. This is unclear and could be due to the way the data was synthesized or some other factors that require clarification from business, because the difficulty of those offers is above average</li>
  <li>The offer that seems to have done the best in terms of engagement is “discount_3”. Customers seem to have engaged with it in terms of views, completion, and the relatively lower number of those who viewed it and ignored it</li>
</ul>

<p>The following chart concisely summarizes the lifecycle of those 2 offers:</p>

<p><img src="/images/starbucks/journey.png" alt="_config.yml" /></p>

<p>This kind of diagrams gives a very good view of how each offer is performing. Of course we can add other measures such as financial, or loyalty, if we have data to support.</p>

<h2 id="q2-how-did-the-offers-affect-or-change-customer-behavior">Q2. How did the offers affect or change customer behavior?</h2>
<p>In the first question we looked at how the offers performed in terms of customer engagement. Now, we want to measure if those offers changed the customer behavior. Of course the condition for transactions within an offer is that the offer has been viewed, and completed in the case of bogo and discount.</p>

<p>We will measure this as follows:</p>
<ol>
  <li>For informational offers, we will check if the duration that users take to make the first purchase after the informational offer is reduced in comparison to the usual duration that customers take between consecutive purchases that are not under any offer</li>
  <li>For bogo and discount offers, we will check if the duration between purchase instances for transactions within an offer is different from the duration between normal consecutive transactions that are not within an offer period</li>
  <li>Finally, we will check if the there is a statistically significant change in transaction amounts during an offer (bogo or discount) from outside an offer</li>
</ol>

<p>Those tests will be conducted using z-test, and then we measure the statistical significance of the result. We choose z-test for the following reasons:</p>
<ul>
  <li>We have a very large sample size</li>
  <li>The data points are independent from each other</li>
  <li>Even though ideally the samples should have a normal distribution, given the large sample size this should be accepted</li>
</ul>

<p>Let’s start with the tests one by one:
<strong>1. Starting with our test regarding the effect of informational offers:</strong></p>

<p>We define our hypotheses:</p>
<ul>
  <li><strong>H0:</strong> The informational offer <em>does NOT</em> have an effect on the duration customers take until their next purchase</li>
  <li><strong>H1:</strong> The informational offer <em>DOES</em> have an effect on the duration customers take until their net purchase</li>
</ul>

<p><img src="/images/starbucks/info_duration.png" alt="_config.yml" /></p>

<p>Only by looking at the chart above and the mean values we can see how different the two samples are. Of course, the z-test confirms that informational offer has an effect. However, it is suprisingly counter-intuitive. Because this suggests that customers take longer time to make a purchase after receiving an informational offer in comparison to the time they usually take between transactions.</p>

<p>Nonetheless, this could be due to the time informational offers are beng set. E.g. late at night, or some time in the weekend. This requires further investigation with business, and complimentary data to shed more light.</p>

<p><strong>2. Testing the effect of BOGO and discount offers on transaction DURATIONS:</strong></p>

<p>AGaine we define the hypotheses for our statistical test:</p>
<ul>
  <li><strong>H0:</strong> The BOGO and discout offers <em>DO NOT</em> have an effect on the duration between customer’s consecutive purchase instances during an offer</li>
  <li><strong>H1:</strong> The BOGO and discout offers <em>DO</em> have an effect on the duration between customer’s consecutive purchase instances during an offer</li>
</ul>

<p><img src="/images/starbucks/duration.png" alt="_config.yml" /></p>

<p>Clearly, from the mean values we see above and the ztest, during an offer customers do purchase more frequently. I.e. the duration between purchase transactions is reduced!</p>

<p>Of course if needed we can dig deeper to see which specific offer did best</p>

<p><strong>3. Testing the effect of BOGO and discount offers on transaction AMOUNTS:</strong></p>

<p>For our final test, we define the hypotheses:</p>
<ul>
  <li><strong>H0:</strong> The BOGO and discout offers <em>DO NOT</em> have an effect on the purchase transaction amount during an offer</li>
  <li><strong>H1:</strong> The BOGO and discout offers <em>DO</em> have an effect on the purchase transaction amount during an offer</li>
</ul>

<p><img src="/images/starbucks/amounts.png" alt="_config.yml" /></p>

<p>Again, this clearly shows that during an offer customers spend more per transaction, and the amount difference is statistically significant.</p>

<p>To summarise:</p>
<ul>
  <li>Informational offers seem to cause customers to take longer time to make a purchase after receiving an informational offer in comparison to the time they usually take between transactions</li>
  <li>During an offer (BOGO, or discount) customers do purchase more frequently. I.e. the duration between purchase transactions is reduced</li>
  <li>During an offer (BOGO, or discount) customers spend more per transaction, and the amount difference is statistically significant</li>
</ul>

<h2 id="q3-can-we-predict-if-a-customer-will-interact-with-an-offer-and-what-are-the-determining-factors">Q3. Can we predict if a customer will interact with an offer? and what are the determining factors?</h2>
<p>For this purpose, we created a dataset containing:</p>
<ul>
  <li>Socio-demographic information about customers</li>
  <li>Offer details</li>
  <li>Customer usual spending on transactions</li>
</ul>

<p>To build this dataset, we joined data from:</p>
<ul>
  <li>profile</li>
  <li>portfolio</li>
  <li>normal_trx_details</li>
  <li>offers_trx_details</li>
</ul>

<p>Then we performed one-hot encoding for categorical features such as gender, and removed the irrelevant columns for modelling such as ids and some other features that won’e be used in the model. Also, since I will be using a random forest classifier, I did not normalize the data, and decided not to got with binning the values. After that, we added a flag of whether each customer viewed and completed the offer. This will be our target for prediction.</p>

<p>This dataset was used to train and evaluate a machine learning model that will try to predict given customer and offer info, whether the customer will view and complete this offer or not</p>

<p><img src="/images/starbucks/ml-model.png" alt="_config.yml" /></p>

<p>We started with a random forest model with the default parameters, e.g.:</p>
<ul>
  <li>‘n_estimators’: 100</li>
  <li>‘min_samples_leaf’: 1</li>
  <li>‘min_samples_split’: 2</li>
</ul>

<p>The reported performance metrics were:</p>
<ul>
  <li>Accuracy: 0.70</li>
  <li>F1 score: 0.65</li>
  <li>Precision: 0.65</li>
  <li>Recall: 0.64</li>
</ul>

<p>This is reasonable given that we did not configure any prameters. The f1-score and precision and recall suggest that the model did not over fit despite the slight imbalance in labels. However, we will try to improve the performance of the model by tuning the parameters. We will use GridSearchCV to search through a different parameters and perform cross validation to make sure that the result we got was not a fluke and that our model will generalize well.</p>

<p>The parameter grid of our search was:</p>

<p><img src="/images/starbucks/21.png" alt="_config.yml" /></p>

<p>The built model has slightly improved and performed relatively well with an accuracy of around 73%. Of course, again we did not rely only on accuracy it can be prone to biases and imbalance. Therefore, we evaluated the model with f1-score, and it reported a value of 0.68, which is very reasonable given the accuracy.</p>

<p>The parameters for our best model are:</p>
<ul>
  <li>‘max_depth’: 10</li>
  <li>‘max_features’: ‘auto’</li>
  <li>‘min_samples_leaf’: 2</li>
  <li>‘min_samples_split’: 2</li>
  <li>‘n_estimators’: 200</li>
</ul>

<p>This model now enables us to infer whether a customer will engage with an offer or not before sending out the offer.</p>

<p>Finally, let’s identify what are the most important features determined by the model that affect whethe a customer will engage with an offer. One way to do that is by looking at features importance:</p>

<p><img src="/images/starbucks/features_imp.png" alt="_config.yml" /></p>

<p>We can clearly see that individual attributes are the most important features, followed by offer properties. Those features are:</p>
<ul>
  <li>avg_trx_amount: The average spending amount per transaction of a customer</li>
  <li>year_of_membership: How long the customer has been a member</li>
  <li>social_ch: whether the offer was sent of a social media channel or not</li>
  <li>income: Customer’s income</li>
  <li>age: Customer’s age</li>
  <li>reward: The reward amount of the offer</li>
  <li>difficulty: Offer’s difficulty</li>
  <li>duration: How long the offer will run for</li>
  <li>mobile_ch: Whether the offer was sent over the mobile channel</li>
  <li>If the offer is of type buy-one-get-one</li>
</ul>

<p>Now let’s look at how those features are correlated with the outcome and with each other. However, we will limit it only to 5 features for ease of visualization:</p>

<p><img src="/images/starbucks/scatterplot.png" alt="_config.yml" /></p>

<p>Focusing on the diagonal charts, we can observe the following:</p>
<ul>
  <li>Average transaction amount is positively correlated with likelihood of participating</li>
  <li>Years of membership that are between 2 and 3 are more positively correlted with a positive outcome. Less or more years are the other way around. Especially newer members.</li>
  <li>Social channel shows a positive correlation</li>
  <li>The higher the income the more likely someone seems to participate in an offer</li>
</ul>

<h2 id="8-justification">8. Justification</h2>
<p>Looking back at the most important decisions we have made throughtout this analysis, we can highlight the following:</p>
<ul>
  <li>The rigorous function “process_transactions”, despite how big the function is, I preferred to keep it all in one function to reduce the overall number of loops. Furthermore, there were so many conditions to keep track of to qualify a transaction to be considered as part of an offer, or just a normal transaction, and the consecutiveness of transactions. The level of detail that this function provides can open up multiple other areas to explore in the data.</li>
  <li>For question two we use choose z-test for the following reasons:
    <ul>
      <li>We have a very large sample size. Each sample consists of multiple thousand observations</li>
      <li>The data points are independent from each other</li>
      <li>Given the large sample size, we can relax the condition or assumption that the data must benormally distributed</li>
    </ul>
  </li>
  <li>The rationale behind our decisions for question 3 are as follows:
    <ul>
      <li>I chose Random Forest because it is less prone to over fitting, due to the way it splits the data and builds multiple trees. Also, does not require normalizing or regularizing the data before feeding it into the model. Finally, does not necessarily require data bining, since it can decide on different ranges for each branch or split</li>
      <li>We use GridSearchCV, first of all to find a better set of parameters for our model. We could have gobe randomized search for faster results, but the calculation was affordable with gridsearch. Also very importantly, we wanted to make use of the cross-validation that it does so that we ensure that we do not overfit our model</li>
      <li>Regarding evaluation metrics of the model, we did not only rely on accuracy, but we also looked at f1-score which takes into consideration precision and recall, and works better for datasets with imbalanced labels</li>
    </ul>
  </li>
</ul>

<h2 id="9-conclusion-and-reflections">9. Conclusion and Reflections</h2>

<p>In this exercise we analyzed the customers and offers data from Starbucks. We tried to answer the different business questions.</p>

<p>We started our analysis by trying to look at how customers interacted with the different kinds of offer. We measured what we called customer engagement. Then we looked at the interaction with each offer an offer lifecycle and a customer journey. We also identified the best performing offers and the least peforming according to our definition.</p>

<p>Then we looked at the problem from another angle. We tried to see how offers impacted customer behavior. We followed a statistical method to assess the significance of this effect, and we found the indeed offers affect customer spending and the frequency of transactions. We found that information offers seemed to have a negative impact on the duration until next transaction. On the other hand, BOGO and discount offers increase the average transaction amound and the frequency of transactions during an offer.</p>

<p>Finally, we built a predictive model to help us identify whether an offer would suit a certain customer. It had a reasonable accuracy with around 70%. Also, the model gave us an insgiht at what the important features are in determining whether a customer will enage with an offer or not. The two most important indicators where average customer spending and years of membership.</p>

<p>The work can be further improved with some extra sources of data such as item pricing, or through some further engineering of some of the features. Also, we can model the whole data and problems as a time series problem with sequences of transaction. However, this would require us have some further information about the time of transactions to correlate with weekdays, weekends, and time.</p>]]></content><author><name></name></author><summary type="html"><![CDATA[Offers are an important tool for engaging your customers, promoting new offerings, or increasing loyalty. However, targeting a customer with the wrong offer could be useless, or in some cases could bring a negative outcome. Therefore, it is very important to understand the interaction between customers and offers.]]></summary></entry><entry><title type="html">Starbucks Customers and Offers Interaction Analysis</title><link href="https://alkalaji.github.io/starbucks-data-analysis-technical/" rel="alternate" type="text/html" title="Starbucks Customers and Offers Interaction Analysis" /><published>2021-03-19T00:00:00+00:00</published><updated>2021-03-19T00:00:00+00:00</updated><id>https://alkalaji.github.io/starbucks-data-analysis-technical</id><content type="html" xml:base="https://alkalaji.github.io/starbucks-data-analysis-technical/"><![CDATA[<p>Offers are an important tool for engaging your customers, promoting new offerings, or increasing loyalty. However, targeting a customer with the wrong offer could be useless, or in some cases could bring a negative outcome. Therefore, it is very important to understand the interaction between customers and offers.</p>

<p><img src="https://s11284.pcdn.co/wp-content/uploads/2019/01/starbucks-customer-holding-coffee-cup-700x466.jpg.webp" alt="_config.yml" /></p>

<p>In this report go through the analysis of the data provided by Starbucks simulating customer behavior in response to offers through their mobile app. We follow CRISP-DM to analyze the data and gain insights into how customers interact with those offers. We will also answer the business questions raised in the next section</p>

<h2 id="1-business-understanding">1. Business understanding</h2>

<p>Starbucks regularly sends offers to different customers. Eachoffer has its own duration and condition to fulfill. Those offers fall under the following categories:</p>
<ul>
  <li>Informational: An advertisement informing customers about a product</li>
  <li>BOGO: Buy one get one,  where auser needs to spend a certain amount to get a reward equal to that threshold amount</li>
  <li>Discount: a user gains a reward equal to a fraction of the amount spent</li>
</ul>

<p>Through the datasets provided we will try to answer the following business questions:</p>
<ol>
  <li><em>How did Starbucks customers engage with the different offers?</em></li>
  <li><em>How did the offers affect or change customer behavior?</em></li>
  <li><em>Can we predict if a customer will interact with an offer?</em></li>
</ol>

<h2 id="2-data-understnding">2. Data understnding</h2>

<p><strong>Note: The source of the description below comes from the provided information about the datasets</strong></p>

<p>The data that will be used is provided in the following three files:</p>
<ul>
  <li>portfolio.json - containing offer ids and meta data about each offer (duration, type, etc.)</li>
  <li>profile.json - demographic data for each customer</li>
  <li>transcript.json - records for transactions, offers received, offers viewed, and offers completed</li>
</ul>

<p>Here is the schema and explanation of each variable in the files:</p>

<p><strong>portfolio.json</strong></p>
<ul>
  <li>id (string) - offer id</li>
  <li>offer_type (string) - type of offer ie BOGO, discount, informational</li>
  <li>difficulty (int) - minimum required spend to complete an offer</li>
  <li>reward (int) - reward given for completing an offer</li>
  <li>duration (int) - time for offer to be open, in days</li>
  <li>channels (list of strings)</li>
</ul>

<p><strong>profile.json</strong></p>
<ul>
  <li>age (int) - age of the customer</li>
  <li>became_member_on (int) - date when customer created an app account</li>
  <li>gender (str) - gender of the customer (note some entries contain ‘O’ for other rather than M or F)</li>
  <li>id (str) - customer id</li>
  <li>income (float) - customer’s income</li>
</ul>

<p><strong>transcript.json</strong></p>
<ul>
  <li>event (str) - record description (ie transaction, offer received, offer viewed, etc.)</li>
  <li>person (str) - customer id</li>
  <li>time (int) - time in hours since start of test. The data begins at time t=0</li>
  <li>value - (dict of strings) - either an offer id or transaction amount depending on the record</li>
</ul>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># Import packages
</span><span class="kn">import</span> <span class="nn">pickle</span>
<span class="kn">import</span> <span class="nn">pandas</span> <span class="k">as</span> <span class="n">pd</span>
<span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="n">np</span>
<span class="kn">import</span> <span class="nn">math</span>
<span class="kn">import</span> <span class="nn">json</span>
<span class="kn">import</span> <span class="nn">matplotlib.pyplot</span> <span class="k">as</span> <span class="n">plt</span>
<span class="kn">import</span> <span class="nn">seaborn</span> <span class="k">as</span> <span class="n">sns</span>
<span class="kn">from</span> <span class="nn">tqdm</span> <span class="kn">import</span> <span class="n">tqdm</span>
<span class="kn">import</span> <span class="nn">plotly.graph_objects</span> <span class="k">as</span> <span class="n">go</span>
<span class="kn">from</span> <span class="nn">statsmodels.stats</span> <span class="kn">import</span> <span class="n">weightstats</span> <span class="k">as</span> <span class="n">ws</span>
<span class="kn">from</span> <span class="nn">sklearn.ensemble</span> <span class="kn">import</span> <span class="n">RandomForestClassifier</span>
<span class="kn">from</span> <span class="nn">sklearn.model_selection</span> <span class="kn">import</span> <span class="n">train_test_split</span>
<span class="kn">from</span> <span class="nn">sklearn.metrics</span> <span class="kn">import</span> <span class="n">confusion_matrix</span><span class="p">,</span> <span class="n">accuracy_score</span><span class="p">,</span> <span class="n">f1_score</span>
<span class="kn">from</span> <span class="nn">sklearn.model_selection</span> <span class="kn">import</span> <span class="n">GridSearchCV</span>
<span class="o">%</span><span class="n">matplotlib</span> <span class="n">inline</span>
</code></pre></div></div>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># read the data json files
</span><span class="k">def</span> <span class="nf">load_datasets</span><span class="p">():</span>
    <span class="s">'''
    Load the json files into pandas dataframes

        Parameters:
            None
        Returns:
            portfolio (pandas.DataFrame):
            profile (pandas.DataFrame):
            transcript (pandas.DataFrame):
    '''</span>
    <span class="n">portfolio</span> <span class="o">=</span> <span class="n">pd</span><span class="p">.</span><span class="n">read_json</span><span class="p">(</span><span class="s">'data/portfolio.json'</span><span class="p">,</span> <span class="n">orient</span><span class="o">=</span><span class="s">'records'</span><span class="p">,</span> <span class="n">lines</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
    <span class="n">profile</span> <span class="o">=</span> <span class="n">pd</span><span class="p">.</span><span class="n">read_json</span><span class="p">(</span><span class="s">'data/profile.json'</span><span class="p">,</span> <span class="n">orient</span><span class="o">=</span><span class="s">'records'</span><span class="p">,</span> <span class="n">lines</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
    <span class="n">transcript</span> <span class="o">=</span> <span class="n">pd</span><span class="p">.</span><span class="n">read_json</span><span class="p">(</span><span class="s">'data/transcript.json'</span><span class="p">,</span> <span class="n">orient</span><span class="o">=</span><span class="s">'records'</span><span class="p">,</span> <span class="n">lines</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">portfolio</span><span class="p">,</span> <span class="n">profile</span><span class="p">,</span> <span class="n">transcript</span>

<span class="c1"># Load the datasets
</span><span class="n">portfolio</span><span class="p">,</span> <span class="n">profile</span><span class="p">,</span> <span class="n">transcript</span> <span class="o">=</span> <span class="n">load_datasets</span><span class="p">()</span>
</code></pre></div></div>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># Supporting functions
</span>
<span class="k">def</span> <span class="nf">is_within_period</span><span class="p">(</span><span class="n">offer_id</span><span class="p">,</span> <span class="n">elapsed_time</span><span class="p">):</span>
    <span class="s">'''
    Check if a transaction is within an offer period

        Parameters:
            offer_id (object): Offer ID
            elapsed_time (int): time of the transaction
        Returns:
            is_within_period (bool): True if the transaction is within ofer period, False otherwise
    '''</span>
    <span class="k">return</span> <span class="n">elapsed_time</span> <span class="o">&lt;</span> <span class="p">(</span><span class="n">portfolio</span><span class="p">[</span><span class="n">portfolio</span><span class="p">.</span><span class="nb">id</span> <span class="o">==</span> <span class="n">offer_id</span><span class="p">].</span><span class="n">duration</span><span class="p">.</span><span class="n">iloc</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">*</span> <span class="mi">24</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">coalesce_int</span><span class="p">(</span><span class="n">iterable</span><span class="p">):</span>
    <span class="s">'''
    Similar to coalesce function in SQL, find the first that is not None nor nan and return it. Otherwise return nan

        Parameters:
            iterable (iterable): An iterable object. E.g. list
        Returns:
            value (iter item): The first value that is not None nor nan. Otherwise return nan
    '''</span>
    <span class="k">for</span> <span class="n">el</span> <span class="ow">in</span> <span class="n">iterable</span><span class="p">:</span>
        <span class="k">if</span> <span class="n">el</span> <span class="ow">is</span> <span class="ow">not</span> <span class="bp">None</span> <span class="ow">and</span> <span class="ow">not</span> <span class="n">np</span><span class="p">.</span><span class="n">isnan</span><span class="p">(</span><span class="n">el</span><span class="p">):</span>
            <span class="k">return</span> <span class="n">el</span>
    <span class="k">return</span> <span class="n">np</span><span class="p">.</span><span class="n">nan</span>

<span class="k">def</span> <span class="nf">print_histogram</span><span class="p">(</span><span class="n">series</span><span class="p">,</span> <span class="n">title</span><span class="o">=</span><span class="s">'Histogram'</span><span class="p">):</span>
    <span class="s">'''
    Display histogram for a series

        Parameters:
            series (pd.Series): A pandas series
            title (object): Histogram title 
    '''</span>
    <span class="n">ax</span> <span class="o">=</span> <span class="n">sns</span><span class="p">.</span><span class="n">histplot</span><span class="p">(</span><span class="n">series</span><span class="p">,</span> <span class="n">stat</span><span class="o">=</span><span class="s">'probability'</span><span class="p">)</span>
    <span class="n">ax</span><span class="p">.</span><span class="nb">set</span><span class="p">(</span><span class="n">ylabel</span><span class="o">=</span><span class="s">'Ratio'</span><span class="p">,</span> <span class="n">title</span><span class="o">=</span><span class="n">title</span><span class="p">)</span>
    <span class="n">plt</span><span class="p">.</span><span class="n">show</span><span class="p">()</span>

<span class="k">def</span> <span class="nf">print_hor_perc_barplot</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">,</span> <span class="n">title</span><span class="p">,</span> <span class="n">xlabel</span><span class="p">,</span> <span class="n">ylabel</span><span class="p">):</span>
    <span class="s">'''
    Display horizontal percentage barplot.
    Source: https://stackoverflow.com/questions/31749448/how-to-add-percentages-on-top-of-bars-in-seaborn

        Parameters:
            x (pd.Series): A pandas series of data values for x
            y (pd.Series): A pandas series of data values for y
            title (object): Plot title
            xlabel (object): X axis label
            ylabel (object): Y axis label
    '''</span>
    <span class="n">plt</span><span class="p">.</span><span class="n">figure</span><span class="p">(</span><span class="n">figsize</span><span class="o">=</span><span class="p">(</span><span class="mi">12</span><span class="p">,</span><span class="mi">6</span><span class="p">))</span>
    <span class="n">ax</span> <span class="o">=</span> <span class="n">sns</span><span class="p">.</span><span class="n">barplot</span><span class="p">(</span><span class="n">y</span><span class="o">=</span><span class="n">y</span><span class="p">,</span> <span class="n">x</span><span class="o">=</span><span class="n">x</span><span class="p">)</span>
    <span class="n">ax</span><span class="p">.</span><span class="nb">set</span><span class="p">(</span><span class="n">xlabel</span><span class="o">=</span><span class="n">xlabel</span><span class="p">,</span> <span class="n">ylabel</span><span class="o">=</span><span class="n">ylabel</span><span class="p">,</span> <span class="n">title</span><span class="o">=</span><span class="n">title</span><span class="p">)</span>
    <span class="n">ax</span><span class="p">.</span><span class="nb">set</span><span class="p">(</span><span class="n">xlim</span><span class="o">=</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">))</span>
    <span class="k">for</span> <span class="n">p</span> <span class="ow">in</span> <span class="n">ax</span><span class="p">.</span><span class="n">patches</span><span class="p">:</span>
        <span class="k">if</span> <span class="n">p</span><span class="p">.</span><span class="n">get_width</span><span class="p">()</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
            <span class="k">continue</span>
        <span class="n">percentage</span> <span class="o">=</span> <span class="s">'{:.1f}%'</span><span class="p">.</span><span class="nb">format</span><span class="p">(</span><span class="n">p</span><span class="p">.</span><span class="n">get_width</span><span class="p">()</span><span class="o">*</span><span class="mi">100</span><span class="p">)</span>
        <span class="n">x</span> <span class="o">=</span> <span class="n">p</span><span class="p">.</span><span class="n">get_x</span><span class="p">()</span> <span class="o">+</span> <span class="n">p</span><span class="p">.</span><span class="n">get_width</span><span class="p">()</span><span class="o">/</span><span class="mi">2</span>
        <span class="n">y</span> <span class="o">=</span> <span class="n">p</span><span class="p">.</span><span class="n">get_y</span><span class="p">()</span> <span class="o">+</span> <span class="n">p</span><span class="p">.</span><span class="n">get_height</span><span class="p">()</span><span class="o">/</span><span class="mi">2</span>
        <span class="n">ax</span><span class="p">.</span><span class="n">annotate</span><span class="p">(</span><span class="n">percentage</span><span class="p">,</span> <span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">),</span> <span class="n">ha</span><span class="o">=</span><span class="s">'center'</span><span class="p">)</span>
    <span class="n">plt</span><span class="p">.</span><span class="n">show</span><span class="p">()</span>

<span class="k">def</span> <span class="nf">plot_sankey</span><span class="p">(</span><span class="n">offer_name</span><span class="p">,</span> <span class="n">aggregated_offers_trx_details</span><span class="p">):</span>
    <span class="s">'''
    Display a sankey diagram for a certain offer.
    Source: https://plotly.com/python/sankey-diagram/

        Parameters:
            offer_name (object): The code_name of an offer
            aggregated_offers_trx_details (pd.DataFrame): A pandas dataframe containing aggregated offers transactions details
    '''</span>
    
    <span class="c1"># Calculate the values for each step
</span>    <span class="n">total_sent</span> <span class="o">=</span> <span class="n">aggregated_offers_trx_details</span><span class="p">.</span><span class="n">loc</span><span class="p">[</span><span class="n">offer_name</span><span class="p">][</span><span class="s">'code_name'</span><span class="p">]</span>
    <span class="n">sent_viewed</span> <span class="o">=</span> <span class="n">aggregated_offers_trx_details</span><span class="p">.</span><span class="n">loc</span><span class="p">[</span><span class="n">offer_name</span><span class="p">][</span><span class="s">'is_viewed'</span><span class="p">]</span>
    <span class="n">viewed_completed</span> <span class="o">=</span> <span class="n">aggregated_offers_trx_details</span><span class="p">.</span><span class="n">loc</span><span class="p">[</span><span class="n">offer_name</span><span class="p">][</span><span class="s">'is_viewed_and_completed'</span><span class="p">]</span>
    <span class="n">sent_completed</span> <span class="o">=</span> <span class="n">aggregated_offers_trx_details</span><span class="p">.</span><span class="n">loc</span><span class="p">[</span><span class="n">offer_name</span><span class="p">][</span><span class="s">'is_completed'</span><span class="p">]</span> <span class="o">-</span> <span class="n">viewed_completed</span>
    <span class="n">viewed_expired</span> <span class="o">=</span> <span class="n">sent_viewed</span> <span class="o">-</span> <span class="n">viewed_completed</span>
    <span class="n">sent_expired</span> <span class="o">=</span> <span class="n">total_sent</span> <span class="o">-</span> <span class="n">sent_viewed</span> <span class="o">-</span> <span class="n">sent_completed</span>
    
    <span class="c1"># Convert values to percentages
</span>    <span class="n">sent_viewed</span> <span class="o">=</span> <span class="n">sent_viewed</span> <span class="o">/</span> <span class="n">total_sent</span> <span class="o">*</span> <span class="mi">100</span>
    <span class="n">viewed_completed</span> <span class="o">=</span> <span class="n">viewed_completed</span> <span class="o">/</span> <span class="n">total_sent</span> <span class="o">*</span> <span class="mi">100</span>
    <span class="n">sent_completed</span> <span class="o">=</span> <span class="n">sent_completed</span> <span class="o">/</span> <span class="n">total_sent</span> <span class="o">*</span> <span class="mi">100</span>
    <span class="n">viewed_expired</span> <span class="o">=</span> <span class="n">viewed_expired</span> <span class="o">/</span> <span class="n">total_sent</span> <span class="o">*</span> <span class="mi">100</span>
    <span class="n">sent_expired</span> <span class="o">=</span> <span class="n">sent_expired</span> <span class="o">/</span> <span class="n">total_sent</span> <span class="o">*</span> <span class="mi">100</span>
    
    <span class="c1"># Create the sankey diagram
</span>    <span class="n">fig</span> <span class="o">=</span> <span class="n">go</span><span class="p">.</span><span class="n">Figure</span><span class="p">(</span><span class="n">data</span><span class="o">=</span><span class="p">[</span><span class="n">go</span><span class="p">.</span><span class="n">Sankey</span><span class="p">(</span>
        <span class="n">node</span> <span class="o">=</span> <span class="nb">dict</span><span class="p">(</span>
          <span class="n">pad</span> <span class="o">=</span> <span class="mi">15</span><span class="p">,</span>
          <span class="n">thickness</span> <span class="o">=</span> <span class="mi">20</span><span class="p">,</span>
          <span class="n">line</span> <span class="o">=</span> <span class="nb">dict</span><span class="p">(</span><span class="n">color</span> <span class="o">=</span> <span class="s">"black"</span><span class="p">,</span> <span class="n">width</span> <span class="o">=</span> <span class="mf">0.5</span><span class="p">),</span>
          <span class="n">label</span> <span class="o">=</span> <span class="p">[</span><span class="s">"Sent: {:.0f}"</span><span class="p">.</span><span class="nb">format</span><span class="p">(</span><span class="n">total_sent</span><span class="p">),</span> 
                   <span class="s">"Viewed: {:.1f}%"</span><span class="p">.</span><span class="nb">format</span><span class="p">(</span><span class="n">sent_viewed</span><span class="p">),</span> 
                   <span class="s">"Completed: {:.1f}%"</span><span class="p">.</span><span class="nb">format</span><span class="p">(</span><span class="n">viewed_completed</span><span class="p">),</span> 
                   <span class="s">'Completed not viewed: {:.1f}%'</span><span class="p">.</span><span class="nb">format</span><span class="p">(</span><span class="n">sent_completed</span><span class="p">),</span>
                   <span class="s">'Viewed not completed: {:.1f}%'</span><span class="p">.</span><span class="nb">format</span><span class="p">(</span><span class="n">viewed_expired</span><span class="p">),</span>
                   <span class="s">"Expired: {:.1f}%"</span><span class="p">.</span><span class="nb">format</span><span class="p">(</span><span class="n">sent_expired</span><span class="p">)],</span>
          <span class="n">color</span> <span class="o">=</span> <span class="s">"blue"</span>
        <span class="p">),</span>
        <span class="n">link</span> <span class="o">=</span> <span class="nb">dict</span><span class="p">(</span>
          <span class="n">source</span> <span class="o">=</span> <span class="p">[</span><span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">0</span><span class="p">],</span> <span class="c1"># indices correspond to labels
</span>          <span class="n">target</span> <span class="o">=</span> <span class="p">[</span><span class="mi">5</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">],</span>
          <span class="n">value</span> <span class="o">=</span> <span class="p">[</span><span class="n">sent_expired</span><span class="p">,</span> <span class="n">sent_viewed</span><span class="p">,</span> <span class="n">viewed_expired</span><span class="p">,</span> <span class="n">viewed_completed</span><span class="p">,</span> <span class="n">sent_completed</span><span class="p">]</span>
      <span class="p">))])</span>

    <span class="n">fig</span><span class="p">.</span><span class="n">update_layout</span><span class="p">(</span><span class="n">title_text</span><span class="o">=</span><span class="s">"Customers journey for Offer: "</span> <span class="o">+</span> <span class="n">offer_name</span><span class="p">,</span> <span class="n">font_size</span><span class="o">=</span><span class="mi">10</span><span class="p">)</span>
    <span class="n">fig</span><span class="p">.</span><span class="n">show</span><span class="p">(</span><span class="n">renderer</span><span class="o">=</span><span class="s">"svg"</span><span class="p">)</span>
    
<span class="k">def</span> <span class="nf">df_summary</span><span class="p">(</span><span class="n">df</span><span class="p">,</span> <span class="n">n</span><span class="o">=</span><span class="mi">5</span><span class="p">):</span>
    <span class="s">'''
    Prints the shape, missing percentages of columns and the head of a dataframe

            Parameters:
                    df (pandas.Dataframe): The dataframe to show the summary for
    '''</span>
    <span class="k">print</span><span class="p">(</span><span class="s">'- Shape:'</span><span class="p">)</span>
    <span class="k">print</span><span class="p">(</span><span class="n">df</span><span class="p">.</span><span class="n">shape</span><span class="p">)</span>
    <span class="k">print</span><span class="p">(</span><span class="s">'- Missing:'</span><span class="p">)</span>
    <span class="n">missing</span> <span class="o">=</span> <span class="n">df</span><span class="p">.</span><span class="n">isna</span><span class="p">().</span><span class="n">mean</span><span class="p">()[</span><span class="n">df</span><span class="p">.</span><span class="n">isna</span><span class="p">().</span><span class="n">mean</span><span class="p">()</span><span class="o">&gt;</span><span class="mi">0</span><span class="p">]</span>
    <span class="k">if</span> <span class="n">missing</span><span class="p">.</span><span class="n">empty</span><span class="p">:</span>
        <span class="k">print</span><span class="p">(</span><span class="s">'No missing (nan) values'</span><span class="p">)</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="k">print</span><span class="p">(</span><span class="n">missing</span><span class="p">)</span>
    <span class="n">display</span><span class="p">(</span><span class="n">df</span><span class="p">.</span><span class="n">head</span><span class="p">(</span><span class="n">n</span><span class="p">))</span>

<span class="k">def</span> <span class="nf">compare_two_samples</span><span class="p">(</span><span class="n">sample1</span><span class="p">,</span> <span class="n">sample2</span><span class="p">,</span> <span class="n">label1</span><span class="o">=</span><span class="s">'label1'</span><span class="p">,</span> <span class="n">label2</span><span class="o">=</span><span class="s">'label2'</span><span class="p">,</span> <span class="n">title</span><span class="o">=</span><span class="s">'Comparison'</span><span class="p">):</span>
    <span class="s">'''
    Compare two independent series:
        - Display a histogram showing the two distributions
        - Display the means of both series
        - Perform z-test and display test result
    Source: https://www.statsmodels.org/stable/generated/statsmodels.stats.weightstats.ztest.html?highlight=ztest#statsmodels.stats.weightstats.ztest
        Parameters:
            sample1 (pd.Series): A pandas series of data values for sample1
            sample2 (pd.Series): A pandas series of data values for sample2
            label1 (object): Axis label for sample 1
            label2 (object): Axis label for sample 2
            title (object): Plot title
    '''</span>
    <span class="c1"># Plot comparison histogram
</span>    <span class="n">plt</span><span class="p">.</span><span class="n">figure</span><span class="p">(</span><span class="n">figsize</span><span class="o">=</span><span class="p">(</span><span class="mi">12</span><span class="p">,</span><span class="mi">6</span><span class="p">))</span>
    <span class="n">ax</span> <span class="o">=</span> <span class="n">sns</span><span class="p">.</span><span class="n">histplot</span><span class="p">(</span><span class="n">sample1</span><span class="p">,</span> <span class="n">label</span><span class="o">=</span><span class="n">label1</span><span class="p">)</span>
    <span class="n">ax</span> <span class="o">=</span> <span class="n">sns</span><span class="p">.</span><span class="n">histplot</span><span class="p">(</span><span class="n">sample2</span><span class="p">,</span> <span class="n">color</span><span class="o">=</span><span class="s">'r'</span><span class="p">,</span> <span class="n">label</span><span class="o">=</span><span class="n">label2</span><span class="p">,</span> <span class="n">alpha</span><span class="o">=</span><span class="mf">0.3</span><span class="p">)</span>
    <span class="n">ax</span><span class="p">.</span><span class="nb">set</span><span class="p">(</span><span class="n">title</span><span class="o">=</span><span class="n">title</span><span class="p">)</span>
    <span class="n">ax</span><span class="p">.</span><span class="n">legend</span><span class="p">(</span><span class="n">loc</span><span class="o">=</span><span class="s">'upper right'</span><span class="p">)</span>
    <span class="n">plt</span><span class="p">.</span><span class="n">show</span><span class="p">()</span>
    
    <span class="c1"># Print the two means
</span>    <span class="k">print</span><span class="p">(</span><span class="s">'Mean for {}: {:.2f}'</span><span class="p">.</span><span class="nb">format</span><span class="p">(</span><span class="n">label1</span><span class="p">,</span> <span class="n">np</span><span class="p">.</span><span class="n">mean</span><span class="p">(</span><span class="n">sample1</span><span class="p">)))</span>
    <span class="k">print</span><span class="p">(</span><span class="s">'Mean for {}: {:.2f}'</span><span class="p">.</span><span class="nb">format</span><span class="p">(</span><span class="n">label2</span><span class="p">,</span> <span class="n">np</span><span class="p">.</span><span class="n">mean</span><span class="p">(</span><span class="n">sample2</span><span class="p">)))</span>
    
    <span class="c1"># Perform ztest
</span>    <span class="n">zscore</span><span class="p">,</span> <span class="n">pvalue</span> <span class="o">=</span> <span class="n">ws</span><span class="p">.</span><span class="n">ztest</span><span class="p">(</span><span class="n">x1</span><span class="o">=</span><span class="n">sample1</span><span class="p">,</span> 
                              <span class="n">x2</span><span class="o">=</span><span class="n">sample2</span><span class="p">,</span>
                              <span class="n">value</span><span class="o">=</span><span class="mi">0</span><span class="p">,</span>
                              <span class="n">alternative</span><span class="o">=</span><span class="s">'two-sided'</span>
                             <span class="p">)</span>
    <span class="k">print</span><span class="p">(</span><span class="s">''</span><span class="p">)</span>
    <span class="k">print</span><span class="p">(</span><span class="s">'Z-test result:'</span><span class="p">)</span>
    <span class="k">print</span><span class="p">(</span><span class="s">'z-score: {:.2f}'</span><span class="p">.</span><span class="nb">format</span><span class="p">(</span><span class="n">zscore</span><span class="p">))</span>
    <span class="k">print</span><span class="p">(</span><span class="s">'p-value: {}'</span><span class="p">.</span><span class="nb">format</span><span class="p">(</span><span class="n">pvalue</span><span class="p">))</span>
    
    <span class="c1"># Display test result based on 0.05 confidence level
</span>    <span class="k">if</span> <span class="n">pvalue</span> <span class="o">&lt;</span> <span class="mf">0.05</span><span class="p">:</span>
        <span class="k">print</span><span class="p">(</span><span class="s">'The null hypothesis H0 is REJECTED. p-value is statistically significant'</span><span class="p">)</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="k">print</span><span class="p">(</span><span class="s">'The null hypothesis H0 is ACCEPTED. p-value is statistically insignificant'</span><span class="p">)</span>
</code></pre></div></div>

<h3 id="we-look-at-the-head-of-each-of-the-three-data-failes-how-they-look-and-if-there-is-any-missing-values">We look at the head of each of the three data failes, how they look and if there is any missing values</h3>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">df_summary</span><span class="p">(</span><span class="n">portfolio</span><span class="p">,</span> <span class="mi">10</span><span class="p">)</span>
</code></pre></div></div>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>- Shape:
(10, 6)
- Missing:
No missing (nan) values
</code></pre></div></div>

<div>
<style scoped="">
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>reward</th>
      <th>channels</th>
      <th>difficulty</th>
      <th>duration</th>
      <th>offer_type</th>
      <th>id</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>10</td>
      <td>[email, mobile, social]</td>
      <td>10</td>
      <td>7</td>
      <td>bogo</td>
      <td>ae264e3637204a6fb9bb56bc8210ddfd</td>
    </tr>
    <tr>
      <th>1</th>
      <td>10</td>
      <td>[web, email, mobile, social]</td>
      <td>10</td>
      <td>5</td>
      <td>bogo</td>
      <td>4d5c57ea9a6940dd891ad53e9dbe8da0</td>
    </tr>
    <tr>
      <th>2</th>
      <td>0</td>
      <td>[web, email, mobile]</td>
      <td>0</td>
      <td>4</td>
      <td>informational</td>
      <td>3f207df678b143eea3cee63160fa8bed</td>
    </tr>
    <tr>
      <th>3</th>
      <td>5</td>
      <td>[web, email, mobile]</td>
      <td>5</td>
      <td>7</td>
      <td>bogo</td>
      <td>9b98b8c7a33c4b65b9aebfe6a799e6d9</td>
    </tr>
    <tr>
      <th>4</th>
      <td>5</td>
      <td>[web, email]</td>
      <td>20</td>
      <td>10</td>
      <td>discount</td>
      <td>0b1e1539f2cc45b7b9fa7c272da2e1d7</td>
    </tr>
    <tr>
      <th>5</th>
      <td>3</td>
      <td>[web, email, mobile, social]</td>
      <td>7</td>
      <td>7</td>
      <td>discount</td>
      <td>2298d6c36e964ae4a3e7e9706d1fb8c2</td>
    </tr>
    <tr>
      <th>6</th>
      <td>2</td>
      <td>[web, email, mobile, social]</td>
      <td>10</td>
      <td>10</td>
      <td>discount</td>
      <td>fafdcd668e3743c1bb461111dcafc2a4</td>
    </tr>
    <tr>
      <th>7</th>
      <td>0</td>
      <td>[email, mobile, social]</td>
      <td>0</td>
      <td>3</td>
      <td>informational</td>
      <td>5a8bc65990b245e5a138643cd4eb9837</td>
    </tr>
    <tr>
      <th>8</th>
      <td>5</td>
      <td>[web, email, mobile, social]</td>
      <td>5</td>
      <td>5</td>
      <td>bogo</td>
      <td>f19421c1d4aa40978ebb69ca19b0e20d</td>
    </tr>
    <tr>
      <th>9</th>
      <td>2</td>
      <td>[web, email, mobile]</td>
      <td>10</td>
      <td>7</td>
      <td>discount</td>
      <td>2906b810c7d4411798c6938adc9daaa5</td>
    </tr>
  </tbody>
</table>
</div>

<p>It was mentioned that missing age values where encded as 118 in the dataset. Hence, we will set those values to nan</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># Before checking percentage of missing values, as documented,
# for age replace 118, which means missing values, with nan
</span><span class="n">profile</span><span class="p">.</span><span class="n">loc</span><span class="p">[</span><span class="n">profile</span><span class="p">.</span><span class="n">age</span><span class="o">==</span><span class="mi">118</span><span class="p">,</span> <span class="s">'age'</span><span class="p">]</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">nan</span>
<span class="n">df_summary</span><span class="p">(</span><span class="n">profile</span><span class="p">)</span>
</code></pre></div></div>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>- Shape:
(17000, 5)
- Missing:
gender    0.127941
age       0.127941
income    0.127941
dtype: float64
</code></pre></div></div>

<div>
<style scoped="">
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>gender</th>
      <th>age</th>
      <th>id</th>
      <th>became_member_on</th>
      <th>income</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>None</td>
      <td>NaN</td>
      <td>68be06ca386d4c31939f3a4f0e3dd783</td>
      <td>20170212</td>
      <td>NaN</td>
    </tr>
    <tr>
      <th>1</th>
      <td>F</td>
      <td>55.0</td>
      <td>0610b486422d4921ae7d2bf64640c50b</td>
      <td>20170715</td>
      <td>112000.0</td>
    </tr>
    <tr>
      <th>2</th>
      <td>None</td>
      <td>NaN</td>
      <td>38fe809add3b4fcf9315a9694bb96ff5</td>
      <td>20180712</td>
      <td>NaN</td>
    </tr>
    <tr>
      <th>3</th>
      <td>F</td>
      <td>75.0</td>
      <td>78afa995795e4d85b5d9ceeca43f5fef</td>
      <td>20170509</td>
      <td>100000.0</td>
    </tr>
    <tr>
      <th>4</th>
      <td>None</td>
      <td>NaN</td>
      <td>a03223e636434f42ac4c3df47e8bac43</td>
      <td>20170804</td>
      <td>NaN</td>
    </tr>
  </tbody>
</table>
</div>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">df_summary</span><span class="p">(</span><span class="n">transcript</span><span class="p">)</span>
</code></pre></div></div>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>- Shape:
(306534, 4)
- Missing:
No missing (nan) values
</code></pre></div></div>

<div>
<style scoped="">
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>person</th>
      <th>event</th>
      <th>value</th>
      <th>time</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>78afa995795e4d85b5d9ceeca43f5fef</td>
      <td>offer received</td>
      <td>{'offer id': '9b98b8c7a33c4b65b9aebfe6a799e6d9'}</td>
      <td>0</td>
    </tr>
    <tr>
      <th>1</th>
      <td>a03223e636434f42ac4c3df47e8bac43</td>
      <td>offer received</td>
      <td>{'offer id': '0b1e1539f2cc45b7b9fa7c272da2e1d7'}</td>
      <td>0</td>
    </tr>
    <tr>
      <th>2</th>
      <td>e2127556f4f64592b11af22de27a7932</td>
      <td>offer received</td>
      <td>{'offer id': '2906b810c7d4411798c6938adc9daaa5'}</td>
      <td>0</td>
    </tr>
    <tr>
      <th>3</th>
      <td>8ec6ce2a7e7949b1bf142def7d0e0586</td>
      <td>offer received</td>
      <td>{'offer id': 'fafdcd668e3743c1bb461111dcafc2a4'}</td>
      <td>0</td>
    </tr>
    <tr>
      <th>4</th>
      <td>68617ca6246f4fbc85e91a2a49552598</td>
      <td>offer received</td>
      <td>{'offer id': '4d5c57ea9a6940dd891ad53e9dbe8da0'}</td>
      <td>0</td>
    </tr>
  </tbody>
</table>
</div>

<p>Only profile dataset contains missing values. We can see that around 12.8% of demographics data is missing. We will decide how to handle this as we have a further look at the data</p>

<h2 id="3-data-preparation-and-exploration">3. Data preparation and exploration</h2>
<p>In this section we will perform the following data processing steps on each dataset:</p>

<h3 id="a-portfolio-dataset">a. “portfolio” dataset</h3>
<p>The portfolio data is quite straight forward having only 10 rows corresponding to the 10 offers.</p>

<p>We do some basic feature engineering. This makes it easier for any modelling step later on</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">prepare_portfolio_dataset</span><span class="p">(</span><span class="n">portfolio</span><span class="p">):</span> 
    <span class="s">'''
    Perform data preparation on portfolio dataset:
    - One-hot-encode channels
    - One-hot-encode offers
    - Give code names for offers for easier readability

        Parameters:
            portfolio (pd.DataFrame): Portfolio dataframe to be processed
        Returns:
            portfolio (pd.DataFrame): Portfolio dataframe after processing
    '''</span>
    <span class="c1"># Split channels column to multiple columns with one-hot-encoding
</span>    <span class="n">portfolio</span><span class="p">[</span><span class="s">'web_ch'</span><span class="p">]</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span> <span class="k">if</span> <span class="s">'web'</span> <span class="ow">in</span> <span class="n">w</span> <span class="k">else</span> <span class="mi">0</span> <span class="k">for</span> <span class="n">w</span> <span class="ow">in</span> <span class="n">portfolio</span><span class="p">.</span><span class="n">channels</span><span class="p">]</span>
    <span class="n">portfolio</span><span class="p">[</span><span class="s">'email_ch'</span><span class="p">]</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span> <span class="k">if</span> <span class="s">'email'</span> <span class="ow">in</span> <span class="n">w</span> <span class="k">else</span> <span class="mi">0</span> <span class="k">for</span> <span class="n">w</span> <span class="ow">in</span> <span class="n">portfolio</span><span class="p">.</span><span class="n">channels</span><span class="p">]</span>
    <span class="n">portfolio</span><span class="p">[</span><span class="s">'mobile_ch'</span><span class="p">]</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span> <span class="k">if</span> <span class="s">'mobile'</span> <span class="ow">in</span> <span class="n">w</span> <span class="k">else</span> <span class="mi">0</span> <span class="k">for</span> <span class="n">w</span> <span class="ow">in</span> <span class="n">portfolio</span><span class="p">.</span><span class="n">channels</span><span class="p">]</span>
    <span class="n">portfolio</span><span class="p">[</span><span class="s">'social_ch'</span><span class="p">]</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span> <span class="k">if</span> <span class="s">'social'</span> <span class="ow">in</span> <span class="n">w</span> <span class="k">else</span> <span class="mi">0</span> <span class="k">for</span> <span class="n">w</span> <span class="ow">in</span> <span class="n">portfolio</span><span class="p">.</span><span class="n">channels</span><span class="p">]</span>

    <span class="c1"># Also one-hot-encode offer_type
</span>    <span class="n">portfolio</span> <span class="o">=</span> <span class="n">pd</span><span class="p">.</span><span class="n">concat</span><span class="p">([</span><span class="n">portfolio</span><span class="p">,</span> <span class="n">pd</span><span class="p">.</span><span class="n">get_dummies</span><span class="p">(</span><span class="n">portfolio</span><span class="p">.</span><span class="n">offer_type</span><span class="p">)],</span> <span class="n">axis</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
    <span class="n">portfolio</span> <span class="o">=</span> <span class="n">portfolio</span><span class="p">.</span><span class="n">drop</span><span class="p">([</span><span class="s">'channels'</span><span class="p">,</span> <span class="s">'offer_type'</span><span class="p">],</span> <span class="n">axis</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>

    <span class="c1"># Finally give code_name to the offers for easier readability
</span>    <span class="n">portfolio</span><span class="p">[</span><span class="s">'code_name'</span><span class="p">]</span> <span class="o">=</span> <span class="p">[</span><span class="s">'bogo_1'</span><span class="p">,</span> <span class="s">'bogo_2'</span><span class="p">,</span> <span class="s">'info_1'</span><span class="p">,</span> <span class="s">'bogo_3'</span><span class="p">,</span> <span class="s">'discount_1'</span><span class="p">,</span> <span class="s">'discount_2'</span><span class="p">,</span> <span class="s">'discount_3'</span><span class="p">,</span> <span class="s">'info_2'</span><span class="p">,</span> <span class="s">'bogo_4'</span><span class="p">,</span> <span class="s">'discount_4'</span><span class="p">]</span>
    <span class="k">return</span> <span class="n">portfolio</span>

<span class="c1"># Prepare portfolio dataset
</span><span class="n">portfolio</span> <span class="o">=</span> <span class="n">prepare_portfolio_dataset</span><span class="p">(</span><span class="n">portfolio</span><span class="p">)</span>
<span class="n">portfolio</span><span class="p">.</span><span class="n">head</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span>
</code></pre></div></div>

<div>
<style scoped="">
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>reward</th>
      <th>difficulty</th>
      <th>duration</th>
      <th>id</th>
      <th>web_ch</th>
      <th>email_ch</th>
      <th>mobile_ch</th>
      <th>social_ch</th>
      <th>bogo</th>
      <th>discount</th>
      <th>informational</th>
      <th>code_name</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>10</td>
      <td>10</td>
      <td>7</td>
      <td>ae264e3637204a6fb9bb56bc8210ddfd</td>
      <td>0</td>
      <td>1</td>
      <td>1</td>
      <td>1</td>
      <td>1</td>
      <td>0</td>
      <td>0</td>
      <td>bogo_1</td>
    </tr>
    <tr>
      <th>1</th>
      <td>10</td>
      <td>10</td>
      <td>5</td>
      <td>4d5c57ea9a6940dd891ad53e9dbe8da0</td>
      <td>1</td>
      <td>1</td>
      <td>1</td>
      <td>1</td>
      <td>1</td>
      <td>0</td>
      <td>0</td>
      <td>bogo_2</td>
    </tr>
    <tr>
      <th>2</th>
      <td>0</td>
      <td>0</td>
      <td>4</td>
      <td>3f207df678b143eea3cee63160fa8bed</td>
      <td>1</td>
      <td>1</td>
      <td>1</td>
      <td>0</td>
      <td>0</td>
      <td>0</td>
      <td>1</td>
      <td>info_1</td>
    </tr>
    <tr>
      <th>3</th>
      <td>5</td>
      <td>5</td>
      <td>7</td>
      <td>9b98b8c7a33c4b65b9aebfe6a799e6d9</td>
      <td>1</td>
      <td>1</td>
      <td>1</td>
      <td>0</td>
      <td>1</td>
      <td>0</td>
      <td>0</td>
      <td>bogo_3</td>
    </tr>
    <tr>
      <th>4</th>
      <td>5</td>
      <td>20</td>
      <td>10</td>
      <td>0b1e1539f2cc45b7b9fa7c272da2e1d7</td>
      <td>1</td>
      <td>1</td>
      <td>0</td>
      <td>0</td>
      <td>0</td>
      <td>1</td>
      <td>0</td>
      <td>discount_1</td>
    </tr>
    <tr>
      <th>5</th>
      <td>3</td>
      <td>7</td>
      <td>7</td>
      <td>2298d6c36e964ae4a3e7e9706d1fb8c2</td>
      <td>1</td>
      <td>1</td>
      <td>1</td>
      <td>1</td>
      <td>0</td>
      <td>1</td>
      <td>0</td>
      <td>discount_2</td>
    </tr>
    <tr>
      <th>6</th>
      <td>2</td>
      <td>10</td>
      <td>10</td>
      <td>fafdcd668e3743c1bb461111dcafc2a4</td>
      <td>1</td>
      <td>1</td>
      <td>1</td>
      <td>1</td>
      <td>0</td>
      <td>1</td>
      <td>0</td>
      <td>discount_3</td>
    </tr>
    <tr>
      <th>7</th>
      <td>0</td>
      <td>0</td>
      <td>3</td>
      <td>5a8bc65990b245e5a138643cd4eb9837</td>
      <td>0</td>
      <td>1</td>
      <td>1</td>
      <td>1</td>
      <td>0</td>
      <td>0</td>
      <td>1</td>
      <td>info_2</td>
    </tr>
    <tr>
      <th>8</th>
      <td>5</td>
      <td>5</td>
      <td>5</td>
      <td>f19421c1d4aa40978ebb69ca19b0e20d</td>
      <td>1</td>
      <td>1</td>
      <td>1</td>
      <td>1</td>
      <td>1</td>
      <td>0</td>
      <td>0</td>
      <td>bogo_4</td>
    </tr>
    <tr>
      <th>9</th>
      <td>2</td>
      <td>10</td>
      <td>7</td>
      <td>2906b810c7d4411798c6938adc9daaa5</td>
      <td>1</td>
      <td>1</td>
      <td>1</td>
      <td>0</td>
      <td>0</td>
      <td>1</td>
      <td>0</td>
      <td>discount_4</td>
    </tr>
  </tbody>
</table>
</div>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># Look at the how each channel was used
</span><span class="n">portfolio</span><span class="p">[[</span><span class="s">'web_ch'</span><span class="p">,</span> <span class="s">'email_ch'</span><span class="p">,</span> <span class="s">'mobile_ch'</span><span class="p">,</span> <span class="s">'social_ch'</span><span class="p">,</span> <span class="s">'bogo'</span><span class="p">,</span> <span class="s">'discount'</span><span class="p">,</span> <span class="s">'informational'</span><span class="p">]].</span><span class="nb">sum</span><span class="p">()</span>
</code></pre></div></div>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>web_ch            8
email_ch         10
mobile_ch         9
social_ch         6
bogo              4
discount          4
informational     2
dtype: int64
</code></pre></div></div>

<p>We can see that email channel is used with all offers, so it loses value in terms of modelling, because it does not carry any discriminatory value!</p>

<p>This should not be confused with the potential importance of it as a channel, but again not for modelling purposes</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">portfolio</span><span class="p">[[</span><span class="s">'bogo'</span><span class="p">,</span> <span class="s">'discount'</span><span class="p">,</span> <span class="s">'informational'</span><span class="p">]].</span><span class="nb">sum</span><span class="p">()</span>
</code></pre></div></div>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>bogo             4
discount         4
informational    2
dtype: int64
</code></pre></div></div>

<p>Clearly we have 4 bogo, 4 discount offers, and 2 informational</p>

<h3 id="b-profile-dataset">b. “profile” dataset</h3>

<p>First, we will perform the following two steps:</p>
<ul>
  <li>Convert ‘became_member_on’ to datetime</li>
  <li>Replace ‘became_member_on’ with ‘year_of_membership’</li>
  <li>Replace missing gender values with ‘U’ for unknown</li>
</ul>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">prepare_profile_dataset</span><span class="p">(</span><span class="n">profile</span><span class="p">):</span>
    <span class="s">'''
    Perform data preparation on profile dataset:
    - Convert 'became_member_on' to datetime
    - Replace 'became_member_on' with 'year_of_membership'
    - Replace missing gender values with 'U' for unknown

        Parameters:
            profile (pd.DataFrame): Profile dataframe to be processed
        Returns:
            profile (pd.DataFrame): Profile dataframe after processing
    '''</span>
    <span class="c1"># Set date column as date
</span>    <span class="n">profile</span><span class="p">.</span><span class="n">became_member_on</span> <span class="o">=</span> <span class="n">pd</span><span class="p">.</span><span class="n">to_datetime</span><span class="p">(</span><span class="n">profile</span><span class="p">.</span><span class="n">became_member_on</span><span class="p">.</span><span class="n">astype</span><span class="p">(</span><span class="s">'str'</span><span class="p">))</span>

    <span class="c1"># Convert became_member_on to year_of_membership starting from 1 for 
</span>    <span class="c1"># subscriptions starting in end of July 2017, given that the max date is end of July 2018
</span>    <span class="n">profile</span><span class="p">[</span><span class="s">'year_of_membership'</span><span class="p">]</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">int32</span><span class="p">(</span><span class="n">np</span><span class="p">.</span><span class="n">ceil</span><span class="p">((</span><span class="n">np</span><span class="p">.</span><span class="n">datetime64</span><span class="p">(</span><span class="s">'2018-07-30'</span><span class="p">)</span> <span class="o">-</span> <span class="n">profile</span><span class="p">.</span><span class="n">became_member_on</span><span class="p">)</span><span class="o">/</span><span class="n">np</span><span class="p">.</span><span class="n">timedelta64</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="s">'Y'</span><span class="p">)))</span>
    <span class="n">profile</span> <span class="o">=</span> <span class="n">profile</span><span class="p">.</span><span class="n">drop</span><span class="p">([</span><span class="s">'became_member_on'</span><span class="p">],</span> <span class="n">axis</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>

    <span class="c1"># Replace gender nan values with 'U'
</span>    <span class="n">profile</span><span class="p">.</span><span class="n">gender</span> <span class="o">=</span> <span class="n">profile</span><span class="p">.</span><span class="n">gender</span><span class="p">.</span><span class="n">fillna</span><span class="p">(</span><span class="s">'U'</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">profile</span>

<span class="c1"># Prepare profile dataset
</span><span class="n">profile</span> <span class="o">=</span> <span class="n">prepare_profile_dataset</span><span class="p">(</span><span class="n">profile</span><span class="p">)</span>
</code></pre></div></div>

<h4 id="looking-at-the-dstribution-of-each-column-and-seeing-if-there-are-outliers-within-the-data">Looking at the dstribution of each column, and seeing if there are outliers within the data</h4>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># Creating gender histogram
</span><span class="n">print_histogram</span><span class="p">(</span><span class="n">profile</span><span class="p">.</span><span class="n">gender</span><span class="p">,</span> <span class="n">title</span><span class="o">=</span><span class="s">'Gender Histogram'</span><span class="p">)</span>
</code></pre></div></div>

<p><img src="/images/output_24_0.png" alt="_config.yml" /></p>

<p>We will decide what to do with the missing values denoted as ‘U’ later on. 
However, looking at M and F values, there is some imbalance, but it is not severe. However we will have to be careful when splitting the data and modelling</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># Age histogram ignoring missing values
</span><span class="n">print_histogram</span><span class="p">(</span><span class="n">profile</span><span class="p">.</span><span class="n">age</span><span class="p">,</span> <span class="n">title</span><span class="o">=</span><span class="s">'Age Histogram'</span><span class="p">)</span>
</code></pre></div></div>

<p><img src="/images/output_26_0.png" alt="_config.yml" /></p>

<p>The data seems to be normally distributed with some skewness. One reason is that the application contains ages starting from 18 years old</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># Age boxplot
</span><span class="n">h</span> <span class="o">=</span> <span class="n">profile</span><span class="p">.</span><span class="n">boxplot</span><span class="p">([</span><span class="s">'age'</span><span class="p">],</span> <span class="n">showfliers</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span> <span class="n">return_type</span><span class="o">=</span><span class="s">'dict'</span><span class="p">)</span>
</code></pre></div></div>

<p><img src="/images/output_28_0.png" alt="_config.yml" /></p>

<p>We don’t see any extreme valus or severe skewness other than slight skewness to the right. 
Also, from the above boxplot, we can see that 50% of our customers fall between ages around 42 and 65</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># Histogram for our newly created feature 'year_of_membership'
# h = profile.year_of_membership.hist()
</span><span class="n">print_histogram</span><span class="p">(</span><span class="n">profile</span><span class="p">.</span><span class="n">year_of_membership</span><span class="p">,</span> <span class="n">title</span><span class="o">=</span><span class="s">'year_of_membership histogram'</span><span class="p">)</span>
</code></pre></div></div>

<p><img src="/images/output_30_0.png" alt="_config.yml" /></p>

<p>We can see that 50% of customers are in their first year of membership. 40% are in their 2nd or 3rd year</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># Income histogram ignoring nan values
</span><span class="n">print_histogram</span><span class="p">(</span><span class="n">profile</span><span class="p">.</span><span class="n">income</span><span class="p">,</span> <span class="n">title</span><span class="o">=</span><span class="s">'Income Histogram'</span><span class="p">)</span>
</code></pre></div></div>

<p><img src="/images/output_32_0.png" alt="_config.yml" /></p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># Income boxplot
</span><span class="n">h</span> <span class="o">=</span> <span class="n">profile</span><span class="p">.</span><span class="n">boxplot</span><span class="p">([</span><span class="s">'income'</span><span class="p">],</span> <span class="n">showfliers</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span> <span class="n">return_type</span><span class="o">=</span><span class="s">'dict'</span><span class="p">)</span>
</code></pre></div></div>

<p><img src="/images/output_33_0.png" alt="_config.yml" /></p>

<p>Again here we don’t outliers and there is some skewness slightly to the right. 50% of customers have an income between 50k to 80k</p>

<p>Now, we can start looking at the correlation matrix for profile features</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># Display correlation heatmap
</span><span class="n">sns</span><span class="p">.</span><span class="n">heatmap</span><span class="p">(</span><span class="n">profile</span><span class="p">.</span><span class="n">corr</span><span class="p">(),</span> <span class="n">annot</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">show</span><span class="p">()</span>
</code></pre></div></div>

<p><img src="/images/output_36_0.png" alt="_config.yml" /></p>

<p>The correlation heatmap suggests some positive correlation between age and income, which is expected and can be seen better in the next set of charts. However, neither age nor income show correlation with year_of_membership feature.</p>

<p>Then we look at the scatterplot matrix to gain further insights</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># For visual representation and to examine missing values, we will set missing gender values to 'U'
</span><span class="n">profile_gender_modified</span> <span class="o">=</span> <span class="n">profile</span>
<span class="n">profile_gender_modified</span><span class="p">.</span><span class="n">gender</span> <span class="o">=</span> <span class="n">profile_gender_modified</span><span class="p">.</span><span class="n">gender</span><span class="p">.</span><span class="n">fillna</span><span class="p">(</span><span class="s">'U'</span><span class="p">)</span>

<span class="c1"># Create scatterplot matrix to observe distribution and interactios of different features
</span><span class="n">sns</span><span class="p">.</span><span class="n">pairplot</span><span class="p">(</span><span class="n">profile_gender_modified</span><span class="p">,</span> <span class="n">hue</span><span class="o">=</span><span class="s">'gender'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">show</span><span class="p">()</span>
</code></pre></div></div>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>C:\Users\alien\anaconda3\lib\site-packages\seaborn\distributions.py:306: UserWarning: Dataset has 0 variance; skipping density estimate.
  warnings.warn(msg, UserWarning)
C:\Users\alien\anaconda3\lib\site-packages\seaborn\distributions.py:306: UserWarning: Dataset has 0 variance; skipping density estimate.
  warnings.warn(msg, UserWarning)
</code></pre></div></div>

<p><img src="/images/output_38_1.png" alt="_config.yml" /></p>

<p>Given the charts above, I have the following comments:</p>
<ul>
  <li>The age vs income charts show a positive correlation. However, clearly it shows how synthetic this dataset is. As in real life we won’t have those clear borders.</li>
  <li>Male income is right skewed</li>
  <li>For higher incomes, it seems that female customers or more prominent</li>
  <li>There is nothing much noticeable regarding O and null gender records distributions. Therefore, we will drop records with nan value for demographic info</li>
</ul>

<h5 id="as-mentioned-removing-customer-records-with-missing-data-however-better-way-to-do-it-is-to-check-specifically-the-distribution-of-those-records-with-missing-values-vs-with-non-missing-values-and-see-if-there-is-any-statistical-significance-in-the-difference-between-the-two">As mentioned, removing customer records with missing data. However, better way to do it is to check specifically the distribution of those records with missing values vs with non-missing values and see if there is any statistical significance in the difference between the two</h5>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># Remove rows with missing values
</span><span class="n">profile</span> <span class="o">=</span> <span class="n">profile</span><span class="p">.</span><span class="n">dropna</span><span class="p">()</span>
</code></pre></div></div>

<h2 id="c-transcript-dataset">c. “transcript” dataset</h2>
<p>This is where the bulk of the preprocessing work will be done as we are deling with the transactions</p>

<p>First we do some initial preprocessing steps by replacing ‘amount’ column and creating 3 columns: offer_id, amount, reward</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">prepare_transcript_dataset</span><span class="p">(</span><span class="n">transcript</span><span class="p">):</span>
    <span class="s">'''
    Perform data preparation on transcript dataset:
    - Convert the value column into 3 corresponding columns
    - Drop value column

        Parameters:
            transcript (pd.DataFrame): Transcript dataframe to be processed
        Returns:
            transcript (pd.DataFrame): Transcript dataframe after processing
    '''</span>
    <span class="n">transcript</span><span class="p">[</span><span class="s">'offer_id'</span><span class="p">]</span> <span class="o">=</span> <span class="p">[</span><span class="n">w</span><span class="p">[</span><span class="s">'offer id'</span><span class="p">]</span> <span class="k">if</span> <span class="s">'offer id'</span> <span class="ow">in</span> <span class="n">w</span> <span class="k">else</span> 
                              <span class="n">w</span><span class="p">[</span><span class="s">'offer_id'</span><span class="p">]</span> <span class="k">if</span> <span class="s">'offer_id'</span> <span class="ow">in</span> <span class="n">w</span> <span class="k">else</span> 
                              <span class="n">np</span><span class="p">.</span><span class="n">nan</span> <span class="k">for</span> <span class="n">w</span> <span class="ow">in</span> <span class="n">transcript</span><span class="p">.</span><span class="n">value</span><span class="p">]</span>
    <span class="n">transcript</span><span class="p">[</span><span class="s">'amount'</span><span class="p">]</span> <span class="o">=</span> <span class="p">[</span><span class="n">w</span><span class="p">[</span><span class="s">'amount'</span><span class="p">]</span> <span class="k">if</span> <span class="s">'amount'</span> <span class="ow">in</span> <span class="n">w</span> <span class="k">else</span> <span class="n">np</span><span class="p">.</span><span class="n">nan</span> <span class="k">for</span> <span class="n">w</span> <span class="ow">in</span> <span class="n">transcript</span><span class="p">.</span><span class="n">value</span><span class="p">]</span>
    <span class="n">transcript</span><span class="p">[</span><span class="s">'reward'</span><span class="p">]</span> <span class="o">=</span> <span class="p">[</span><span class="n">w</span><span class="p">[</span><span class="s">'reward'</span><span class="p">]</span> <span class="k">if</span> <span class="s">'reward'</span> <span class="ow">in</span> <span class="n">w</span> <span class="k">else</span> <span class="n">np</span><span class="p">.</span><span class="n">nan</span> <span class="k">for</span> <span class="n">w</span> <span class="ow">in</span> <span class="n">transcript</span><span class="p">.</span><span class="n">value</span><span class="p">]</span>
    <span class="n">transcript</span> <span class="o">=</span> <span class="n">transcript</span><span class="p">.</span><span class="n">drop</span><span class="p">([</span><span class="s">'value'</span><span class="p">],</span> <span class="n">axis</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">transcript</span>

<span class="n">transcript</span> <span class="o">=</span> <span class="n">prepare_transcript_dataset</span><span class="p">(</span><span class="n">transcript</span><span class="p">)</span>
</code></pre></div></div>

<h4 id="looking-at-the-dstribution-of-each-column-and-seeing-if-there-are-outliers-within-the-data-1">Looking at the dstribution of each column, and seeing if there are outliers within the data</h4>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># Starting with transaction amounts
</span><span class="n">print_histogram</span><span class="p">(</span><span class="n">transcript</span><span class="p">[</span><span class="n">transcript</span><span class="p">.</span><span class="n">event</span> <span class="o">==</span> <span class="s">'transaction'</span><span class="p">].</span><span class="n">amount</span><span class="p">)</span>
</code></pre></div></div>

<p><img src="/images/output_46_0.png" alt="_config.yml" /></p>

<p>The shape of this histogram suggests that we have some extreme values. Therefore, we will create a boxplot</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># Show boxplot with outliers
</span><span class="n">transcript</span><span class="p">[</span><span class="n">transcript</span><span class="p">.</span><span class="n">event</span> <span class="o">==</span> <span class="s">'transaction'</span><span class="p">].</span><span class="n">boxplot</span><span class="p">([</span><span class="s">'amount'</span><span class="p">],</span> <span class="n">return_type</span><span class="o">=</span><span class="s">'dict'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">show</span><span class="p">()</span>
</code></pre></div></div>

<p><img src="/images/output_48_0.png" alt="_config.yml" /></p>

<p>We can clearly see that there are extreme values in the data.</p>

<p>Having another look without those extreme values:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># Show boxplot without outliers
</span><span class="n">transcript</span><span class="p">[</span><span class="n">transcript</span><span class="p">.</span><span class="n">event</span> <span class="o">==</span> <span class="s">'transaction'</span><span class="p">].</span><span class="n">boxplot</span><span class="p">([</span><span class="s">'amount'</span><span class="p">],</span> <span class="n">return_type</span><span class="o">=</span><span class="s">'dict'</span><span class="p">,</span> <span class="n">showfliers</span><span class="o">=</span><span class="bp">False</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">show</span><span class="p">()</span>
</code></pre></div></div>

<p><img src="/images/output_50_0.png" alt="_config.yml" /></p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># Let's see how many transactions are with amount value above 45 let's say
# number of transactions set as outliers, check with 45 as amount
</span><span class="n">transcript</span><span class="p">[</span><span class="n">transcript</span><span class="p">.</span><span class="n">amount</span> <span class="o">&gt;</span> <span class="mi">45</span><span class="p">].</span><span class="n">amount</span><span class="p">.</span><span class="n">count</span><span class="p">()</span>
</code></pre></div></div>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>863
</code></pre></div></div>

<p>Given the small number of transactions, 863 out of 306534, we will drop those transactions</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">transcript</span> <span class="o">=</span> <span class="n">pd</span><span class="p">.</span><span class="n">concat</span><span class="p">([</span><span class="n">transcript</span><span class="p">[</span><span class="n">transcript</span><span class="p">.</span><span class="n">amount</span> <span class="o">&lt;=</span> <span class="mi">45</span><span class="p">],</span> <span class="n">transcript</span><span class="p">[</span><span class="n">transcript</span><span class="p">.</span><span class="n">amount</span><span class="p">.</span><span class="n">isna</span><span class="p">()]])</span>
</code></pre></div></div>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># Now we have another look at the histogram 
</span><span class="k">print</span><span class="p">(</span><span class="n">transcript</span><span class="p">[</span><span class="n">transcript</span><span class="p">.</span><span class="n">event</span> <span class="o">==</span> <span class="s">'transaction'</span><span class="p">].</span><span class="n">amount</span><span class="p">.</span><span class="n">describe</span><span class="p">())</span>
<span class="n">print_histogram</span><span class="p">(</span><span class="n">transcript</span><span class="p">[</span><span class="n">transcript</span><span class="p">.</span><span class="n">event</span> <span class="o">==</span> <span class="s">'transaction'</span><span class="p">].</span><span class="n">amount</span><span class="p">)</span>
</code></pre></div></div>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>count    138090.000000
mean         11.182865
std           9.538444
min           0.050000
25%           2.750000
50%           8.780000
75%          17.880000
max          44.970000
Name: amount, dtype: float64
</code></pre></div></div>

<p><img src="/images/output_54_1.png" alt="_config.yml" /></p>

<p>This diagram has an interesting shape. I believe it is mostly due to the pricing of items at Starbucks, and the bump in the chart could be attributed to combination of items purchased. To confirm or refute some pricing data would be required.</p>

<h2 id="4-data-analysis-modelling-and-evaluation">4. Data Analysis, modelling, and evaluation</h2>
<p>In this section we will analyze the data in order to answer the different business questions that were posed earlier. However, before we get to the questions one by one, we will need to process transcript data to identify how customers interact with the offers, and how offers affect customer behavior.</p>

<p>The logic in the following function produces two main data frames, and 5 other data frames containing raw transaction metrics:</p>
<ol>
  <li><strong>offers_trx_details:</strong> This DataFrame is concerned with offers, how users interact with them, and the transactions that we assume are associated with them, as follows:
    <ul>
      <li>For all offers received we calculate how long it took to view the offer and how long to complete if applicable</li>
      <li>For each person for each offer (bogo or discount) we get all the transactions that happened between offer reception and completion. For those specific transactions we calculate avg time between transactions, mean transaction amount, and how many</li>
      <li>For informational offers we calculate the time from last transaction before the offer was viewed to the first transaction after the offer is viewed</li>
    </ul>
  </li>
  <li><strong>normal_trx_details:</strong> Those are transactions that took place outside the conditions outlined above. So they do not fall between an offer view and completion</li>
  <li><strong>raw_within_offer_trx_amounts:</strong> individual transaction amounts that took place during an offer</li>
  <li><strong>raw_within_offer_trx_durations:</strong> duration between consecutive transactions during an offer</li>
  <li><strong>raw_first_trx_from_last_durations:</strong> the duration between first commited transaction after receiving an information offer and last transaction</li>
  <li><strong>raw_without_offer_trx_amounts:</strong> individual transaction amounts that took place outside any offer</li>
  <li><strong>raw_without_offer_trx_durations:</strong> duration between consecutive transactions that took place outside offers</li>
</ol>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">process_transactions</span><span class="p">(</span><span class="n">transcript</span><span class="p">,</span> <span class="n">profile</span><span class="p">,</span> <span class="n">force_calc</span><span class="o">=</span><span class="bp">False</span><span class="p">):</span>
    <span class="s">'''
    Process transaction to identify which ones are associated to offers 
    and which are transaction that happened outside an offer. 
    
    The function looks at two main metrics (amount and duration).
    
    If the data has already been preprocssed it will be loaded. 
    Otherwise it will be processed again. If force_calc is set to True it will process anyway

        Parameters:
            transcript (pd.DataFrame): Transcript dataframe 
            profile (pd.DataFrame): Profile dataframe 
        Returns:
            raw_within_offer_trx_amounts (pd.DataFrame): individual transaction amounts that took place during an offer
            raw_within_offer_trx_durations (pd.DataFrame): duration between consecutive transactions during an offer
            raw_first_trx_from_last_durations (pd.DataFrame): the duration between first commited transaction after receiving an information offer and last transaction
            raw_without_offer_trx_amounts (pd.DataFrame): individual transaction amounts that took place outside any offer
            raw_without_offer_trx_durations (pd.DataFrame): duration between consecutive transactions that took place outside offers
    '''</span>
    
    <span class="c1"># If force_calc is not set try to load data from preprocessed files. 
</span>    <span class="c1"># If the data is not there, the data will be processed again
</span>    <span class="k">if</span> <span class="ow">not</span> <span class="n">force_calc</span><span class="p">:</span>
        <span class="k">try</span><span class="p">:</span>
            <span class="n">offers_trx_details</span> <span class="o">=</span> <span class="n">pd</span><span class="p">.</span><span class="n">read_pickle</span><span class="p">(</span><span class="s">'data/offers_trx_details.pkl'</span><span class="p">)</span>
            <span class="n">non_offers_trx_details</span> <span class="o">=</span> <span class="n">pd</span><span class="p">.</span><span class="n">read_pickle</span><span class="p">(</span><span class="s">'data/non_offers_trx_details.pkl'</span><span class="p">)</span>
            <span class="n">raw_within_offer_trx_amounts</span> <span class="o">=</span> <span class="n">pd</span><span class="p">.</span><span class="n">read_pickle</span><span class="p">(</span><span class="s">'data/raw_within_offer_trx_amounts.pkl'</span><span class="p">)</span>
            <span class="n">raw_within_offer_trx_durations</span> <span class="o">=</span> <span class="n">pd</span><span class="p">.</span><span class="n">read_pickle</span><span class="p">(</span><span class="s">'data/raw_within_offer_trx_durations.pkl'</span><span class="p">)</span>
            <span class="n">raw_first_trx_from_last_durations</span> <span class="o">=</span> <span class="n">pd</span><span class="p">.</span><span class="n">read_pickle</span><span class="p">(</span><span class="s">'data/raw_first_trx_from_last_durations.pkl'</span><span class="p">)</span>
            <span class="n">raw_without_offer_trx_amounts</span> <span class="o">=</span> <span class="n">pd</span><span class="p">.</span><span class="n">read_pickle</span><span class="p">(</span><span class="s">'data/raw_without_offer_trx_amounts.pkl'</span><span class="p">)</span>
            <span class="n">raw_without_offer_trx_durations</span> <span class="o">=</span> <span class="n">pd</span><span class="p">.</span><span class="n">read_pickle</span><span class="p">(</span><span class="s">'data/raw_without_offer_trx_durations.pkl'</span><span class="p">)</span>
            <span class="n">offers_trx_details</span><span class="p">.</span><span class="n">trx_count</span> <span class="o">=</span> <span class="p">[</span><span class="n">np</span><span class="p">.</span><span class="n">nan</span> <span class="k">if</span> <span class="n">w</span> <span class="o">==</span> <span class="mi">0</span> <span class="k">else</span> <span class="n">w</span> <span class="k">for</span> <span class="n">w</span> <span class="ow">in</span> <span class="n">offers_trx_details</span><span class="p">.</span><span class="n">trx_count</span><span class="p">]</span>
            <span class="k">return</span> <span class="p">(</span><span class="n">offers_trx_details</span><span class="p">,</span> 
                    <span class="n">non_offers_trx_details</span><span class="p">,</span> 
                    <span class="n">raw_within_offer_trx_amounts</span><span class="p">,</span> 
                    <span class="n">raw_within_offer_trx_durations</span><span class="p">,</span> 
                    <span class="n">raw_first_trx_from_last_durations</span><span class="p">,</span> 
                    <span class="n">raw_without_offer_trx_amounts</span><span class="p">,</span> 
                    <span class="n">raw_without_offer_trx_durations</span><span class="p">)</span>
        <span class="k">except</span><span class="p">:</span>
            <span class="k">print</span><span class="p">(</span><span class="s">'Could not load processed files. Starting processing:'</span><span class="p">)</span>
    
    <span class="n">transcript</span> <span class="o">=</span> <span class="n">transcript</span><span class="p">.</span><span class="n">sort_index</span><span class="p">()</span>
    
    <span class="c1"># Defining required dataframes
</span>    <span class="n">offers_trx_details</span> <span class="o">=</span> <span class="n">pd</span><span class="p">.</span><span class="n">DataFrame</span><span class="p">({</span><span class="s">'person_id'</span><span class="p">:</span> <span class="n">pd</span><span class="p">.</span><span class="n">Series</span><span class="p">([],</span> <span class="n">dtype</span><span class="o">=</span><span class="s">'str'</span><span class="p">),</span> 
                                       <span class="s">'offer_id'</span><span class="p">:</span> <span class="n">pd</span><span class="p">.</span><span class="n">Series</span><span class="p">([],</span> <span class="n">dtype</span><span class="o">=</span><span class="s">'str'</span><span class="p">),</span> 
                                       <span class="s">'viewed_time'</span><span class="p">:</span> <span class="n">pd</span><span class="p">.</span><span class="n">Series</span><span class="p">([],</span> <span class="n">dtype</span><span class="o">=</span><span class="s">'int'</span><span class="p">),</span> 
                                       <span class="s">'completed_time'</span><span class="p">:</span> <span class="n">pd</span><span class="p">.</span><span class="n">Series</span><span class="p">([],</span> <span class="n">dtype</span><span class="o">=</span><span class="s">'int'</span><span class="p">),</span> 
                                       <span class="s">'first_trx_time_from_last_trx'</span><span class="p">:</span> <span class="n">pd</span><span class="p">.</span><span class="n">Series</span><span class="p">([],</span> <span class="n">dtype</span><span class="o">=</span><span class="s">'int'</span><span class="p">),</span>
                                       <span class="s">'trx_count'</span><span class="p">:</span> <span class="n">pd</span><span class="p">.</span><span class="n">Series</span><span class="p">([],</span> <span class="n">dtype</span><span class="o">=</span><span class="s">'int'</span><span class="p">),</span> 
                                       <span class="s">'avg_trx_amount'</span><span class="p">:</span> <span class="n">pd</span><span class="p">.</span><span class="n">Series</span><span class="p">([],</span> <span class="n">dtype</span><span class="o">=</span><span class="s">'float'</span><span class="p">),</span>
                                       <span class="s">'avg_time_btwn_trx'</span><span class="p">:</span> <span class="n">pd</span><span class="p">.</span><span class="n">Series</span><span class="p">([],</span> <span class="n">dtype</span><span class="o">=</span><span class="s">'float'</span><span class="p">)</span>
                                      <span class="p">})</span>
    <span class="n">non_offers_trx_details</span> <span class="o">=</span> <span class="n">pd</span><span class="p">.</span><span class="n">DataFrame</span><span class="p">({</span><span class="s">'person_id'</span><span class="p">:</span> <span class="n">pd</span><span class="p">.</span><span class="n">Series</span><span class="p">([],</span> <span class="n">dtype</span><span class="o">=</span><span class="s">'str'</span><span class="p">),</span> 
                                           <span class="s">'trx_count'</span><span class="p">:</span> <span class="n">pd</span><span class="p">.</span><span class="n">Series</span><span class="p">([],</span> <span class="n">dtype</span><span class="o">=</span><span class="s">'int'</span><span class="p">),</span> 
                                           <span class="s">'avg_trx_amount'</span><span class="p">:</span> <span class="n">pd</span><span class="p">.</span><span class="n">Series</span><span class="p">([],</span> <span class="n">dtype</span><span class="o">=</span><span class="s">'float'</span><span class="p">),</span> 
                                           <span class="s">'avg_time_btwn_consec_trx'</span><span class="p">:</span> <span class="n">pd</span><span class="p">.</span><span class="n">Series</span><span class="p">([],</span> <span class="n">dtype</span><span class="o">=</span><span class="s">'float'</span><span class="p">)</span>
                                          <span class="p">})</span>
    
    <span class="n">raw_within_offer_trx_amounts</span> <span class="o">=</span> <span class="n">pd</span><span class="p">.</span><span class="n">DataFrame</span><span class="p">({</span><span class="s">'person_id'</span><span class="p">:</span> <span class="n">pd</span><span class="p">.</span><span class="n">Series</span><span class="p">([],</span> <span class="n">dtype</span><span class="o">=</span><span class="s">'str'</span><span class="p">),</span> 
                                                 <span class="s">'offer_id'</span><span class="p">:</span> <span class="n">pd</span><span class="p">.</span><span class="n">Series</span><span class="p">([],</span> <span class="n">dtype</span><span class="o">=</span><span class="s">'str'</span><span class="p">),</span> 
                                                 <span class="s">'trx_amount'</span><span class="p">:</span> <span class="n">pd</span><span class="p">.</span><span class="n">Series</span><span class="p">([],</span> <span class="n">dtype</span><span class="o">=</span><span class="s">'float'</span><span class="p">)</span>
                                                <span class="p">})</span>
    <span class="n">raw_within_offer_trx_durations</span> <span class="o">=</span> <span class="n">pd</span><span class="p">.</span><span class="n">DataFrame</span><span class="p">({</span><span class="s">'person_id'</span><span class="p">:</span> <span class="n">pd</span><span class="p">.</span><span class="n">Series</span><span class="p">([],</span> <span class="n">dtype</span><span class="o">=</span><span class="s">'str'</span><span class="p">),</span> 
                                                   <span class="s">'offer_id'</span><span class="p">:</span> <span class="n">pd</span><span class="p">.</span><span class="n">Series</span><span class="p">([],</span> <span class="n">dtype</span><span class="o">=</span><span class="s">'str'</span><span class="p">),</span> 
                                                   <span class="s">'trx_duration'</span><span class="p">:</span> <span class="n">pd</span><span class="p">.</span><span class="n">Series</span><span class="p">([],</span> <span class="n">dtype</span><span class="o">=</span><span class="s">'float'</span><span class="p">)</span>
                                                  <span class="p">})</span>
    <span class="n">raw_first_trx_from_last_durations</span> <span class="o">=</span> <span class="n">pd</span><span class="p">.</span><span class="n">DataFrame</span><span class="p">({</span><span class="s">'person_id'</span><span class="p">:</span> <span class="n">pd</span><span class="p">.</span><span class="n">Series</span><span class="p">([],</span> <span class="n">dtype</span><span class="o">=</span><span class="s">'str'</span><span class="p">),</span> 
                                                      <span class="s">'offer_id'</span><span class="p">:</span> <span class="n">pd</span><span class="p">.</span><span class="n">Series</span><span class="p">([],</span> <span class="n">dtype</span><span class="o">=</span><span class="s">'str'</span><span class="p">),</span> 
                                                      <span class="s">'trx_duration'</span><span class="p">:</span> <span class="n">pd</span><span class="p">.</span><span class="n">Series</span><span class="p">([],</span> <span class="n">dtype</span><span class="o">=</span><span class="s">'float'</span><span class="p">)</span>
                                                     <span class="p">})</span>
    <span class="n">raw_without_offer_trx_amounts</span> <span class="o">=</span> <span class="n">pd</span><span class="p">.</span><span class="n">DataFrame</span><span class="p">({</span><span class="s">'person_id'</span><span class="p">:</span> <span class="n">pd</span><span class="p">.</span><span class="n">Series</span><span class="p">([],</span> <span class="n">dtype</span><span class="o">=</span><span class="s">'str'</span><span class="p">),</span> 
                                                  <span class="s">'trx_amount'</span><span class="p">:</span> <span class="n">pd</span><span class="p">.</span><span class="n">Series</span><span class="p">([],</span> <span class="n">dtype</span><span class="o">=</span><span class="s">'float'</span><span class="p">)</span>
                                                 <span class="p">})</span>
    <span class="n">raw_without_offer_trx_durations</span> <span class="o">=</span> <span class="n">pd</span><span class="p">.</span><span class="n">DataFrame</span><span class="p">({</span><span class="s">'person_id'</span><span class="p">:</span> <span class="n">pd</span><span class="p">.</span><span class="n">Series</span><span class="p">([],</span> <span class="n">dtype</span><span class="o">=</span><span class="s">'str'</span><span class="p">),</span> 
                                                    <span class="s">'trx_duration'</span><span class="p">:</span> <span class="n">pd</span><span class="p">.</span><span class="n">Series</span><span class="p">([],</span> <span class="n">dtype</span><span class="o">=</span><span class="s">'float'</span><span class="p">)</span>
                                                   <span class="p">})</span>
    
    <span class="c1"># Go through person by person
</span>    <span class="k">for</span> <span class="n">person</span> <span class="ow">in</span> <span class="n">tqdm</span><span class="p">(</span><span class="n">profile</span><span class="p">.</span><span class="nb">id</span><span class="p">):</span>
        <span class="c1"># Get all transaction per person
</span>        <span class="n">pt</span> <span class="o">=</span> <span class="n">transcript</span><span class="p">[</span><span class="n">transcript</span><span class="p">.</span><span class="n">person</span> <span class="o">==</span> <span class="n">person</span><span class="p">]</span>
        
        <span class="c1"># Flags to be used when we start checking if offers were received or viewed 
</span>        <span class="n">is_offer_received</span> <span class="o">=</span> <span class="bp">False</span>
        <span class="n">is_offer_viewed</span> <span class="o">=</span> <span class="bp">False</span>

        <span class="c1"># Go through all customer transactions and find offers events and transactions
</span>        <span class="n">received_offers</span> <span class="o">=</span> <span class="p">{}</span>
        <span class="n">viewed_offers</span> <span class="o">=</span> <span class="p">{}</span>
        <span class="n">completed_offers</span> <span class="o">=</span> <span class="p">{}</span>
        <span class="n">transactions</span> <span class="o">=</span> <span class="p">{}</span>
        <span class="n">excluded_transactions</span><span class="o">=</span> <span class="p">[]</span>
        <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">pt</span><span class="p">.</span><span class="n">shape</span><span class="p">[</span><span class="mi">0</span><span class="p">]):</span>
            <span class="n">t</span> <span class="o">=</span> <span class="n">pt</span><span class="p">.</span><span class="n">iloc</span><span class="p">[</span><span class="n">i</span><span class="p">]</span>
            <span class="k">if</span> <span class="n">t</span><span class="p">.</span><span class="n">event</span> <span class="o">==</span> <span class="s">'offer received'</span><span class="p">:</span>
                <span class="n">received_offers</span><span class="p">[</span><span class="n">t</span><span class="p">.</span><span class="n">name</span><span class="p">]</span> <span class="o">=</span> <span class="n">t</span>
            <span class="k">elif</span> <span class="n">t</span><span class="p">.</span><span class="n">event</span> <span class="o">==</span> <span class="s">'offer viewed'</span><span class="p">:</span>
                <span class="n">viewed_offers</span><span class="p">[</span><span class="n">t</span><span class="p">.</span><span class="n">name</span><span class="p">]</span> <span class="o">=</span> <span class="n">t</span>
            <span class="k">elif</span> <span class="n">t</span><span class="p">.</span><span class="n">event</span> <span class="o">==</span> <span class="s">'offer completed'</span><span class="p">:</span>
                <span class="n">completed_offers</span><span class="p">[</span><span class="n">t</span><span class="p">.</span><span class="n">name</span><span class="p">]</span> <span class="o">=</span> <span class="n">t</span>
            <span class="k">elif</span> <span class="n">t</span><span class="p">.</span><span class="n">event</span> <span class="o">==</span> <span class="s">'transaction'</span><span class="p">:</span>
                <span class="n">transactions</span><span class="p">[</span><span class="n">t</span><span class="p">.</span><span class="n">name</span><span class="p">]</span> <span class="o">=</span> <span class="n">t</span>
        
        <span class="c1"># Go through received offers one by one
</span>        <span class="k">for</span> <span class="n">offer_index</span> <span class="ow">in</span> <span class="n">received_offers</span><span class="p">:</span>
            <span class="n">offer_id</span> <span class="o">=</span> <span class="n">received_offers</span><span class="p">[</span><span class="n">offer_index</span><span class="p">].</span><span class="n">offer_id</span>
            <span class="n">offer_time</span> <span class="o">=</span> <span class="n">received_offers</span><span class="p">[</span><span class="n">offer_index</span><span class="p">].</span><span class="n">time</span>
            <span class="n">next_same_offer_index</span> <span class="o">=</span> <span class="bp">None</span>

            <span class="c1"># Find the next offer with the same offer_id
</span>            <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="n">received_offers</span><span class="p">:</span>
                <span class="k">if</span> <span class="n">i</span> <span class="o">&gt;</span> <span class="n">offer_index</span> <span class="ow">and</span> <span class="n">offer_id</span> <span class="o">==</span> <span class="n">received_offers</span><span class="p">[</span><span class="n">i</span><span class="p">].</span><span class="n">offer_id</span><span class="p">:</span>
                    <span class="n">next_same_offer_index</span> <span class="o">=</span> <span class="n">i</span>

            <span class="c1"># Has the offer been viewed?
</span>            <span class="n">is_offer_viewed</span> <span class="o">=</span> <span class="bp">False</span>
            <span class="n">view_index</span> <span class="o">=</span> <span class="bp">None</span>
            <span class="n">view_time</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">nan</span>
            <span class="k">for</span> <span class="n">j</span> <span class="ow">in</span> <span class="n">viewed_offers</span><span class="p">:</span>
                <span class="k">if</span> <span class="n">j</span> <span class="o">&gt;</span> <span class="n">offer_index</span> <span class="ow">and</span> <span class="n">offer_id</span> <span class="o">==</span> <span class="n">viewed_offers</span><span class="p">[</span><span class="n">j</span><span class="p">].</span><span class="n">offer_id</span> <span class="ow">and</span> <span class="p">(</span><span class="n">next_same_offer_index</span> <span class="ow">is</span> <span class="bp">None</span> 
                                                                                  <span class="ow">or</span> <span class="n">j</span> <span class="o">&lt;</span> <span class="n">next_same_offer_index</span><span class="p">):</span>
                    <span class="n">is_offer_viewed</span> <span class="o">=</span> <span class="bp">True</span>
                    <span class="n">view_index</span> <span class="o">=</span> <span class="n">j</span>
                    <span class="n">view_time</span> <span class="o">=</span> <span class="n">viewed_offers</span><span class="p">[</span><span class="n">j</span><span class="p">].</span><span class="n">time</span>
                    <span class="k">break</span>

            
            <span class="c1"># If it is an information offer skip looking for completion. however, calculate time from last trx
</span>            <span class="c1"># Also check if it is within promotion period
</span>            <span class="c1"># Also make sure that the offer has been viewed
</span>            <span class="n">first_trx_time_from_last_trx</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">nan</span>
            <span class="k">if</span> <span class="n">is_offer_viewed</span><span class="p">:</span>
                <span class="n">transaction_index</span> <span class="o">=</span> <span class="bp">None</span>
                <span class="n">previous_transaction_index</span> <span class="o">=</span> <span class="bp">None</span>
                <span class="n">first_trx_time_from_last_trx</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">nan</span>
                <span class="k">for</span> <span class="n">t</span> <span class="ow">in</span> <span class="n">transactions</span><span class="p">:</span>
                    <span class="k">if</span> <span class="n">t</span> <span class="o">&gt;=</span> <span class="n">view_index</span> <span class="ow">and</span> <span class="n">previous_transaction_index</span> <span class="ow">is</span> <span class="ow">not</span> <span class="bp">None</span><span class="p">:</span>
                        <span class="k">if</span> <span class="n">is_within_period</span><span class="p">(</span><span class="n">offer_id</span><span class="p">,</span> <span class="n">transactions</span><span class="p">[</span><span class="n">t</span><span class="p">].</span><span class="n">time</span> <span class="o">-</span> <span class="n">offer_time</span><span class="p">):</span>
                            <span class="n">first_trx_time_from_last_trx</span> <span class="o">=</span> <span class="n">transactions</span><span class="p">[</span><span class="n">t</span><span class="p">].</span><span class="n">time</span> <span class="o">-</span> <span class="n">transactions</span><span class="p">[</span><span class="n">previous_transaction_index</span><span class="p">].</span><span class="n">time</span>
                            <span class="n">excluded_transactions</span><span class="p">.</span><span class="n">append</span><span class="p">(</span><span class="n">t</span><span class="p">)</span>
                        <span class="k">break</span>
                    <span class="k">elif</span> <span class="n">t</span> <span class="o">&lt;</span> <span class="n">view_index</span><span class="p">:</span>
                        <span class="n">previous_transaction_index</span> <span class="o">=</span> <span class="n">t</span>

            <span class="c1"># has the offer been completed?
</span>            <span class="n">is_offer_completed</span> <span class="o">=</span> <span class="bp">False</span>
            <span class="n">completion_index</span> <span class="o">=</span> <span class="bp">None</span>
            <span class="n">completion_time</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">nan</span>
            <span class="k">for</span> <span class="n">k</span> <span class="ow">in</span> <span class="n">completed_offers</span><span class="p">:</span>
                <span class="k">if</span> <span class="n">k</span> <span class="o">&gt;</span> <span class="n">offer_index</span> <span class="ow">and</span> <span class="n">offer_id</span> <span class="o">==</span> <span class="n">completed_offers</span><span class="p">[</span><span class="n">k</span><span class="p">].</span><span class="n">offer_id</span> <span class="ow">and</span> <span class="p">(</span><span class="n">next_same_offer_index</span> <span class="ow">is</span> <span class="bp">None</span> 
                                                                                     <span class="ow">or</span> <span class="n">k</span> <span class="o">&lt;</span> <span class="n">next_same_offer_index</span><span class="p">):</span>
                    <span class="n">is_offer_completed</span> <span class="o">=</span> <span class="bp">True</span>
                    <span class="n">completion_index</span> <span class="o">=</span> <span class="n">k</span>
                    <span class="n">completion_time</span> <span class="o">=</span> <span class="n">completed_offers</span><span class="p">[</span><span class="n">k</span><span class="p">].</span><span class="n">time</span>
                    <span class="k">break</span>
            
            <span class="c1"># Handle the case if the offer has been viewed after completion
</span>            <span class="k">if</span> <span class="n">is_offer_viewed</span> <span class="ow">and</span> <span class="n">is_offer_completed</span> <span class="ow">and</span> <span class="n">view_index</span> <span class="o">&gt;=</span> <span class="n">completion_index</span><span class="p">:</span>
                <span class="n">is_offer_viewed</span> <span class="o">=</span> <span class="bp">False</span>
                <span class="n">view_index</span> <span class="o">=</span> <span class="bp">None</span>
                <span class="n">view_time</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">nan</span>

            <span class="c1"># KEEP IN MIND THAT WE ARE DISCARDING THE FIRST TRANSACTIONS THAT HAPPENS AFTER INFO IF WITHIN DURATION
</span>            <span class="c1"># Find within offer transactions
</span>            <span class="n">within_offer_trx_amounts</span> <span class="o">=</span> <span class="p">[]</span>
            <span class="n">within_offer_trx_durations</span> <span class="o">=</span> <span class="p">[]</span>
            <span class="n">prev_trx_time</span> <span class="o">=</span> <span class="bp">None</span>
            <span class="k">for</span> <span class="n">t</span> <span class="ow">in</span> <span class="n">transactions</span><span class="p">:</span>
                <span class="k">if</span> <span class="n">t</span> <span class="o">&gt;</span> <span class="n">offer_index</span> <span class="ow">and</span> <span class="n">is_offer_completed</span> <span class="ow">and</span> <span class="n">t</span> <span class="o">&lt;</span> <span class="n">completion_index</span><span class="p">:</span>
                    <span class="n">within_offer_trx_amounts</span><span class="p">.</span><span class="n">append</span><span class="p">(</span><span class="n">transactions</span><span class="p">[</span><span class="n">t</span><span class="p">].</span><span class="n">amount</span><span class="p">)</span>
                    <span class="k">if</span> <span class="n">prev_trx_time</span> <span class="ow">is</span> <span class="ow">not</span> <span class="bp">None</span><span class="p">:</span>
                        <span class="n">within_offer_trx_durations</span><span class="p">.</span><span class="n">append</span><span class="p">(</span><span class="n">transactions</span><span class="p">[</span><span class="n">t</span><span class="p">].</span><span class="n">time</span> <span class="o">-</span> <span class="n">prev_trx_time</span><span class="p">)</span>
                    <span class="n">prev_trx_time</span> <span class="o">=</span> <span class="n">transactions</span><span class="p">[</span><span class="n">t</span><span class="p">].</span><span class="n">time</span>
                    <span class="k">if</span> <span class="n">is_offer_viewed</span><span class="p">:</span>
                        <span class="n">excluded_transactions</span><span class="p">.</span><span class="n">append</span><span class="p">(</span><span class="n">t</span><span class="p">)</span>
            
            <span class="c1"># Extract raw within offer transactions amounts
</span>            <span class="c1"># raw_within_offer_trx_amounts
</span>            <span class="n">temp_raw_within_offer_trx_amounts</span> <span class="o">=</span> <span class="n">pd</span><span class="p">.</span><span class="n">DataFrame</span><span class="p">().</span><span class="n">reindex</span><span class="p">(</span>
                <span class="n">columns</span><span class="o">=</span><span class="n">raw_within_offer_trx_amounts</span><span class="p">.</span><span class="n">columns</span><span class="p">)</span>
            <span class="n">temp_raw_within_offer_trx_amounts</span><span class="p">.</span><span class="n">trx_amount</span> <span class="o">=</span> <span class="n">within_offer_trx_amounts</span>
            <span class="n">temp_raw_within_offer_trx_amounts</span><span class="p">.</span><span class="n">person_id</span> <span class="o">=</span> <span class="n">temp_raw_within_offer_trx_amounts</span><span class="p">.</span><span class="n">person_id</span><span class="p">.</span><span class="n">fillna</span><span class="p">(</span><span class="n">person</span><span class="p">)</span>
            <span class="n">temp_raw_within_offer_trx_amounts</span><span class="p">.</span><span class="n">offer_id</span> <span class="o">=</span> <span class="n">temp_raw_within_offer_trx_amounts</span><span class="p">.</span><span class="n">offer_id</span><span class="p">.</span><span class="n">fillna</span><span class="p">(</span><span class="n">offer_id</span><span class="p">)</span>
            <span class="n">raw_within_offer_trx_amounts</span> <span class="o">=</span> <span class="n">raw_within_offer_trx_amounts</span><span class="p">.</span><span class="n">append</span><span class="p">(</span>
                <span class="n">temp_raw_within_offer_trx_amounts</span><span class="p">)</span>
            
            <span class="c1"># Extract raw within offer transactions durations
</span>            <span class="c1"># raw_within_offer_trx_durations
</span>            <span class="n">temp_raw_within_offer_trx_durations</span> <span class="o">=</span> <span class="n">pd</span><span class="p">.</span><span class="n">DataFrame</span><span class="p">().</span><span class="n">reindex</span><span class="p">(</span>
                <span class="n">columns</span><span class="o">=</span><span class="n">raw_within_offer_trx_durations</span><span class="p">.</span><span class="n">columns</span><span class="p">)</span>
            <span class="n">temp_raw_within_offer_trx_durations</span><span class="p">.</span><span class="n">trx_duration</span> <span class="o">=</span> <span class="n">within_offer_trx_durations</span>
            <span class="n">temp_raw_within_offer_trx_durations</span><span class="p">.</span><span class="n">person_id</span> <span class="o">=</span> <span class="n">temp_raw_within_offer_trx_durations</span><span class="p">.</span><span class="n">person_id</span><span class="p">.</span><span class="n">fillna</span><span class="p">(</span><span class="n">person</span><span class="p">)</span>
            <span class="n">temp_raw_within_offer_trx_durations</span><span class="p">.</span><span class="n">offer_id</span> <span class="o">=</span> <span class="n">temp_raw_within_offer_trx_durations</span><span class="p">.</span><span class="n">offer_id</span><span class="p">.</span><span class="n">fillna</span><span class="p">(</span><span class="n">offer_id</span><span class="p">)</span>
            <span class="n">raw_within_offer_trx_durations</span> <span class="o">=</span> <span class="n">raw_within_offer_trx_durations</span><span class="p">.</span><span class="n">append</span><span class="p">(</span>
                <span class="n">temp_raw_within_offer_trx_durations</span><span class="p">)</span>
            
            <span class="c1"># Extract raw duration between transactions after receiving info offer
</span>            <span class="c1"># raw_first_trx_from_last_durations
</span>            <span class="n">temp_raw_first_trx_from_last_durations</span> <span class="o">=</span> <span class="n">pd</span><span class="p">.</span><span class="n">DataFrame</span><span class="p">().</span><span class="n">reindex</span><span class="p">(</span>
                <span class="n">columns</span><span class="o">=</span><span class="n">raw_first_trx_from_last_durations</span><span class="p">.</span><span class="n">columns</span><span class="p">)</span>
            <span class="n">temp_raw_first_trx_from_last_durations</span><span class="p">.</span><span class="n">trx_duration</span> <span class="o">=</span> <span class="p">[</span><span class="n">first_trx_time_from_last_trx</span><span class="p">]</span>
            <span class="n">temp_raw_first_trx_from_last_durations</span><span class="p">.</span><span class="n">person_id</span> <span class="o">=</span> <span class="n">temp_raw_first_trx_from_last_durations</span><span class="p">.</span><span class="n">person_id</span><span class="p">.</span><span class="n">fillna</span><span class="p">(</span><span class="n">person</span><span class="p">)</span>
            <span class="n">temp_raw_first_trx_from_last_durations</span><span class="p">.</span><span class="n">offer_id</span> <span class="o">=</span> <span class="n">temp_raw_first_trx_from_last_durations</span><span class="p">.</span><span class="n">offer_id</span><span class="p">.</span><span class="n">fillna</span><span class="p">(</span><span class="n">offer_id</span><span class="p">)</span>
            <span class="n">raw_first_trx_from_last_durations</span> <span class="o">=</span> <span class="n">raw_first_trx_from_last_durations</span><span class="p">.</span><span class="n">append</span><span class="p">(</span>
                <span class="n">temp_raw_first_trx_from_last_durations</span><span class="p">)</span>
            
            <span class="c1"># Calculate aggregations for offers_trx_details dataframe
</span>            <span class="n">within_offer_trx_amounts_count</span> <span class="o">=</span> <span class="nb">len</span><span class="p">(</span><span class="n">within_offer_trx_amounts</span><span class="p">)</span>
            <span class="n">within_offer_trx_amounts_avg</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">nan</span>
            <span class="k">if</span> <span class="n">within_offer_trx_amounts_count</span> <span class="o">&gt;</span> <span class="mi">0</span><span class="p">:</span>
                <span class="n">within_offer_trx_amounts_avg</span> <span class="o">=</span> <span class="nb">round</span><span class="p">(</span><span class="n">np</span><span class="p">.</span><span class="n">mean</span><span class="p">(</span><span class="n">within_offer_trx_amounts</span><span class="p">),</span> <span class="mi">2</span><span class="p">)</span>
            <span class="n">within_offer_trx_durations_avg</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">nan</span>
            <span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="n">within_offer_trx_durations</span><span class="p">)</span> <span class="o">&gt;</span> <span class="mi">0</span><span class="p">:</span>
                <span class="n">within_offer_trx_durations_avg</span> <span class="o">=</span> <span class="nb">round</span><span class="p">(</span><span class="n">np</span><span class="p">.</span><span class="n">mean</span><span class="p">(</span><span class="n">within_offer_trx_durations</span><span class="p">),</span> <span class="mi">2</span><span class="p">)</span>
            
            <span class="c1"># Create row to be added to offers_trx_details
</span>            <span class="n">od</span> <span class="o">=</span> <span class="p">{</span><span class="s">'person_id'</span><span class="p">:</span> <span class="n">person</span><span class="p">,</span> 
                  <span class="s">'offer_id'</span><span class="p">:</span> <span class="n">offer_id</span><span class="p">,</span>
                  <span class="s">'viewed_time'</span><span class="p">:</span> <span class="n">view_time</span><span class="o">-</span><span class="n">offer_time</span><span class="p">,</span>
                  <span class="s">'completed_time'</span><span class="p">:</span> <span class="n">completion_time</span><span class="o">-</span><span class="n">coalesce_int</span><span class="p">([</span><span class="n">view_time</span><span class="p">,</span> <span class="n">offer_time</span><span class="p">]),</span>
                  <span class="s">'first_trx_time_from_last_trx'</span><span class="p">:</span> <span class="n">first_trx_time_from_last_trx</span><span class="p">,</span>
                  <span class="s">'trx_count'</span><span class="p">:</span> <span class="n">within_offer_trx_amounts_count</span><span class="p">,</span>
                  <span class="s">'avg_trx_amount'</span><span class="p">:</span> <span class="n">within_offer_trx_amounts_avg</span><span class="p">,</span>
                  <span class="s">'avg_time_btwn_trx'</span><span class="p">:</span> <span class="n">within_offer_trx_durations_avg</span>
                 <span class="p">}</span>
            <span class="n">offers_trx_details</span><span class="p">.</span><span class="n">loc</span><span class="p">[</span><span class="nb">len</span><span class="p">(</span><span class="n">offers_trx_details</span><span class="p">)]</span> <span class="o">=</span> <span class="n">od</span>

        <span class="c1"># Process all transactions that do not fall within an offer
</span>        <span class="c1"># Get count, average_amount, time_between_transactions
</span>        <span class="n">independent_transaction_amounts</span> <span class="o">=</span> <span class="p">[]</span>
        <span class="n">time_between_transactions</span> <span class="o">=</span> <span class="p">[]</span>
        <span class="n">previous_trx</span> <span class="o">=</span> <span class="bp">None</span>
        <span class="k">for</span> <span class="n">t</span> <span class="ow">in</span> <span class="n">transactions</span><span class="p">:</span>
            <span class="k">if</span> <span class="n">t</span> <span class="ow">not</span> <span class="ow">in</span> <span class="n">excluded_transactions</span><span class="p">:</span>
                <span class="n">independent_transaction_amounts</span><span class="p">.</span><span class="n">append</span><span class="p">(</span><span class="n">transactions</span><span class="p">[</span><span class="n">t</span><span class="p">].</span><span class="n">amount</span><span class="p">)</span>
                <span class="k">if</span> <span class="n">previous_trx</span> <span class="ow">is</span> <span class="ow">not</span> <span class="bp">None</span><span class="p">:</span>
                    <span class="n">time_between_transactions</span><span class="p">.</span><span class="n">append</span><span class="p">(</span><span class="n">transactions</span><span class="p">[</span><span class="n">t</span><span class="p">].</span><span class="n">time</span><span class="o">-</span><span class="n">transactions</span><span class="p">[</span><span class="n">previous_trx</span><span class="p">].</span><span class="n">time</span><span class="p">)</span>
                <span class="n">previous_trx</span> <span class="o">=</span> <span class="n">t</span>
            <span class="k">else</span><span class="p">:</span>
                <span class="n">previous_trx</span> <span class="o">=</span> <span class="bp">None</span>
        
        <span class="c1"># Fill raw without offer transactions amounts
</span>        <span class="c1"># raw_without_offer_trx_amounts
</span>        <span class="n">temp_raw_without_offer_trx_amounts</span> <span class="o">=</span> <span class="n">pd</span><span class="p">.</span><span class="n">DataFrame</span><span class="p">().</span><span class="n">reindex</span><span class="p">(</span>
                <span class="n">columns</span><span class="o">=</span><span class="n">raw_without_offer_trx_amounts</span><span class="p">.</span><span class="n">columns</span><span class="p">)</span>
        <span class="n">temp_raw_without_offer_trx_amounts</span><span class="p">.</span><span class="n">trx_amount</span> <span class="o">=</span> <span class="n">independent_transaction_amounts</span>
        <span class="n">temp_raw_without_offer_trx_amounts</span><span class="p">.</span><span class="n">person_id</span> <span class="o">=</span> <span class="n">temp_raw_without_offer_trx_amounts</span><span class="p">.</span><span class="n">person_id</span><span class="p">.</span><span class="n">fillna</span><span class="p">(</span><span class="n">person</span><span class="p">)</span>
        <span class="n">raw_without_offer_trx_amounts</span> <span class="o">=</span> <span class="n">raw_without_offer_trx_amounts</span><span class="p">.</span><span class="n">append</span><span class="p">(</span>
            <span class="n">temp_raw_without_offer_trx_amounts</span><span class="p">)</span>
        
        <span class="c1"># Fill raw without offer transactions durations
</span>        <span class="c1"># raw_without_offer_trx_durations
</span>        <span class="n">temp_raw_without_offer_trx_durations</span> <span class="o">=</span> <span class="n">pd</span><span class="p">.</span><span class="n">DataFrame</span><span class="p">().</span><span class="n">reindex</span><span class="p">(</span>
                <span class="n">columns</span><span class="o">=</span><span class="n">raw_without_offer_trx_durations</span><span class="p">.</span><span class="n">columns</span><span class="p">)</span>
        <span class="n">temp_raw_without_offer_trx_durations</span><span class="p">.</span><span class="n">trx_duration</span> <span class="o">=</span> <span class="n">time_between_transactions</span>
        <span class="n">temp_raw_without_offer_trx_durations</span><span class="p">.</span><span class="n">person_id</span> <span class="o">=</span> <span class="n">temp_raw_without_offer_trx_durations</span><span class="p">.</span><span class="n">person_id</span><span class="p">.</span><span class="n">fillna</span><span class="p">(</span><span class="n">person</span><span class="p">)</span>
        <span class="n">raw_without_offer_trx_durations</span> <span class="o">=</span> <span class="n">raw_without_offer_trx_durations</span><span class="p">.</span><span class="n">append</span><span class="p">(</span>
            <span class="n">temp_raw_without_offer_trx_durations</span><span class="p">)</span>
        
        <span class="c1"># 'person_id', 'trx_count', 'avg_trx_amount', 'avg_time_btwn_consec_trx'
</span>        <span class="n">trx_amounts_count</span> <span class="o">=</span> <span class="nb">len</span><span class="p">(</span><span class="n">independent_transaction_amounts</span><span class="p">)</span>
        <span class="n">trx_amounts_avg</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">nan</span>
        <span class="n">time_between_trx_avg</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">nan</span>
        <span class="k">if</span> <span class="n">trx_amounts_count</span> <span class="o">&gt;</span> <span class="mi">0</span><span class="p">:</span>
            <span class="n">trx_amounts_avg</span> <span class="o">=</span> <span class="nb">round</span><span class="p">(</span><span class="n">np</span><span class="p">.</span><span class="n">mean</span><span class="p">(</span><span class="n">independent_transaction_amounts</span><span class="p">),</span> <span class="mi">2</span><span class="p">)</span>
        <span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="n">time_between_transactions</span><span class="p">)</span> <span class="o">&gt;</span> <span class="mi">0</span><span class="p">:</span>
            <span class="n">time_between_trx_avg</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">mean</span><span class="p">(</span><span class="n">time_between_transactions</span><span class="p">)</span>
        
        <span class="c1"># Create row to be added to non_offers_trx_details
</span>        <span class="n">nod</span> <span class="o">=</span> <span class="p">{</span><span class="s">'person_id'</span><span class="p">:</span> <span class="n">person</span><span class="p">,</span> 
               <span class="s">'trx_count'</span><span class="p">:</span> <span class="n">trx_amounts_count</span><span class="p">,</span> 
               <span class="s">'avg_trx_amount'</span><span class="p">:</span> <span class="n">trx_amounts_avg</span><span class="p">,</span> 
               <span class="s">'avg_time_btwn_consec_trx'</span><span class="p">:</span> <span class="n">time_between_trx_avg</span>
              <span class="p">}</span>
        <span class="n">non_offers_trx_details</span><span class="p">.</span><span class="n">loc</span><span class="p">[</span><span class="nb">len</span><span class="p">(</span><span class="n">non_offers_trx_details</span><span class="p">)]</span> <span class="o">=</span> <span class="n">nod</span>
    
    <span class="n">offers_trx_details</span><span class="p">.</span><span class="n">trx_count</span> <span class="o">=</span> <span class="p">[</span><span class="n">np</span><span class="p">.</span><span class="n">nan</span> <span class="k">if</span> <span class="n">w</span> <span class="o">==</span> <span class="mi">0</span> <span class="k">else</span> <span class="n">w</span> <span class="k">for</span> <span class="n">w</span> <span class="ow">in</span> <span class="n">offers_trx_details</span><span class="p">.</span><span class="n">trx_count</span><span class="p">]</span>
    
    <span class="c1"># Once done write processed data to pickle files
</span>    <span class="k">print</span><span class="p">(</span><span class="s">'Saving processed transactions'</span><span class="p">)</span>
    <span class="n">offers_trx_details</span><span class="p">.</span><span class="n">to_pickle</span><span class="p">(</span><span class="s">'data/offers_trx_details.pkl'</span><span class="p">)</span>
    <span class="n">non_offers_trx_details</span><span class="p">.</span><span class="n">to_pickle</span><span class="p">(</span><span class="s">'data/non_offers_trx_details.pkl'</span><span class="p">)</span>
    <span class="n">raw_within_offer_trx_amounts</span><span class="p">.</span><span class="n">to_pickle</span><span class="p">(</span><span class="s">'data/raw_within_offer_trx_amounts.pkl'</span><span class="p">)</span>
    <span class="n">raw_within_offer_trx_durations</span><span class="p">.</span><span class="n">to_pickle</span><span class="p">(</span><span class="s">'data/raw_within_offer_trx_durations.pkl'</span><span class="p">)</span>
    <span class="n">raw_first_trx_from_last_durations</span><span class="p">.</span><span class="n">to_pickle</span><span class="p">(</span><span class="s">'data/raw_first_trx_from_last_durations.pkl'</span><span class="p">)</span>
    <span class="n">raw_without_offer_trx_amounts</span><span class="p">.</span><span class="n">to_pickle</span><span class="p">(</span><span class="s">'data/raw_without_offer_trx_amounts.pkl'</span><span class="p">)</span>
    <span class="n">raw_without_offer_trx_durations</span><span class="p">.</span><span class="n">to_pickle</span><span class="p">(</span><span class="s">'data/raw_without_offer_trx_durations.pkl'</span><span class="p">)</span>
    <span class="k">return</span> <span class="p">(</span><span class="n">offers_trx_details</span><span class="p">,</span> 
            <span class="n">non_offers_trx_details</span><span class="p">,</span> 
            <span class="n">raw_within_offer_trx_amounts</span><span class="p">,</span> 
            <span class="n">raw_within_offer_trx_durations</span><span class="p">,</span> 
            <span class="n">raw_first_trx_from_last_durations</span><span class="p">,</span> 
            <span class="n">raw_without_offer_trx_amounts</span><span class="p">,</span> 
            <span class="n">raw_without_offer_trx_durations</span><span class="p">)</span>

<span class="c1"># Process transactions
</span><span class="n">offers_trx_details</span><span class="p">,</span> <span class="n">normal_trx_details</span><span class="p">,</span> <span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">,</span> <span class="n">c</span><span class="p">,</span> <span class="n">d</span><span class="p">,</span> <span class="n">e</span> <span class="o">=</span> <span class="n">process_transactions</span><span class="p">(</span><span class="n">transcript</span><span class="p">,</span> <span class="n">profile</span><span class="p">,</span> <span class="n">force_calc</span><span class="o">=</span><span class="bp">False</span><span class="p">)</span>
<span class="c1"># For readability
</span><span class="n">raw_within_offer_trx_amounts</span> <span class="o">=</span> <span class="n">a</span>
<span class="n">raw_within_offer_trx_durations</span> <span class="o">=</span> <span class="n">b</span>
<span class="n">raw_first_trx_from_last_durations</span> <span class="o">=</span> <span class="n">c</span>
<span class="n">raw_without_offer_trx_amounts</span> <span class="o">=</span> <span class="n">d</span>
<span class="n">raw_without_offer_trx_durations</span> <span class="o">=</span> <span class="n">e</span>
</code></pre></div></div>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>  0%|                                                                                        | 0/14825 [00:00&lt;?, ?it/s]

Could not load processed files. Starting processing:


100%|████████████████████████████████████████████████████████████████████████████| 14825/14825 [17:35&lt;00:00, 14.05it/s]

Saving processed transactions
</code></pre></div></div>

<p>The columns description for each dataFrame is as follows:</p>
<ol>
  <li>offers_trx_details:
    <ul>
      <li><strong>person_id</strong>: Person id</li>
      <li><strong>offer_id</strong>: Offer id</li>
      <li><strong>viewed_time</strong>: the time difference between viewing and offer and receiving it. If not viewed it would be nan</li>
      <li><strong>completed_time</strong>: the time difference between completing an offer and viewing it, in case it was viewed. If not, then from receiving it. If not completed it would be nan</li>
      <li><strong>first_trx_time_from_last_trx</strong>: the time from last transaction before the offer was viewed to the first transaction after the offer is viewed</li>
      <li><strong>trx_count</strong>: # of transactions between view/reception and completion</li>
      <li><strong>avg_trx_amount</strong>: avergae transaction amount for the aforementioned transactions</li>
      <li><strong>avg_time_btwn_trx</strong>: average time between transactions for the aforementioned transactions</li>
    </ul>
  </li>
  <li>normal_trx_details:
    <ul>
      <li><strong>person_id</strong>: Person id</li>
      <li><strong>trx_count</strong>: # of transactions that are not between view/reception and completion</li>
      <li><strong>avg_trx_amount</strong>: avergae transaction amount for the aforementioned transactions</li>
      <li><strong>avg_time_btwn_consec_trx</strong>: average time between only consecutive transactions for the aforementioned transactions</li>
    </ul>
  </li>
</ol>

<p>A sample for each is shown below:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">offers_trx_details</span><span class="p">.</span><span class="n">head</span><span class="p">()</span>
</code></pre></div></div>

<div>
<style scoped="">
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>person_id</th>
      <th>offer_id</th>
      <th>viewed_time</th>
      <th>completed_time</th>
      <th>first_trx_time_from_last_trx</th>
      <th>trx_count</th>
      <th>avg_trx_amount</th>
      <th>avg_time_btwn_trx</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>0610b486422d4921ae7d2bf64640c50b</td>
      <td>9b98b8c7a33c4b65b9aebfe6a799e6d9</td>
      <td>NaN</td>
      <td>120.0</td>
      <td>NaN</td>
      <td>1.0</td>
      <td>23.22</td>
      <td>NaN</td>
    </tr>
    <tr>
      <th>1</th>
      <td>0610b486422d4921ae7d2bf64640c50b</td>
      <td>3f207df678b143eea3cee63160fa8bed</td>
      <td>NaN</td>
      <td>NaN</td>
      <td>NaN</td>
      <td>NaN</td>
      <td>NaN</td>
      <td>NaN</td>
    </tr>
    <tr>
      <th>2</th>
      <td>78afa995795e4d85b5d9ceeca43f5fef</td>
      <td>9b98b8c7a33c4b65b9aebfe6a799e6d9</td>
      <td>6.0</td>
      <td>126.0</td>
      <td>NaN</td>
      <td>1.0</td>
      <td>19.89</td>
      <td>NaN</td>
    </tr>
    <tr>
      <th>3</th>
      <td>78afa995795e4d85b5d9ceeca43f5fef</td>
      <td>5a8bc65990b245e5a138643cd4eb9837</td>
      <td>48.0</td>
      <td>NaN</td>
      <td>78.0</td>
      <td>NaN</td>
      <td>NaN</td>
      <td>NaN</td>
    </tr>
    <tr>
      <th>4</th>
      <td>78afa995795e4d85b5d9ceeca43f5fef</td>
      <td>ae264e3637204a6fb9bb56bc8210ddfd</td>
      <td>0.0</td>
      <td>102.0</td>
      <td>132.0</td>
      <td>1.0</td>
      <td>21.72</td>
      <td>NaN</td>
    </tr>
  </tbody>
</table>
</div>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">normal_trx_details</span><span class="p">.</span><span class="n">head</span><span class="p">()</span>
</code></pre></div></div>

<div>
<style scoped="">
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>person_id</th>
      <th>trx_count</th>
      <th>avg_trx_amount</th>
      <th>avg_time_btwn_consec_trx</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>0610b486422d4921ae7d2bf64640c50b</td>
      <td>3</td>
      <td>25.67</td>
      <td>255.0</td>
    </tr>
    <tr>
      <th>1</th>
      <td>78afa995795e4d85b5d9ceeca43f5fef</td>
      <td>4</td>
      <td>24.50</td>
      <td>138.0</td>
    </tr>
    <tr>
      <th>2</th>
      <td>e2127556f4f64592b11af22de27a7932</td>
      <td>2</td>
      <td>19.66</td>
      <td>6.0</td>
    </tr>
    <tr>
      <th>3</th>
      <td>389bc3fa690240e798340f5a15918d5c</td>
      <td>0</td>
      <td>NaN</td>
      <td>NaN</td>
    </tr>
    <tr>
      <th>4</th>
      <td>2eeac8d8feae4a8cad5a6af0499a211d</td>
      <td>2</td>
      <td>1.60</td>
      <td>NaN</td>
    </tr>
  </tbody>
</table>
</div>

<h3 id="q1--how-did-starbucks-customers-engage-with-the-different-offers">Q1- How did Starbucks customers engage with the different offers?</h3>

<p>For the purpose of this analysis, we will examine how the offers were sent, viewed, completed, or expired. For informational offers, there will be only two statuses sent and viewed.</p>

<p>We will start by creating an aggregated dataframe from ‘offers_trx_details’. For each offer we will calculate the number of receipients, views, completion, or lack thereof</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">create_aggregated_offers_trx_details</span><span class="p">(</span><span class="n">offers_trx_details</span><span class="p">):</span>
    <span class="s">'''
    Create offer level aggregation for some transaction details metrics related to:
    - Vieweing counts and percentages
    - Completion counts and percentages
    - Transaction amounts
    - Duration between transactions
    
    If the data has already been preprocssed it will be loaded. 
    Otherwise it will be processed again. If force_calc is set to True it will process anyway

        Parameters:
            offers_trx_details (pd.DataFrame): Transactions within offers details dataframe 
        Returns:
            aggregated_offers_trx_details (pd.DataFrame): Per offer aggregated amounts, durations, interaction counts, and percentages
    '''</span>
    <span class="c1"># Adding two columns to flag if the offer was viewed and if it was completed
</span>    <span class="n">offers_trx_details</span><span class="p">[</span><span class="s">'is_viewed'</span><span class="p">]</span> <span class="o">=</span> <span class="o">~</span><span class="n">offers_trx_details</span><span class="p">.</span><span class="n">viewed_time</span><span class="p">.</span><span class="n">isna</span><span class="p">()</span><span class="o">*</span><span class="mi">1</span>
    <span class="n">offers_trx_details</span><span class="p">[</span><span class="s">'is_completed'</span><span class="p">]</span> <span class="o">=</span> <span class="o">~</span><span class="n">offers_trx_details</span><span class="p">.</span><span class="n">completed_time</span><span class="p">.</span><span class="n">isna</span><span class="p">()</span><span class="o">*</span><span class="mi">1</span>
    <span class="n">offers_trx_details</span><span class="p">[</span><span class="s">'is_viewed_and_completed'</span><span class="p">]</span> <span class="o">=</span> <span class="n">offers_trx_details</span><span class="p">[</span><span class="s">'is_viewed'</span><span class="p">]</span> <span class="o">*</span> <span class="n">offers_trx_details</span><span class="p">[</span><span class="s">'is_completed'</span><span class="p">]</span>
    
    <span class="c1"># Merging with portfolio dataset
</span>    <span class="n">offers_trx_details</span> <span class="o">=</span> <span class="n">offers_trx_details</span><span class="p">.</span><span class="n">merge</span><span class="p">(</span><span class="n">portfolio</span><span class="p">,</span> <span class="n">left_on</span><span class="o">=</span><span class="s">'offer_id'</span><span class="p">,</span> <span class="n">right_on</span><span class="o">=</span><span class="s">'id'</span><span class="p">).</span><span class="n">drop</span><span class="p">(</span><span class="s">'id'</span><span class="p">,</span> <span class="n">axis</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
    
    <span class="c1"># Pivot the dataframe and create aggregations as specified
</span>    <span class="n">agg_offers_trx_details</span> <span class="o">=</span> <span class="n">offers_trx_details</span><span class="p">.</span><span class="n">pivot_table</span><span class="p">(</span><span class="n">index</span><span class="o">=</span><span class="s">'code_name'</span><span class="p">,</span> <span class="n">aggfunc</span><span class="o">=</span><span class="p">{</span><span class="s">'code_name'</span><span class="p">:</span><span class="s">'count'</span><span class="p">,</span>
                                                                                    <span class="s">'viewed_time'</span><span class="p">:</span><span class="s">'mean'</span><span class="p">,</span>
                                                                                    <span class="s">'completed_time'</span><span class="p">:</span><span class="s">'mean'</span><span class="p">,</span>
                                                                                    <span class="s">'first_trx_time_from_last_trx'</span><span class="p">:</span><span class="s">'mean'</span><span class="p">,</span>
                                                                                    <span class="s">'trx_count'</span><span class="p">:</span><span class="s">'mean'</span><span class="p">,</span>
                                                                                    <span class="s">'is_viewed'</span><span class="p">:</span><span class="s">'sum'</span><span class="p">,</span>
                                                                                    <span class="s">'is_completed'</span><span class="p">:</span><span class="s">'sum'</span><span class="p">,</span>
                                                                                    <span class="s">'is_viewed_and_completed'</span><span class="p">:</span><span class="s">'sum'</span><span class="p">,</span>
                                                                                    <span class="s">'web_ch'</span><span class="p">:</span><span class="s">'sum'</span><span class="p">,</span>
                                                                                    <span class="s">'email_ch'</span><span class="p">:</span><span class="s">'sum'</span><span class="p">,</span>
                                                                                    <span class="s">'mobile_ch'</span><span class="p">:</span><span class="s">'sum'</span><span class="p">,</span>
                                                                                    <span class="s">'social_ch'</span><span class="p">:</span><span class="s">'sum'</span><span class="p">,</span>
                                                                                    <span class="s">'bogo'</span><span class="p">:</span><span class="s">'sum'</span><span class="p">,</span>
                                                                                    <span class="s">'discount'</span><span class="p">:</span><span class="s">'sum'</span><span class="p">,</span>
                                                                                    <span class="s">'informational'</span><span class="p">:</span><span class="s">'sum'</span><span class="p">})</span>
    
    <span class="c1"># Calculate view percentage
</span>    <span class="n">agg_offers_trx_details</span><span class="p">[</span><span class="s">'view_perc'</span><span class="p">]</span> <span class="o">=</span> <span class="n">agg_offers_trx_details</span><span class="p">.</span><span class="n">is_viewed</span> <span class="o">/</span> <span class="n">agg_offers_trx_details</span><span class="p">.</span><span class="n">code_name</span>
    <span class="n">agg_offers_trx_details</span><span class="p">[</span><span class="s">'view_complete_perc'</span><span class="p">]</span> <span class="o">=</span> <span class="n">agg_offers_trx_details</span><span class="p">.</span><span class="n">is_viewed_and_completed</span> <span class="o">/</span> <span class="n">agg_offers_trx_details</span><span class="p">.</span><span class="n">code_name</span>

    <span class="c1"># Since we cannot take the average of averages, I will have to weigh each average with the trx count before I can
</span>    <span class="c1"># calculate the overall average per offer
</span>    <span class="n">temp_averages_df</span> <span class="o">=</span> <span class="n">offers_trx_details</span><span class="p">.</span><span class="n">loc</span><span class="p">[:,</span> <span class="p">[</span><span class="s">'code_name'</span><span class="p">,</span> <span class="s">'trx_count'</span><span class="p">,</span> <span class="s">'avg_trx_amount'</span><span class="p">,</span> <span class="s">'avg_time_btwn_trx'</span><span class="p">]]</span>
    <span class="c1"># With this trick I just need to calculate how many durations are counted to originally get 'avg_time_btwn_trx'. 
</span>    <span class="c1"># It will always be (trx_count-1). Hence we are deducting the logicl condition to ensure that we only deduct when 
</span>    <span class="c1"># the count of transactions is greater that 0
</span>    <span class="n">temp_averages_df</span><span class="p">[</span><span class="s">'durations_count'</span><span class="p">]</span> <span class="o">=</span> <span class="n">temp_averages_df</span><span class="p">.</span><span class="n">trx_count</span><span class="o">-</span><span class="p">(</span><span class="n">temp_averages_df</span><span class="p">.</span><span class="n">trx_count</span> <span class="o">&gt;</span> <span class="mi">0</span><span class="p">)</span>
    <span class="n">temp_averages_df</span><span class="p">[</span><span class="s">'total_trx_durations'</span><span class="p">]</span> <span class="o">=</span> <span class="n">temp_averages_df</span><span class="p">.</span><span class="n">durations_count</span> <span class="o">*</span> <span class="n">temp_averages_df</span><span class="p">.</span><span class="n">avg_time_btwn_trx</span>
    <span class="n">temp_averages_df</span><span class="p">[</span><span class="s">'total_trx_amounts'</span><span class="p">]</span> <span class="o">=</span> <span class="n">temp_averages_df</span><span class="p">.</span><span class="n">trx_count</span> <span class="o">*</span> <span class="n">temp_averages_df</span><span class="p">.</span><span class="n">avg_trx_amount</span>
    <span class="n">averages_df</span> <span class="o">=</span> <span class="n">pd</span><span class="p">.</span><span class="n">DataFrame</span><span class="p">(</span><span class="n">temp_averages_df</span><span class="p">.</span><span class="n">groupby</span><span class="p">(</span><span class="s">'code_name'</span><span class="p">).</span><span class="n">total_trx_durations</span><span class="p">.</span><span class="nb">sum</span><span class="p">()</span><span class="o">/</span>
                               <span class="n">temp_averages_df</span><span class="p">.</span><span class="n">groupby</span><span class="p">(</span><span class="s">'code_name'</span><span class="p">).</span><span class="n">durations_count</span><span class="p">.</span><span class="nb">sum</span><span class="p">(),</span> <span class="n">columns</span><span class="o">=</span><span class="p">[</span><span class="s">'avg_trx_time'</span><span class="p">])</span>
    <span class="n">averages_df</span><span class="p">[</span><span class="s">'avg_trx_amount'</span><span class="p">]</span> <span class="o">=</span> <span class="n">temp_averages_df</span><span class="p">.</span><span class="n">groupby</span><span class="p">(</span><span class="s">'code_name'</span><span class="p">).</span><span class="n">total_trx_amounts</span><span class="p">.</span><span class="nb">sum</span><span class="p">()</span><span class="o">/</span><span class="n">temp_averages_df</span><span class="p">.</span><span class="n">groupby</span><span class="p">(</span><span class="s">'code_name'</span><span class="p">).</span><span class="n">trx_count</span><span class="p">.</span><span class="nb">sum</span><span class="p">()</span>
    
    <span class="k">return</span> <span class="n">agg_offers_trx_details</span><span class="p">.</span><span class="n">merge</span><span class="p">(</span><span class="n">averages_df</span><span class="p">,</span> <span class="n">left_index</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span> <span class="n">right_on</span><span class="o">=</span><span class="s">'code_name'</span><span class="p">)</span>

<span class="c1"># Create aggregated_offers_trx_details
</span><span class="n">aggregated_offers_trx_details</span> <span class="o">=</span> <span class="n">create_aggregated_offers_trx_details</span><span class="p">(</span><span class="n">offers_trx_details</span><span class="p">)</span>
</code></pre></div></div>

<p>Now we create a bunch of charts to look at the different metrics mentioned above:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># Show barplot for number of times each offer is sent
</span><span class="n">plt</span><span class="p">.</span><span class="n">figure</span><span class="p">(</span><span class="n">figsize</span><span class="o">=</span><span class="p">(</span><span class="mi">12</span><span class="p">,</span><span class="mi">6</span><span class="p">))</span>
<span class="n">ax</span> <span class="o">=</span> <span class="n">sns</span><span class="p">.</span><span class="n">barplot</span><span class="p">(</span><span class="n">y</span><span class="o">=</span><span class="n">aggregated_offers_trx_details</span><span class="p">.</span><span class="n">index</span><span class="p">.</span><span class="n">values</span><span class="p">,</span> <span class="n">x</span><span class="o">=</span><span class="n">aggregated_offers_trx_details</span><span class="p">.</span><span class="n">code_name</span><span class="p">)</span>
<span class="n">ax</span><span class="p">.</span><span class="nb">set</span><span class="p">(</span><span class="n">xlabel</span><span class="o">=</span><span class="s">'Count'</span><span class="p">,</span> <span class="n">ylabel</span><span class="o">=</span><span class="s">'Offer'</span><span class="p">,</span> <span class="n">title</span><span class="o">=</span><span class="s">'Number of times sent'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">show</span><span class="p">()</span>
</code></pre></div></div>

<p><img src="/images/output_67_0.png" alt="_config.yml" /></p>

<p>Clearly the offers are sent almost equal number of times. That makes our life easier</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># Display barplot for viewing % for each offer
</span><span class="n">print_hor_perc_barplot</span><span class="p">(</span><span class="n">x</span><span class="o">=</span><span class="n">aggregated_offers_trx_details</span><span class="p">.</span><span class="n">view_perc</span><span class="p">,</span>
                       <span class="n">y</span><span class="o">=</span><span class="n">aggregated_offers_trx_details</span><span class="p">.</span><span class="n">index</span><span class="p">.</span><span class="n">values</span><span class="p">,</span>
                       <span class="n">title</span><span class="o">=</span><span class="s">'Viewed %'</span><span class="p">,</span> <span class="n">xlabel</span><span class="o">=</span><span class="s">'Viewed %'</span><span class="p">,</span> <span class="n">ylabel</span><span class="o">=</span><span class="s">'Offer'</span>
                      <span class="p">)</span>
</code></pre></div></div>

<p><img src="/images/output_69_0.png" alt="_config.yml" /></p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># Display barplot for the percentage of those who viewed and did not complete the offer
</span><span class="n">print_hor_perc_barplot</span><span class="p">(</span><span class="n">x</span><span class="o">=</span><span class="p">((</span><span class="n">aggregated_offers_trx_details</span><span class="p">.</span><span class="n">is_viewed</span> <span class="o">-</span> <span class="n">aggregated_offers_trx_details</span><span class="p">.</span><span class="n">is_viewed_and_completed</span><span class="p">)</span><span class="o">/</span><span class="n">aggregated_offers_trx_details</span><span class="p">.</span><span class="n">code_name</span><span class="p">)[:</span><span class="mi">8</span><span class="p">],</span>
                       <span class="n">y</span><span class="o">=</span><span class="n">aggregated_offers_trx_details</span><span class="p">.</span><span class="n">index</span><span class="p">.</span><span class="n">values</span><span class="p">[:</span><span class="mi">8</span><span class="p">],</span>
                       <span class="n">title</span><span class="o">=</span><span class="s">'Viewed &amp; Ignored %'</span><span class="p">,</span> <span class="n">xlabel</span><span class="o">=</span><span class="s">'Viewed &amp; Ignored %'</span><span class="p">,</span> <span class="n">ylabel</span><span class="o">=</span><span class="s">'Offer'</span>
                      <span class="p">)</span>
</code></pre></div></div>

<p><img src="/images/output_70_0.png" alt="_config.yml" /></p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># Display barplot for the percentage of those who viewed and completed the offer
</span><span class="n">print_hor_perc_barplot</span><span class="p">(</span><span class="n">x</span><span class="o">=</span><span class="n">aggregated_offers_trx_details</span><span class="p">.</span><span class="n">view_complete_perc</span><span class="p">[:</span><span class="mi">8</span><span class="p">],</span>
                       <span class="n">y</span><span class="o">=</span><span class="n">aggregated_offers_trx_details</span><span class="p">.</span><span class="n">index</span><span class="p">.</span><span class="n">values</span><span class="p">[:</span><span class="mi">8</span><span class="p">],</span>
                       <span class="n">title</span><span class="o">=</span><span class="s">'Viewed &amp; Completed %'</span><span class="p">,</span> <span class="n">xlabel</span><span class="o">=</span><span class="s">'Viewed &amp; Completed %'</span><span class="p">,</span> <span class="n">ylabel</span><span class="o">=</span><span class="s">'Offer'</span>
                      <span class="p">)</span>
</code></pre></div></div>

<p><img src="/images/output_71_0.png" alt="_config.yml" /></p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># Display barplot for the percentage of those who completed the offer unntentionally (without viewing it )
</span><span class="n">print_hor_perc_barplot</span><span class="p">(</span><span class="n">x</span><span class="o">=</span><span class="p">((</span><span class="n">aggregated_offers_trx_details</span><span class="p">.</span><span class="n">is_completed</span><span class="o">-</span><span class="n">aggregated_offers_trx_details</span><span class="p">.</span><span class="n">is_viewed_and_completed</span><span class="p">)</span><span class="o">/</span><span class="n">aggregated_offers_trx_details</span><span class="p">.</span><span class="n">code_name</span><span class="p">)[:</span><span class="mi">8</span><span class="p">],</span>
                       <span class="n">y</span><span class="o">=</span><span class="n">aggregated_offers_trx_details</span><span class="p">.</span><span class="n">index</span><span class="p">.</span><span class="n">values</span><span class="p">[:</span><span class="mi">8</span><span class="p">],</span>
                       <span class="n">title</span><span class="o">=</span><span class="s">'Completed without being viewed %'</span><span class="p">,</span>
                       <span class="n">xlabel</span><span class="o">=</span><span class="s">'Completed without being viewed %'</span><span class="p">,</span>
                       <span class="n">ylabel</span><span class="o">=</span><span class="s">'Offer'</span>
                      <span class="p">)</span>
</code></pre></div></div>

<p><img src="/images/output_72_0.png" alt="_config.yml" /></p>

<p>Fromt the charts above we can observe the following:</p>
<ul>
  <li>6 out of 10 offers were viewed by around 80% or more of customers which seems very good</li>
  <li>Around 30% of those who completed bogo_3, discount_1, and discount_4 did it without even viewing the offer. This means that either way customers would have continued with their purchaing habits without the business spending money on those offers. However, this cannot be concluded unless we know the motivation of this offer. It might not be purely financial, there might be loyalty aspects, or some utility function that is used to measure success of an offer</li>
  <li>Surprisingly, those three offers (bogo_3, discount_1, and discount_4) that were viewed the least (less than 50%), are the ones that were completed without being viewed the most. This is unclear and could be due to the way the data was synthesized or some other factors that require clarification from business, because the difficulty of those offers is above average</li>
  <li>The offer that seems to have done the best in terms of engagement is “discount_3”. Customers seem to have engaged with it in terms of views, completion, and the relatively lower number of those who viewed it and ignored it</li>
</ul>

<p>In the section we look at the journey of how our customers interacted with what we deem to be the best performing offer (discount_3), and one of the worst performing offers (discount_1)</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># Display sankey diagrams for discount_3 and discount_1
</span><span class="n">plot_sankey</span><span class="p">(</span><span class="s">'discount_3'</span><span class="p">,</span> <span class="n">aggregated_offers_trx_details</span><span class="p">)</span>
<span class="n">plot_sankey</span><span class="p">(</span><span class="s">'discount_1'</span><span class="p">,</span> <span class="n">aggregated_offers_trx_details</span><span class="p">)</span>
</code></pre></div></div>

<p><img src="/images/output_75_0.svg" alt="_config.yml" /></p>

<p><img src="/images/output_75_1.svg" alt="_config.yml" /></p>

<p>This kind of diagrams gives a very good view of how each offer is performing. Of course we can add other measures, e.g. financial</p>

<h3 id="q2--how-did-the-offers-affect-or-change-customer-behavior">Q2- How did the offers affect or change customer behavior?</h3>

<p>In the first question we looked at how the offers performed in terms of customer engagement. Now, we want to measure if those offers changed the customer behavior. Of course the condition for transactions within an offer is that the offer has been viewed, and completed in the case of bogo and discount.</p>

<p>We will measure this as follows:</p>
<ol>
  <li>For informational offers, we will check if the duration that users take to make the first purchase after the informational offer is reduced in comparison to the usual duration that customers take between consecutive purchases that are not under any offer</li>
  <li>For bogo and discount offers, we will check if the duration between purchase instances for transactions within an offer is different from the duration between normal consecutive transactions that are not withi an offer period</li>
  <li>Finally, we will check if the there is a statistically significant change in transaction amounts during an offer (bogo or discount) from outside an offer</li>
</ol>

<p>Those tests will be conducted using z-test, and then we measure the statistical significance of the result. We choose z-test for the following reasons:</p>
<ul>
  <li>We have a very large sample size</li>
  <li>The data points are independent from each other</li>
  <li>Even though ideally the samples should have a normal distribution, given the large sample size this should be accepted</li>
</ul>

<h5 id="1-starting-with-our-test-regarding-the-effect-of-informational-offers-we-set-the-hypotheses-first">1. Starting with our test regarding the effect of informational offers. We set the hypotheses first:</h5>
<p><strong>H0:</strong> The informational offer <em>does NOT</em> have an effect on the duration customers take until their next purchase</p>

<p><strong>H1:</strong> The informational offer <em>DOES</em> have an effect on the duration customers take until their net purchase</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">raw_first_trx_from_last_durations</span> <span class="o">=</span> <span class="n">raw_first_trx_from_last_durations</span><span class="p">.</span><span class="n">dropna</span><span class="p">()</span>
<span class="n">compare_two_samples</span><span class="p">(</span><span class="n">raw_without_offer_trx_durations</span><span class="p">.</span><span class="n">trx_duration</span><span class="p">,</span> 
                    <span class="n">raw_first_trx_from_last_durations</span><span class="p">.</span><span class="n">trx_duration</span><span class="p">,</span>
                    <span class="n">label1</span><span class="o">=</span><span class="s">'Duration without offer'</span><span class="p">,</span>
                    <span class="n">label2</span><span class="o">=</span><span class="s">'Duration after info offer'</span><span class="p">,</span>
                    <span class="n">title</span><span class="o">=</span><span class="s">'Duration between transactions distribution comparison'</span>
                   <span class="p">)</span>
</code></pre></div></div>

<p><img src="/images/output_80_0.png" alt="_config.yml" /></p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Mean for Duration without offer: 56.60
Mean for Duration after info offer: 112.21

Z-test result:
z-score: -105.95
p-value: 0.0
The null hypothesis H0 is REJECTED. p-value is statistically significant
</code></pre></div></div>

<p>Only by looking at the chart above and the mean values we can see how different the two samples are. Of course, the z-test confirms that informational offer has an effect. However, it is suprisingly counter-intuitive. Because this suggests that customers take longer time to make a purchase after receiving an informational offer in comparison to the time they usually take between transactions.</p>

<p>Nonetheless, this could be due to the time informational offers are beng set. E.g. late at night, or some time in the weekend. This requires further investigation with business, and complimentary data to shed more light.</p>

<h5 id="2-testing-the-effect-of-bogo-and-discount-offers-on-transaction-durations-we-set-the-hypotheses">2. Testing the effect of BOGO and discount offers on transaction durations. We set the hypotheses:</h5>
<p><strong>H0:</strong> The BOGO and discout offers <em>DO NOT</em> have an effect on the duration between customer’s consecutive purchase instances during an offer</p>

<p><strong>H1:</strong> The BOGO and discout offers <em>DO</em> have an effect on the duration between customer’s consecutive purchase instances during an offer</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">compare_two_samples</span><span class="p">(</span><span class="n">raw_without_offer_trx_durations</span><span class="p">.</span><span class="n">trx_duration</span><span class="p">,</span> 
                    <span class="n">raw_within_offer_trx_durations</span><span class="p">.</span><span class="n">trx_duration</span><span class="p">,</span>
                    <span class="n">label1</span><span class="o">=</span><span class="s">'Duration without offer'</span><span class="p">,</span>
                    <span class="n">label2</span><span class="o">=</span><span class="s">'Duration within offer'</span><span class="p">,</span>
                    <span class="n">title</span><span class="o">=</span><span class="s">'Duration between transactions distribution comparison'</span>
                   <span class="p">)</span>
</code></pre></div></div>

<p><img src="/images/output_83_0.png" alt="_config.yml" /></p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Mean for Duration without offer: 56.60
Mean for Duration within offer: 34.99

Z-test result:
z-score: 35.71
p-value: 2.7584775958939873e-279
The null hypothesis H0 is REJECTED. p-value is statistically significant
</code></pre></div></div>

<p>Clearly, from the mean values we see above and the ztest, during an offer customers do purchase more frequently. I.e. the duration between purchase transactions is reduced!</p>

<p>Of course if needed we can dig deeper to see which specific offer did best</p>

<h5 id="3-testing-the-effect-of-bogo-and-discount-offers-on-transaction-amounts-we-set-the-hypotheses">3. Testing the effect of BOGO and discount offers on transaction amounts. We set the hypotheses:</h5>
<p><strong>H0:</strong> The BOGO and discout offers <em>DO NOT</em> have an effect on the purchase transaction amount during an offer</p>

<p><strong>H1:</strong> The BOGO and discout offers <em>DO</em> have an effect on the purchase transaction amount during an offer</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">compare_two_samples</span><span class="p">(</span><span class="n">raw_without_offer_trx_amounts</span><span class="p">.</span><span class="n">trx_amount</span><span class="p">,</span> 
                    <span class="n">raw_within_offer_trx_amounts</span><span class="p">.</span><span class="n">trx_amount</span><span class="p">,</span>
                    <span class="n">label1</span><span class="o">=</span><span class="s">'Transaction amount without offer'</span><span class="p">,</span>
                    <span class="n">label2</span><span class="o">=</span><span class="s">'Transaction amount within offer'</span><span class="p">,</span>
                    <span class="n">title</span><span class="o">=</span><span class="s">'Amount distribution comparison'</span>
                   <span class="p">)</span>
</code></pre></div></div>

<p><img src="/images/output_86_0.png" alt="_config.yml" /></p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Mean for Transaction amount without offer: 12.18
Mean for Transaction amount within offer: 14.09

Z-test result:
z-score: -34.11
p-value: 5.999710750577186e-255
The null hypothesis H0 is REJECTED. p-value is statistically significant
</code></pre></div></div>

<p>Again, this clearly shows that during an offer customers spend more per transaction, and the amount difference is statistically significant</p>

<h3 id="q3--can-we-predict-if-a-customer-will-interact-with-an-offer-and-what-are-the-determining-factors">Q3- Can we predict if a customer will interact with an offer? and what are the determining factors?</h3>

<p>For the purpose of answering this question, we will create a dataset containing information aboiut our customers and offers. Then we will fit a model and evaluate its performance. Then, we will look at the most important features that derive the model decision</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">generate_dataset</span><span class="p">(</span><span class="n">profile</span><span class="p">,</span> <span class="n">portfolio</span><span class="p">,</span> <span class="n">offers_trx_details</span><span class="p">,</span> <span class="n">normal_trx_details</span><span class="p">):</span>
    <span class="s">'''
    Generate a dataset for the predictive model. 
    The dataset will be created from combining data from:
    - profile
    - portfolio
    - normal_trx_details
    - offers_trx_details
    
    It will join the data, one-hot-encode, and remove any unnecessary data for the modelling

        Parameters:
            profile (pd.DataFrame): Profile dataset
            portfolio (pd.DataFrame): Portfolio dataset 
            normal_trx_details (pd.DataFrame): Transactions outside an offer details dataframe 
            offers_trx_details (pd.DataFrame): Transactions within offers details dataframe 
        Returns:
            prediction_dataset (pd.DataFrame): Dataset to be used for creating the model
    '''</span>
    
    <span class="c1"># One-hot-encode gender and merge with profile
</span>    <span class="n">prediction_dataset</span> <span class="o">=</span> <span class="n">profile</span><span class="p">.</span><span class="n">merge</span><span class="p">(</span><span class="n">pd</span><span class="p">.</span><span class="n">get_dummies</span><span class="p">(</span><span class="n">profile</span><span class="p">.</span><span class="n">gender</span><span class="p">),</span> 
                                       <span class="n">left_index</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span> <span class="n">right_index</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
    <span class="n">prediction_dataset</span> <span class="o">=</span> <span class="n">prediction_dataset</span><span class="p">.</span><span class="n">drop</span><span class="p">([</span><span class="s">'gender'</span><span class="p">],</span> <span class="n">axis</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
    <span class="n">prediction_dataset</span> <span class="o">=</span> <span class="n">prediction_dataset</span><span class="p">.</span><span class="n">set_index</span><span class="p">(</span><span class="s">'id'</span><span class="p">)</span>
    
    <span class="c1"># Merge with normal_trx_details and remove unnecessary columns
</span>    <span class="n">normal_trx_details</span> <span class="o">=</span> <span class="n">normal_trx_details</span><span class="p">.</span><span class="n">set_index</span><span class="p">(</span><span class="s">'person_id'</span><span class="p">)</span>
    <span class="n">normal_trx_details</span> <span class="o">=</span> <span class="n">normal_trx_details</span><span class="p">.</span><span class="n">drop</span><span class="p">([</span><span class="s">'trx_count'</span><span class="p">,</span> <span class="s">'avg_time_btwn_consec_trx'</span><span class="p">],</span> <span class="n">axis</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
    <span class="n">prediction_dataset</span> <span class="o">=</span> <span class="n">prediction_dataset</span><span class="p">.</span><span class="n">merge</span><span class="p">(</span>
        <span class="n">normal_trx_details</span><span class="p">,</span> <span class="n">left_index</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span> <span class="n">right_index</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
    <span class="n">prediction_dataset</span><span class="p">.</span><span class="n">avg_trx_amount</span> <span class="o">=</span> <span class="n">prediction_dataset</span><span class="p">.</span><span class="n">avg_trx_amount</span><span class="p">.</span><span class="n">fillna</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
    
    <span class="c1"># Merge with offers_trx_details and remove unnecessary columns
</span>    <span class="n">offers_trx_details</span> <span class="o">=</span> <span class="n">offers_trx_details</span><span class="p">[[</span><span class="s">'person_id'</span><span class="p">,</span> <span class="s">'offer_id'</span><span class="p">,</span> <span class="s">'is_viewed_and_completed'</span><span class="p">]]</span>
    <span class="n">prediction_dataset</span> <span class="o">=</span> <span class="n">prediction_dataset</span><span class="p">.</span><span class="n">merge</span><span class="p">(</span><span class="n">offers_trx_details</span><span class="p">,</span> <span class="n">left_index</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span> <span class="n">right_on</span><span class="o">=</span><span class="s">'person_id'</span><span class="p">)</span>
    <span class="n">prediction_dataset</span> <span class="o">=</span> <span class="n">prediction_dataset</span><span class="p">.</span><span class="n">drop</span><span class="p">([</span><span class="s">'person_id'</span><span class="p">],</span> <span class="n">axis</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
    
    <span class="c1"># Merge with portfolio dataset and remove unnecessary columns
</span>    <span class="n">prediction_dataset</span> <span class="o">=</span> <span class="n">prediction_dataset</span><span class="p">.</span><span class="n">merge</span><span class="p">(</span><span class="n">portfolio</span><span class="p">,</span> <span class="n">left_on</span><span class="o">=</span><span class="s">'offer_id'</span><span class="p">,</span> <span class="n">right_on</span><span class="o">=</span><span class="s">'id'</span><span class="p">)</span>
    <span class="n">prediction_dataset</span> <span class="o">=</span> <span class="n">prediction_dataset</span><span class="p">[</span><span class="n">prediction_dataset</span><span class="p">.</span><span class="n">informational</span> <span class="o">==</span> <span class="mi">0</span><span class="p">]</span>
    <span class="n">prediction_dataset</span> <span class="o">=</span> <span class="n">prediction_dataset</span><span class="p">.</span><span class="n">drop</span><span class="p">([</span><span class="s">'offer_id'</span><span class="p">,</span> <span class="s">'id'</span><span class="p">,</span> <span class="s">'code_name'</span><span class="p">,</span> <span class="s">'informational'</span><span class="p">],</span> <span class="n">axis</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
    <span class="n">prediction_dataset</span> <span class="o">=</span> <span class="n">prediction_dataset</span><span class="p">.</span><span class="n">reset_index</span><span class="p">()</span>
    <span class="n">prediction_dataset</span> <span class="o">=</span> <span class="n">prediction_dataset</span><span class="p">.</span><span class="n">drop</span><span class="p">([</span><span class="s">'index'</span><span class="p">],</span> <span class="n">axis</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">prediction_dataset</span>

<span class="c1"># Create dataset to be used to build the model
</span><span class="n">prediction_dataset</span> <span class="o">=</span> <span class="n">generate_dataset</span><span class="p">(</span><span class="n">profile</span><span class="p">,</span> <span class="n">portfolio</span><span class="p">,</span> <span class="n">offers_trx_details</span><span class="p">,</span> <span class="n">normal_trx_details</span><span class="p">)</span>
</code></pre></div></div>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">build_model</span><span class="p">():</span>
    <span class="s">'''
    Build a random forest classifier model and use GridSearchCV to find the best model prameters

            Returns:
                    clf (GridSearchCV): the model enveloped in the search method
    '''</span>
    <span class="c1"># Number of trees in random forest
</span>    <span class="n">n_estimators</span> <span class="o">=</span> <span class="nb">range</span><span class="p">(</span><span class="mi">200</span><span class="p">,</span> <span class="mi">500</span><span class="p">,</span> <span class="mi">100</span><span class="p">)</span>
    <span class="c1"># Number of features to consider at every split
</span>    <span class="n">max_features</span> <span class="o">=</span> <span class="p">[</span><span class="s">'auto'</span><span class="p">,</span> <span class="s">'sqrt'</span><span class="p">]</span>
    <span class="c1"># Maximum number of levels in tree
</span>    <span class="n">max_depth</span> <span class="o">=</span> <span class="nb">range</span><span class="p">(</span><span class="mi">8</span><span class="p">,</span> <span class="mi">15</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span>
    <span class="c1"># Minimum number of samples required to split a node
</span>    <span class="n">min_samples_split</span> <span class="o">=</span> <span class="p">[</span><span class="mi">2</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">10</span><span class="p">]</span>
    <span class="c1"># Minimum number of samples required at each leaf node
</span>    <span class="n">min_samples_leaf</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">4</span><span class="p">]</span>
    <span class="n">random_grid</span> <span class="o">=</span> <span class="p">{</span><span class="s">'n_estimators'</span><span class="p">:</span> <span class="n">n_estimators</span><span class="p">,</span>
                   <span class="s">'max_features'</span><span class="p">:</span> <span class="n">max_features</span><span class="p">,</span>
                   <span class="s">'max_depth'</span><span class="p">:</span> <span class="n">max_depth</span><span class="p">,</span>
                   <span class="s">'min_samples_split'</span><span class="p">:</span> <span class="n">min_samples_split</span><span class="p">,</span>
                   <span class="s">'min_samples_leaf'</span><span class="p">:</span> <span class="n">min_samples_leaf</span>
                  <span class="p">}</span>

    <span class="c1"># Define the random forest model and set it in randomized search cv
</span>    <span class="n">rfc</span> <span class="o">=</span> <span class="n">RandomForestClassifier</span><span class="p">()</span>
    <span class="n">clf</span> <span class="o">=</span> <span class="n">GridSearchCV</span><span class="p">(</span><span class="n">estimator</span> <span class="o">=</span> <span class="n">rfc</span><span class="p">,</span> <span class="n">param_grid</span><span class="o">=</span><span class="n">random_grid</span><span class="p">,</span> <span class="n">cv</span><span class="o">=</span><span class="mi">10</span><span class="p">,</span> <span class="n">verbose</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span> <span class="n">n_jobs</span> <span class="o">=</span> <span class="o">-</span><span class="mi">1</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">clf</span>
</code></pre></div></div>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">display_model_metrics</span><span class="p">(</span><span class="n">y_test</span><span class="p">,</span> <span class="n">y_pred</span><span class="p">,</span> <span class="n">model</span><span class="p">):</span>
    <span class="s">'''
    Displays the model metrics (Accuracy, F1 score), and the best performing model parameters

            Parameters:
                    y_test (pandas.Series): ground truth values
                    y_pred (pandas.Series): model predictions
                    model (RandomizedSearchCV): fit search model 
    '''</span>
    <span class="k">print</span><span class="p">(</span><span class="s">'Accuracy: {:0.2f}'</span><span class="p">.</span><span class="nb">format</span><span class="p">(</span><span class="n">accuracy_score</span><span class="p">(</span><span class="n">y_test</span><span class="p">,</span> <span class="n">y_pred</span><span class="p">)))</span>
    <span class="k">print</span><span class="p">(</span><span class="s">'F1 score: {:0.2f}'</span><span class="p">.</span><span class="nb">format</span><span class="p">(</span><span class="n">f1_score</span><span class="p">(</span><span class="n">y_test</span><span class="p">,</span> <span class="n">y_pred</span><span class="p">)))</span>
    <span class="k">print</span><span class="p">(</span><span class="s">'Best performing model parameters:'</span><span class="p">)</span>
    <span class="k">print</span><span class="p">(</span><span class="n">model</span><span class="p">.</span><span class="n">best_params_</span><span class="p">)</span>
</code></pre></div></div>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">fit_model</span><span class="p">(</span><span class="n">X_train</span><span class="p">,</span> <span class="n">y_train</span><span class="p">,</span> <span class="n">model</span><span class="p">):</span>  
    <span class="k">try</span><span class="p">:</span>
        <span class="n">loaded_model</span> <span class="o">=</span> <span class="n">pickle</span><span class="p">.</span><span class="n">load</span><span class="p">(</span><span class="nb">open</span><span class="p">(</span><span class="s">'model/trained_model.pkl'</span><span class="p">,</span> <span class="s">'rb'</span><span class="p">))</span>
        <span class="k">return</span> <span class="n">loaded_model</span>
    <span class="k">except</span><span class="p">:</span>
        <span class="k">print</span><span class="p">(</span><span class="s">'Model not found. Fitting new model'</span><span class="p">)</span>
    
    <span class="n">model</span><span class="p">.</span><span class="n">fit</span><span class="p">(</span><span class="n">X_train</span><span class="p">,</span> <span class="n">y_train</span><span class="p">)</span>
    <span class="n">pickle</span><span class="p">.</span><span class="n">dump</span><span class="p">(</span><span class="n">model</span><span class="p">,</span> <span class="nb">open</span><span class="p">(</span><span class="s">'model/trained_model.pkl'</span><span class="p">,</span> <span class="s">'wb'</span><span class="p">))</span>
    <span class="k">return</span> <span class="n">model</span>
</code></pre></div></div>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># Split the data for training and testing
</span><span class="n">y</span> <span class="o">=</span> <span class="n">prediction_dataset</span><span class="p">.</span><span class="n">is_viewed_and_completed</span>
<span class="n">X</span> <span class="o">=</span> <span class="n">prediction_dataset</span><span class="p">.</span><span class="n">drop</span><span class="p">([</span><span class="s">'is_viewed_and_completed'</span><span class="p">],</span> <span class="n">axis</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
<span class="n">X_train</span><span class="p">,</span> <span class="n">X_test</span><span class="p">,</span> <span class="n">y_train</span><span class="p">,</span> <span class="n">y_test</span> <span class="o">=</span> <span class="n">train_test_split</span><span class="p">(</span><span class="n">X</span><span class="p">,</span> <span class="n">y</span><span class="p">,</span> <span class="n">random_state</span><span class="o">=</span><span class="mi">42</span><span class="p">,</span> <span class="n">test_size</span><span class="o">=</span><span class="mf">0.3</span><span class="p">,</span> <span class="n">shuffle</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span> <span class="n">stratify</span><span class="o">=</span><span class="n">y</span><span class="p">)</span>

<span class="c1"># Build and fit the model
</span><span class="n">model</span> <span class="o">=</span> <span class="n">build_model</span><span class="p">()</span>
<span class="n">model</span> <span class="o">=</span> <span class="n">fit_model</span><span class="p">(</span><span class="n">X_train</span><span class="p">,</span> <span class="n">y_train</span><span class="p">,</span> <span class="n">model</span><span class="p">)</span>

<span class="c1"># Create predictions
</span><span class="n">y_pred</span> <span class="o">=</span> <span class="n">model</span><span class="p">.</span><span class="n">predict</span><span class="p">(</span><span class="n">X_test</span><span class="p">)</span>

<span class="c1"># Test model performance
</span><span class="n">display_model_metrics</span><span class="p">(</span><span class="n">y_test</span><span class="p">,</span> <span class="n">y_pred</span><span class="p">,</span> <span class="n">model</span><span class="p">)</span>
</code></pre></div></div>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Model not found. Fitting new model
Fitting 10 folds for each of 216 candidates, totalling 2160 fits


[Parallel(n_jobs=-1)]: Using backend LokyBackend with 16 concurrent workers.
[Parallel(n_jobs=-1)]: Done   9 tasks      | elapsed:    6.8s
[Parallel(n_jobs=-1)]: Done 130 tasks      | elapsed:  1.0min
[Parallel(n_jobs=-1)]: Done 333 tasks      | elapsed:  2.6min
[Parallel(n_jobs=-1)]: Done 616 tasks      | elapsed:  4.8min
[Parallel(n_jobs=-1)]: Done 981 tasks      | elapsed:  8.1min
[Parallel(n_jobs=-1)]: Done 1426 tasks      | elapsed: 12.3min
[Parallel(n_jobs=-1)]: Done 1953 tasks      | elapsed: 17.9min
[Parallel(n_jobs=-1)]: Done 2160 out of 2160 | elapsed: 20.1min finished


Accuracy: 0.73
F1 score: 0.68
Best performing model parameters:
{'max_depth': 10, 'max_features': 'auto', 'min_samples_leaf': 2, 'min_samples_split': 2, 'n_estimators': 200}
</code></pre></div></div>

<p>Looking at the score, we are checking the f1-score to see if there is bias in the model due to the imbalance in labels. However, we can say that the value for both Accuracy and F1-score is very reasonable</p>

<h4 id="determining-factors">Determining factors</h4>

<p>Now we take a look at the most important features determined by the model that would give an indicator if someone will view and complete an offer or not</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">features_imp</span> <span class="o">=</span> <span class="nb">dict</span><span class="p">(</span><span class="nb">zip</span><span class="p">(</span><span class="n">X_train</span><span class="p">.</span><span class="n">columns</span><span class="p">,</span> <span class="n">model</span><span class="p">.</span><span class="n">best_estimator_</span><span class="p">.</span><span class="n">feature_importances_</span><span class="p">))</span>
<span class="n">top_10_features_imp</span> <span class="o">=</span> <span class="nb">dict</span><span class="p">(</span><span class="nb">sorted</span><span class="p">(</span><span class="n">features_imp</span><span class="p">.</span><span class="n">items</span><span class="p">(),</span> <span class="n">key</span><span class="o">=</span><span class="k">lambda</span> <span class="n">x</span><span class="p">:</span> <span class="n">x</span><span class="p">[</span><span class="mi">1</span><span class="p">],</span> <span class="n">reverse</span><span class="o">=</span><span class="bp">True</span><span class="p">)[:</span><span class="mi">10</span><span class="p">])</span>
<span class="n">top_10_features_imp</span>
</code></pre></div></div>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>{'avg_trx_amount': 0.3716380215282812,
 'year_of_membership': 0.1385218232822374,
 'social_ch': 0.13006587174137996,
 'income': 0.08617988934399316,
 'age': 0.06468248255489872,
 'reward': 0.04732381085392822,
 'difficulty': 0.040605336025519,
 'duration': 0.033450815207409,
 'mobile_ch': 0.025639339256143114,
 'bogo': 0.01870600034089425}
</code></pre></div></div>

<p>We can clearly see that individual attributes are the most important features, followed by offer properties. Those features are:</p>
<ul>
  <li>avg_trx_amount: The average spending amount per transaction of a customer</li>
  <li>year_of_membership: How long the customer has been a member</li>
  <li>social_ch: whether the offer was sent of a social media channel or not</li>
  <li>income: Customer’s income</li>
  <li>age: Customer’s age</li>
  <li>reward: The reward amount of the offer</li>
  <li>difficulty: Offer’s difficulty</li>
  <li>duration: How long the offer will run for</li>
  <li>mobile_ch: Whether the offer was sent over the mobile channel</li>
  <li>If the offer is of type buy-one-get-one</li>
</ul>

<p>Now let’s look at how those features are correlated with the outcome and with each other. However, we will limit it only to 5 features for ease of visualization:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># Display correlation matrix for the top 5 features with outcome
</span><span class="n">fig</span> <span class="o">=</span> <span class="n">plt</span><span class="p">.</span><span class="n">gcf</span><span class="p">()</span>
<span class="n">fig</span><span class="p">.</span><span class="n">set_size_inches</span><span class="p">(</span><span class="mi">12</span><span class="p">,</span> <span class="mi">8</span><span class="p">)</span>
<span class="n">top_features_df</span> <span class="o">=</span> <span class="n">pd</span><span class="p">.</span><span class="n">concat</span><span class="p">([</span><span class="n">X_train</span><span class="p">,</span> <span class="n">X_test</span><span class="p">],</span> <span class="n">axis</span><span class="o">=</span><span class="mi">0</span><span class="p">)[</span><span class="nb">list</span><span class="p">(</span><span class="n">top_10_features_imp</span><span class="p">.</span><span class="n">keys</span><span class="p">())[:</span><span class="mi">5</span><span class="p">]]</span>
<span class="n">top_features_df</span> <span class="o">=</span> <span class="n">top_features_df</span><span class="p">.</span><span class="n">merge</span><span class="p">(</span><span class="n">pd</span><span class="p">.</span><span class="n">concat</span><span class="p">([</span><span class="n">y_train</span><span class="p">,</span> <span class="n">y_test</span><span class="p">],</span> <span class="n">axis</span><span class="o">=</span><span class="mi">0</span><span class="p">),</span> <span class="n">left_index</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span> <span class="n">right_index</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>

<span class="n">sns</span><span class="p">.</span><span class="n">heatmap</span><span class="p">(</span><span class="n">pd</span><span class="p">.</span><span class="n">DataFrame</span><span class="p">.</span><span class="n">corr</span><span class="p">(</span><span class="n">top_features_df</span><span class="p">),</span> <span class="n">cmap</span><span class="o">=</span><span class="s">"YlGnBu"</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">show</span><span class="p">()</span>
</code></pre></div></div>

<p><img src="/images/output_100_0.png" alt="_config.yml" /></p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># Display the scatterplot matrix for the top 5 features with outcome
</span><span class="n">sns</span><span class="p">.</span><span class="n">pairplot</span><span class="p">(</span><span class="n">top_features_df</span><span class="p">,</span> <span class="n">hue</span><span class="o">=</span><span class="s">'is_viewed_and_completed'</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="n">show</span><span class="p">()</span>
</code></pre></div></div>

<p><img src="/images/output_101_0.png" alt="_config.yml" /></p>

<p>Focusing on the diagonal charts, we can observe the following:</p>
<ul>
  <li>Average transaction amount is positively correlated with likelihood of participating</li>
  <li>Years of membership that are between 2 and 3 are more positively correlted with a positive outcome. Less or more years are the other way around. Especially newer members.</li>
  <li>Social channel shows a positive correlation</li>
  <li>The higher the income the more likely someone seems to participate in an offer</li>
</ul>

<h2 id="5-conclusion">5. Conclusion</h2>

<p>In this exercise we analyzed the customers and offers data from Starbucks. We tried to answer the different posed business questions by following CRISP-DM.</p>

<p>We identified how our customers interacted with each of the offer, and the journey of customers throughout this interaction.</p>

<p>Then we shed some light at whether the offers has an impact on customer behavior and spending.</p>

<p>Finally, built a predictive model that can provide us with the likelihood of a customer participating with a certain offer or not. We also utilized this model to understand the most important features at determining whether a customer will interact with an offer.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">prediction_dataset</span><span class="p">.</span><span class="n">head</span><span class="p">()</span>
</code></pre></div></div>

<div>
<style scoped="">
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>age</th>
      <th>income</th>
      <th>year_of_membership</th>
      <th>F</th>
      <th>M</th>
      <th>O</th>
      <th>avg_trx_amount</th>
      <th>is_viewed_and_completed</th>
      <th>reward</th>
      <th>difficulty</th>
      <th>duration</th>
      <th>web_ch</th>
      <th>email_ch</th>
      <th>mobile_ch</th>
      <th>social_ch</th>
      <th>bogo</th>
      <th>discount</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>55.0</td>
      <td>112000.0</td>
      <td>2</td>
      <td>1</td>
      <td>0</td>
      <td>0</td>
      <td>25.67</td>
      <td>0</td>
      <td>5</td>
      <td>5</td>
      <td>7</td>
      <td>1</td>
      <td>1</td>
      <td>1</td>
      <td>0</td>
      <td>1</td>
      <td>0</td>
    </tr>
    <tr>
      <th>1</th>
      <td>75.0</td>
      <td>100000.0</td>
      <td>2</td>
      <td>1</td>
      <td>0</td>
      <td>0</td>
      <td>24.50</td>
      <td>1</td>
      <td>5</td>
      <td>5</td>
      <td>7</td>
      <td>1</td>
      <td>1</td>
      <td>1</td>
      <td>0</td>
      <td>1</td>
      <td>0</td>
    </tr>
    <tr>
      <th>2</th>
      <td>68.0</td>
      <td>70000.0</td>
      <td>1</td>
      <td>0</td>
      <td>1</td>
      <td>0</td>
      <td>19.66</td>
      <td>1</td>
      <td>5</td>
      <td>5</td>
      <td>7</td>
      <td>1</td>
      <td>1</td>
      <td>1</td>
      <td>0</td>
      <td>1</td>
      <td>0</td>
    </tr>
    <tr>
      <th>3</th>
      <td>65.0</td>
      <td>53000.0</td>
      <td>1</td>
      <td>0</td>
      <td>1</td>
      <td>0</td>
      <td>0.00</td>
      <td>0</td>
      <td>5</td>
      <td>5</td>
      <td>7</td>
      <td>1</td>
      <td>1</td>
      <td>1</td>
      <td>0</td>
      <td>1</td>
      <td>0</td>
    </tr>
    <tr>
      <th>4</th>
      <td>65.0</td>
      <td>53000.0</td>
      <td>1</td>
      <td>0</td>
      <td>1</td>
      <td>0</td>
      <td>0.00</td>
      <td>1</td>
      <td>5</td>
      <td>5</td>
      <td>7</td>
      <td>1</td>
      <td>1</td>
      <td>1</td>
      <td>0</td>
      <td>1</td>
      <td>0</td>
    </tr>
  </tbody>
</table>
</div>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
</code></pre></div></div>]]></content><author><name></name></author><summary type="html"><![CDATA[Offers are an important tool for engaging your customers, promoting new offerings, or increasing loyalty. However, targeting a customer with the wrong offer could be useless, or in some cases could bring a negative outcome. Therefore, it is very important to understand the interaction between customers and offers.]]></summary></entry><entry><title type="html">Starbucks Customers and Offers Interaction Analysis</title><link href="https://alkalaji.github.io/starbucks-data-analysis/" rel="alternate" type="text/html" title="Starbucks Customers and Offers Interaction Analysis" /><published>2021-03-19T00:00:00+00:00</published><updated>2021-03-19T00:00:00+00:00</updated><id>https://alkalaji.github.io/starbucks-data-analysis</id><content type="html" xml:base="https://alkalaji.github.io/starbucks-data-analysis/"><![CDATA[<p>Offers are an important tool for engaging your customers, promoting new offerings, or increasing loyalty. However, targeting a customer with the wrong offer could be useless, or in some cases could bring a negative outcome. Therefore, it is very important to understand the interaction between customers and offers.</p>

<p><img src="https://s11284.pcdn.co/wp-content/uploads/2019/01/starbucks-customer-holding-coffee-cup-700x466.jpg.webp" alt="_config.yml" /></p>

<h2 id="introduction">Introduction</h2>

<p>Starbucks is the world’s largest coffehouse chain in the world. With thousands of stores, and millions of customers, it is important to engage with your customers and understand them. Therefore, Starbucks has an application that makes it easier to know customers better, make it easier for them to order, and to send offers.</p>

<p>However, with the huge number of customers, and multitude of offer options, it is a challenge to understand how customer interact with the offers, and how the offers affct customers behavior. Therefore, using some Starbucks provided data that mimics real life offers and customer behavior.</p>

<p>The data contains scio-demographic information about customers, the transactions of customers, and the different types of offers which are:</p>
<ul>
  <li>Informational: An advertisement informing customers about a product</li>
  <li>BOGO: Buy one get one,  where auser needs to spend a certain amount to get a reward equal to that threshold amount</li>
  <li>Discount: a user gains a reward equal to a fraction of the amount spent</li>
</ul>

<p>Through this analysis, we will try to answer the following business questions:</p>
<ol>
  <li><em>How did Starbucks customers engage with the different offers?</em></li>
  <li><em>How did the offers affect or change customer behavior?</em></li>
  <li><em>Can we predict if a customer will interact with an offer? and what are the determining factors?</em></li>
</ol>

<p>We will tackle those questions one by one. So let’s get started!</p>

<h2 id="q1-how-did-starbucks-customers-engage-with-the-different-offers">Q1. How did Starbucks customers engage with the different offers?</h2>
<p>Each offer has a lifecycle, and goes through different stages depending on the offer type, from being received to viewed or ignore, to completed. Also, we need to measure the effectivess of an offer. This can be measured in many ways, whether financial, or impact on future purchases, or just the engagement of customers.</p>

<p>For the purpose of this question, we will focus on customer engagement, and how customers interacted with each offer in terms of viewing and completing.</p>

<p>Starting with the viewing percentage for each offer:</p>

<p><img src="/images/starbucks/viewed.png" alt="_config.yml" /></p>

<p>We can notice that 6 out of 10 offers were viewed by around 80% or more of customers which seems very good. However, the offers (bogo_3, discount_1, and discount_4) had less than 50% viewing, which suggests that it did not attract customers as the other ones did.</p>

<p>Then we look at the performance of offers in terms of being viewed and completed, and being completed WITHOUT having been viewed:</p>

<p><img src="/images/starbucks/viewed_completed.png" alt="_config.yml" /></p>

<p><img src="/images/starbucks/completed_not_viewed.png" alt="_config.yml" /></p>

<p>We notice that around 30% of those who completed bogo_3, discount_1, and discount_4 did it without even viewing the offer. This means that either way customers would have continued with their purchaing habits without the business spending money on those offers. However, this cannot be concluded unless we know the motivation of this offer. It might not be purely financial, there might be loyalty aspects, or some utility function that is used to measure success of an offer</p>

<p>Furthermore, surprisingly, those three offers (bogo_3, discount_1, and discount_4) that were viewed the least (less than 50%), are the ones that were completed without being viewed the most. This is unclear and could be due to the way the data was synthesized or some other factors that require clarification from business, because the difficulty of those offers is above average</p>

<p>After all, the offer that seems to have done the best in terms of engagement is “discount_3”. Customers seem to have engaged with it in terms of views, completion, and the relatively lower number of those who viewed it and ignored it. On the other hand, “discount_1” seems to have done the poorest in terms of customer engagement, and being completed without customers even noticing it.</p>

<p>The following chart concisely summarizes the lifecycle of those 2 offers:</p>

<p><img src="/images/starbucks/journey.png" alt="_config.yml" /></p>

<p>This kind of diagrams gives a very good view of how each offer is performing. Of course we can add other measures such as financial, or loyalty, if we have data to support.</p>

<h2 id="q2-how-did-the-offers-affect-or-change-customer-behavior">Q2. How did the offers affect or change customer behavior?</h2>
<p>In the first question we looked at how the offers performed in terms of customer engagement. Now, we want to measure if those offers changed the customer behavior. Of course the condition for transactions within an offer is that the offer has been viewed, and completed in the case of bogo and discount.</p>

<p>We will measure this as follows:</p>
<ol>
  <li>For informational offers, we will check if the duration that users take to make the first purchase after the informational offer is reduced in comparison to the usual duration that customers take between consecutive purchases that are not under any offer</li>
  <li>For bogo and discount offers, we will check if the duration between purchase instances for transactions within an offer is different from the duration between normal consecutive transactions that are not within an offer period</li>
  <li>Finally, we will check if the there is a statistically significant change in transaction amounts during an offer (bogo or discount) from outside an offer</li>
</ol>

<p>Those tests will be conducted using a statistical method (z-test), and then we measure the statistical significance of the result.</p>

<p>Let’s start with the tests one by one:
<strong>1. Starting with our test regarding the effect of informational offers:</strong></p>

<p><img src="/images/starbucks/info_duration.png" alt="_config.yml" /></p>

<p>Only by looking at the chart above and the mean values we can see how different the two samples are. Of course, the z-test confirms that informational offer has an effect. However, it is suprisingly counter-intuitive. Because this suggests that customers take longer time to make a purchase after receiving an informational offer in comparison to the time they usually take between transactions.</p>

<p>Nonetheless, this could be due to the time informational offers are beng set. E.g. late at night, or some time in the weekend. This requires further investigation with business, and complimentary data to shed more light.</p>

<p><strong>2. Testing the effect of BOGO and discount offers on transaction DURATIONS:</strong></p>

<p><img src="/images/starbucks/duration.png" alt="_config.yml" /></p>

<p>Clearly, from the mean values we see above and the ztest, during an offer customers do purchase more frequently. I.e. the duration between purchase transactions is reduced!</p>

<p>Of course if needed we can dig deeper to see which specific offer did best</p>

<p><strong>3. Testing the effect of BOGO and discount offers on transaction AMOUNTS:</strong></p>

<p><img src="/images/starbucks/amounts.png" alt="_config.yml" /></p>

<p>Again, this clearly shows that during an offer customers spend more per transaction, and the amount difference is statistically significant</p>

<h2 id="q3-can-we-predict-if-a-customer-will-interact-with-an-offer-and-what-are-the-determining-factors">Q3. Can we predict if a customer will interact with an offer? and what are the determining factors?</h2>
<p>For this purpose, we created a dataset containing:</p>
<ul>
  <li>Socio-demographic information about customers</li>
  <li>Offer details</li>
  <li>Customer usual spending on transactions</li>
</ul>

<p>Then we added a flag of whether each customer viewed and completed the offer. This will be our target for prediction.</p>

<p>This dataset was used to train and evaluate a machine learning model that will try to predict given customer and offer info, whether the customer will view and complete this offer or not</p>

<p><img src="/images/starbucks/ml-model.png" alt="_config.yml" /></p>

<p>The built model performed relatively well with an accuracy of around 73%. Of course, we did not rely only on accuracyas it can be prone to biases and imbalance. Therefore, we evaluated the model with f1-score, and it reported a value of 0.68, which is very reasonable given the accuracy.</p>

<p>This model now enables us to infer whether a customer will engage with an offer or not before sending out the offer.</p>

<p>Finally, let’s identify what are the most important features determined by the model that affect whethe a customer will engage with an offer. One way to do that is by looking at features importance:</p>

<p><img src="/images/starbucks/features_imp.png" alt="_config.yml" /></p>

<p>We can clearly see that individual attributes are the most important features, followed by offer properties. Those features are:</p>
<ul>
  <li>avg_trx_amount: The average spending amount per transaction of a customer</li>
  <li>year_of_membership: How long the customer has been a member</li>
  <li>social_ch: whether the offer was sent of a social media channel or not</li>
  <li>income: Customer’s income</li>
  <li>age: Customer’s age</li>
  <li>reward: The reward amount of the offer</li>
  <li>difficulty: Offer’s difficulty</li>
  <li>duration: How long the offer will run for</li>
  <li>mobile_ch: Whether the offer was sent over the mobile channel</li>
  <li>If the offer is of type buy-one-get-one</li>
</ul>

<p>Now let’s look at how those features are correlated with the outcome and with each other. However, we will limit it only to 5 features for ease of visualization:</p>

<p><img src="/images/starbucks/scatterplot.png" alt="_config.yml" /></p>

<p>Focusing on the diagonal charts, we can observe the following:</p>
<ul>
  <li>Average transaction amount is positively correlated with likelihood of participating</li>
  <li>Years of membership that are between 2 and 3 are more positively correlted with a positive outcome. Less or more years are the other way around. Especially newer members.</li>
  <li>Social channel shows a positive correlation</li>
  <li>The higher the income the more likely someone seems to participate in an offer</li>
</ul>

<h2 id="conclusion">Conclusion</h2>

<p>In this exercise we analyzed the customers and offers data from Starbucks. We tried to answer the different business questions.</p>

<p>We started our analysis by trying to look at how customers interacted with the different kinds of offer. We measured what we called customer engagement. Then we looked at the interaction with each offer an offer lifecycle and a customer journey.</p>

<p>Then we looked at the problem from another angle. We tried to see how offers impacted customer behavior. We followed a statistical method to assess the significance of this effect, and we found the indeed offers affect customer spending and the frequency of transactions.</p>

<p>Finally, we built a predictive model to help us identify whether an offer would suit a certain customer. Also, the model gave us an insgiht at what the important features are in determining whether a customer will enage with an offer or not.</p>

<p>The work can be further improved with some extra sources of data such as item pricing, or through some further engineering of some of the features.</p>]]></content><author><name></name></author><summary type="html"><![CDATA[Offers are an important tool for engaging your customers, promoting new offerings, or increasing loyalty. However, targeting a customer with the wrong offer could be useless, or in some cases could bring a negative outcome. Therefore, it is very important to understand the interaction between customers and offers.]]></summary></entry><entry><title type="html">What drives Airbnb pricing</title><link href="https://alkalaji.github.io/Airbnb-Seattle-Data-Analysis/" rel="alternate" type="text/html" title="What drives Airbnb pricing" /><published>2021-02-28T00:00:00+00:00</published><updated>2021-02-28T00:00:00+00:00</updated><id>https://alkalaji.github.io/Airbnb-Seattle-Data-Analysis</id><content type="html" xml:base="https://alkalaji.github.io/Airbnb-Seattle-Data-Analysis/"><![CDATA[<p>Airbnb serves guests and hosts whether to list a property or find one that matches their need. However, a badly priced property affects both sides negatively. Therefore, it is very important to understand pricing.</p>

<p><img src="https://render.fineartamerica.com/images/rendered/share/27275092&amp;domainId=1" alt="_config.yml" /></p>

<h2 id="introduction">Introduction</h2>

<p>Airbnb revolutionized the industry with its platform by bringing both the hosts and guests directly into one platform. However, unlike established businesses that work in hospitality, now individuals found themselves as people who are running their own business over airbnb.</p>

<p>Part of a successful business is the right pricing. Therefore, using Airbnb data for Seattle we will try to answer the following business question related to pricing:</p>
<ul>
  <li>Is there any trend in house prices and availability, and how can it be explained?</li>
  <li>Can we estimate the price of a listing given listing features?</li>
  <li>What are the factors determining the price of a listing?</li>
</ul>

<p>We will tackle those questions one by one. So let’s get started!</p>

<h2 id="is-there-any-trend-in-house-prices-and-availability-and-how-can-it-be-explained">Is there any trend in house prices and availability, and how can it be explained?</h2>
<p>Pricing always changes especially in sectors like tourism and hospitality, and Airbnb listings are no exception. Factors like seasons, holidays, and so on affect both pricing and demand!</p>

<p>We will start by looking at the average listing prices fo each day and plot over a year’s period to see how the prices change:</p>

<p><img src="/images/price-vs-time.png" alt="_config.yml" /></p>

<p>We can quicky observe few things from the chart above:</p>
<ul>
  <li>Pricing over the weekend (in yellow) is abut 5% to 6% higher than usual days throughout the year</li>
  <li>Price over the first half year is generally increasing, whereas it decreases over the second half</li>
  <li>We can see clear spikes near Valentine’s day, spring break, summer break, and a small one near new year</li>
</ul>

<p>However, we cannot look at pricing without looking at availability:</p>

<p><img src="/images/available-vs-time.png" alt="_config.yml" /></p>

<p>This chart is very interesting because it follows the expected logic but at the same time is counterintuitive. We can observe the following:</p>
<ul>
  <li>We can see the same dips in availability around seasons as expected</li>
  <li>The small zigzag pattern throughout the chart seems to correspond with weekends</li>
  <li>Counterintuitively, there is an overall positive trend of availability throughout the year</li>
</ul>

<p>The general trend of increase in availability did not drop the prices, especially during the first half of the year. This could be attributed to other factors that could be revealed upon closer examination of other data sources, such events, or change in demographics in Seattle.</p>

<h2 id="can-we-estimate-the-price-of-a-listing-given-listing-features">Can we estimate the price of a listing given listing features?</h2>

<p>Even though the charts above gave us a good idea of pricing and availability trends on the platform, it is still not easy task to price a listing. If only we could have a crystal ball that can suggest to us listing prices!</p>

<p>Well, the good news is that using machine leaning is the closest thing we can get to a crystal ball. Therefore, to tackle this question we used the data available to build a machine learning model that can look at the historical pricing data and all property features to suggest a price.</p>

<p>The graph below illustrates the kind of input data that was fed into our predictive model, with the output being the expected price:</p>

<p><img src="/images/ml-model.png" alt="_config.yml" /></p>

<p>Without getting into the details, the model performed relatively OK. However, it can be further improved with some possibly extra sources of data. This performance can be illsutrated by looking at the following chart:</p>

<p><img src="/images/actual-vs-predicted.png" alt="_config.yml" /></p>

<p>This chart shows the actual prices of a sample of data, and the predictions from the machine learning model. In a perfect scenario, all points should fall on the red line. However, for our case the model is predicting prices with a margin of error of around 25%.</p>

<h2 id="what-are-the-factors-determining-the-price-of-a-listing">What are the factors determining the price of a listing?</h2>

<p>Now that we have a working model that can make predictions, we can use the model not only to predict prices, but also to identify the most important features in determining the listing price.</p>

<p>The following table lists the top 10 most important features in determining the price ranked from most important:</p>

<p><img src="/images/important-features.png" alt="_config.yml" /></p>

<p>Clearly, the most important features to determine a property’s price are its size and how many it accomodates. Next, comes the listing type, the level of availability and how much it was reviewed.</p>

<p>This kind of insight helps us understand for example that property size is more important to some extent that location. Also, it reduces the number of variables that we need to take into consideration when pricing.</p>

<h2 id="conclusion">Conclusion</h2>

<p>We started with our analysis of pricing from a high level, by looking at trends and seasonality of pricing and availability. This helped us identify the effect of weekends, holidays and so on on those factors.</p>

<p>Then we delved deeper, by training a machine learning model to predict for us an ideal price given different listing features. That was our crystal ball, despite being a bit hazy with the relatively degraded accuracy. Nonetheless, it took us one step closer to identifying the most important factors in pricing.</p>

<p>Finally, we utilized how the model learned to identify those most important factors and that’s the most granular level of details that we managed to acquire.</p>

<p>Defnitely, the work can be further improved by utilizing the textual data and analyzing it. Also, including the time factor as a more integral part in the analysis and predictive modeling.</p>]]></content><author><name></name></author><summary type="html"><![CDATA[Airbnb serves guests and hosts whether to list a property or find one that matches their need. However, a badly priced property affects both sides negatively. Therefore, it is very important to understand pricing.]]></summary></entry><entry><title type="html">You’re up and running!</title><link href="https://alkalaji.github.io/Hello-World/" rel="alternate" type="text/html" title="You’re up and running!" /><published>2014-03-03T00:00:00+00:00</published><updated>2014-03-03T00:00:00+00:00</updated><id>https://alkalaji.github.io/Hello-World</id><content type="html" xml:base="https://alkalaji.github.io/Hello-World/"><![CDATA[<p>Next you can update your site name, avatar and other options using the _config.yml file in the root of your repository (shown below).</p>

<p><img src="/images/config.png" alt="_config.yml" /></p>

<p>The easiest way to make your first post is to edit this one. Go into /_posts/ and update the Hello World markdown file. For more instructions head over to the <a href="https://github.com/barryclark/jekyll-now">Jekyll Now repository</a> on GitHub.</p>]]></content><author><name></name></author><summary type="html"><![CDATA[Next you can update your site name, avatar and other options using the _config.yml file in the root of your repository (shown below).]]></summary></entry></feed>