<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Moses Kinoti on Medium]]></title>
        <description><![CDATA[Stories by Moses Kinoti on Medium]]></description>
        <link>https://medium.com/@mkinoti19?source=rss-d9c4cba5a42d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*CX_FFbOl6y0WbvF-sTlYQg.jpeg</url>
            <title>Stories by Moses Kinoti on Medium</title>
            <link>https://medium.com/@mkinoti19?source=rss-d9c4cba5a42d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 06:02:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mkinoti19/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Data Driven Dynamic Pricing using Python and Machine Learning]]></title>
            <link>https://medium.com/@mkinoti19/data-driven-dynamic-pricing-using-python-and-machine-learning-b898e0e5fbe3?source=rss-d9c4cba5a42d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b898e0e5fbe3</guid>
            <category><![CDATA[business-strategy]]></category>
            <category><![CDATA[dynamic-pricing]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Moses Kinoti]]></dc:creator>
            <pubDate>Thu, 29 Jun 2023 10:01:46 GMT</pubDate>
            <atom:updated>2023-07-04T09:13:29.443Z</atom:updated>
            <content:encoded><![CDATA[<p>Dynamic Pricing is a strategy in which product or service prices continue to adjust in response to the real-time supply and demand (per Business Insider). It has filled the shortcomings of historical pricing strategies that were somewhat rigid in their structure and not easily responsive to changes in demand and supply.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*h61lXWuNgJpFOwud" /><figcaption>Photo by <a href="https://unsplash.com/@fikrirasyid?utm_source=medium&amp;utm_medium=referral">Fikri Rasyid</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Some of the key ways dynamic pricing has revolutionized business product or service pricing is that <strong>it gives greater control over your pricing strategy </strong>and <strong>it allows flexibility without compromising brand value</strong>, something which is very crucial for retention of the customer base.</p><p>In this project, we take a case example of a ride hailing app called Dash and we leverage Data Science techniques and Machine Learning to be able to implement a data-driven dynamic pricing strategy that is able to maximize revenue and profitability by pricing items at the right level that balances supply and demand dynamics.</p><p>We first begin by importing the necessary Python libraries and the dataset to be used in the project. The dataset used can be found <a href="https://statso.io/dynamic-pricing-case-study/">here</a>.</p><pre>#importing Python libraries and dataset<br>import pandas as pd<br>import plotly.express as px<br>import plotly.graph_objects as go<br><br>data = pd.read_csv(&quot;/content/dashapp_pricing.csv&quot;)<br>print(data.head())</pre><p>Output:</p><pre>   Number_of_Riders  Number_of_Drivers Location_Category  \<br>0                90                 45             Urban   <br>1                58                 39          Suburban   <br>2                42                 31             Rural   <br>3                89                 28             Rural   <br>4                78                 22             Rural   <br><br>  Customer_Loyalty_Status  Number_of_Past_Rides  Average_Ratings  \<br>0                  Silver                    13             4.47   <br>1                  Silver                    72             4.06   <br>2                  Silver                     0             3.99   <br>3                 Regular                    67             4.31   <br>4                 Regular                    74             3.77   <br><br>  Time_of_Booking Vehicle_Type  Expected_Ride_Duration  \<br>0           Night      Premium                      90   <br>1         Evening      Economy                      43   <br>2       Afternoon      Premium                      76   <br>3       Afternoon      Premium                     134   <br>4       Afternoon      Economy                     149   <br><br>   Historical_Cost_of_Ride  <br>0               284.257273  <br>1               173.874753  <br>2               329.795469  <br>3               470.201232  <br>4               579.681422  </pre><p>We then perform exploratory data analysis to have a better look at the descriptive statistics of the data.</p><pre>#exploratory data analysis<br>print(data.describe())</pre><p>Output:</p><pre>      Number_of_Riders  Number_of_Drivers  Number_of_Past_Rides  \<br>count       1000.000000        1000.000000           1000.000000   <br>mean          60.372000          27.076000             50.031000   <br>std           23.701506          19.068346             29.313774   <br>min           20.000000           5.000000              0.000000   <br>25%           40.000000          11.000000             25.000000   <br>50%           60.000000          22.000000             51.000000   <br>75%           81.000000          38.000000             75.000000   <br>max          100.000000          89.000000            100.000000   <br><br>       Average_Ratings  Expected_Ride_Duration  Historical_Cost_of_Ride  <br>count      1000.000000              1000.00000              1000.000000  <br>mean          4.257220                99.58800               372.502623  <br>std           0.435781                49.16545               187.158756  <br>min           3.500000                10.00000                25.993449  <br>25%           3.870000                59.75000               221.365202  <br>50%           4.270000               102.00000               362.019426  <br>75%           4.632500               143.00000               510.497504  <br>max           5.000000               180.00000               836.116419  </pre><p>We can create a scatter plot graph to be able to visualize the relationship between the expected ride duration and the historical cost of the ride:</p><pre>#plotting a scatter plot graph for ride duration against cost of ride<br>fig = px.scatter(data, x=&#39;Expected_Ride_Duration&#39;, <br>                 y=&#39;Historical_Cost_of_Ride&#39;,<br>                 title=&#39;Expected Ride Duration vs Historical Cost of Ride&#39;,<br>                 trendline=&#39;ols&#39;)<br>fig.show()</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*pZgR2qGO-ghHdk4L5hD_fA.png" /></figure><p>As expected, there is a linear distribution that shows one variable is directly proportional to the other i.e. ( an increase in expected ride duration will lead to a corresponding increase in the cost of the ride) which makes sense because the longer the trip the more money it will cost.</p><p>We can also view the distribution of the historical cost of rides based on the vehicle type using a box plot:</p><pre>#plotting a box plot graph for cost of ride against vehicle type<br>fig = px.box(data, x=&#39;Vehicle_Type&#39;,<br>             y=&#39;Historical_Cost_of_Ride&#39;,<br>             title=&#39;Historical Cost of Ride Distribution by Vehicle Type&#39;)<br>fig.show()</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*XorOMI1P18kHtnynsP9F7Q.png" /></figure><p>Reading off the median values (middle lines in the box) the cost of a premium vehicle (about 400) is higher than the cost of the economy vehicle (about 330), this is also expected considering factors such as comfort and number of seats the car. (Some ride hailing apps cap the maximum number of riders that can seat a car based on vehicle type).</p><p>We can replicate the same to view the distribution of the historical cost of rides based on the time of booking with a box plot:</p><pre>#plotting a box plot graph for cost of ride against time of booking<br>fig = px.box(data, x=&#39;Time_of_Booking&#39;,<br>             y=&#39;Historical_Cost_of_Ride&#39;,<br>             title=&#39;Historical Cost of Ride Distribution by Time of Booking&#39;)<br>fig.show()</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*3zYcOEN-W8T2nG0nkxY3NQ.png" /></figure><p>Reading off the median values (middle lines in the box) the historical cost of a ride is high in the morning (about 380) and highest in the afternoon (about 390) but gets lower in the evening (about 360) and is lowest in the night(about 330), this is expected considering factors such as amount of vehicle traffic during the day: heavy vehicle traffic in the morning and afternoon hours but less traffic in the evening and night time.</p><p>We can have a look at the correlation matrix of the dataset to get a summarization of relationships between all the variables using a measure of linear association between the two variables of between 0 and 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*vOMDwTsxx5Zow_nDUoMxgw.png" /></figure><p>From the correlation matrix, we can deduce a strong correlation between expected ride duration and historical cost of ride.</p><p>The dataset provided only brings out that the pricing model used takes only the expected ride duration as a factor to determine the price for a ride. Implementation of a dynamic pricing strategy will see to adjust the ride costs dynamically based on the demand and supply levels observed in the data in real-time. The strategy will be to capture high-demand periods and low-supply scenarios to increase prices, while low-demand periods and high-supply situations will lead to price reductions.</p><p>We can now move forward with the code implementation of this strategy:</p><pre>#implementing the dynamic pricing strategy<br>import numpy as np<br><br>#calculating demand_multiplier based on percentile for high and low demand<br>high_demand_percentile = 75<br>low_demand_percentile = 25<br><br>data[&#39;demand_multiplier&#39;] = np.where(data[&#39;Number_of_Riders&#39;] &gt; np.percentile(data[&#39;Number_of_Riders&#39;], high_demand_percentile),<br>                                     data[&#39;Number_of_Riders&#39;] / np.percentile(data[&#39;Number_of_Riders&#39;], high_demand_percentile),<br>                                     data[&#39;Number_of_Riders&#39;] / np.percentile(data[&#39;Number_of_Riders&#39;], low_demand_percentile))<br><br>#calculating supply_multiplier based on percentile for high and low supply<br>high_supply_percentile = 75<br>low_supply_percentile = 25<br><br>data[&#39;supply_multiplier&#39;] = np.where(data[&#39;Number_of_Drivers&#39;] &gt; np.percentile(data[&#39;Number_of_Drivers&#39;], low_supply_percentile),<br>                                     np.percentile(data[&#39;Number_of_Drivers&#39;], high_supply_percentile) / data[&#39;Number_of_Drivers&#39;],<br>                                     np.percentile(data[&#39;Number_of_Drivers&#39;], low_supply_percentile) / data[&#39;Number_of_Drivers&#39;])<br><br>#defining the price adjustment factors for high and low demand/supply<br>demand_threshold_high = 1.2 #higher demand threshold<br>demand_threshold_low = 0.8 #lower demand threshold<br>supply_threshold_high = 0.8 #higher supply threshold<br>supply_threshold_low = 1.2 #lower supply threshold<br><br>#calculating adjusted_ride_cost for dynamic pricing<br>data[&#39;adjusted_ride_cost&#39;] = data[&#39;Historical_Cost_of_Ride&#39;] * (<br>    np.maximum(data[&#39;demand_multiplier&#39;], demand_threshold_low) * <br>    np.maximum(data[&#39;supply_multiplier&#39;], supply_threshold_high)<br>)</pre><p>We begin by first defining percentiles that represent high and low demand levels. Afterwards we calculate the demand multiplier by comparing the number of riders to these defined percentiles. If the number of riders exceeds the percentile for high demand then the multiplier is set as the number of riders divided by the high-demand percentile. However if the number of riders falls below the percentile for low demand then the demand multiplier is set as the number of riders divided by the low-demand percentile.</p><p>The next thing is to defining percentiles that represent high and low supply levels. If the number of drivers exceeds the low-supply percentile, the supply multiplier is set as the high-supply percentile divided by the number of drivers. Otherwise if the number of drivers is below the low-cost supply percentile then the supply multiplier is set as the low-supply percentile divided by the number of drivers.</p><p>We conclude by calculating the adjusted ride cost for dynamic pricing where it multiplies the historical cost of the ride by the maximum of the demand multiplier and a lower threshold (demand_threshold_low) and also by the maximum of the supply multiplier and an upper threshold (supply_threshold_high). This multiplication ensures that the adjusted ride cost captures the combined effect of demand and supply multipliers with the thresholds serving as caps or floors to control the price adjustments.</p><p>We can now to proceed to calculate the profit percentage when this dynamic pricing strategy is implemented:</p><pre>#calclating profit percentage for each ride using dynamic pricing strategy<br>data[&#39;profit_percentage&#39;] = ((data[&#39;adjusted_ride_cost&#39;] - data[&#39;Historical_Cost_of_Ride&#39;]) / data[&#39;Historical_Cost_of_Ride&#39;]) * 100<br><br>#ID profitable rides when profit percentage percentage is positive<br>profitable_rides = data[data[&#39;profit_percentage&#39;] &gt; 0]<br><br>#ID rides incurring losses when profit percentage is negative<br>loss_rides = data[data[&#39;profit_percentage&#39;] &lt; 0]<br><br>import plotly.graph_objects as go<br><br>#calculate the count of profitable and loss rides<br>profitable_count = len(profitable_rides)<br>loss_count = len(loss_rides)<br><br>#creating a donut chart to show the distribution of profitable and loss rides using the dynamic pricing strategy<br>labels = [&#39;Profitable Rides&#39;, &#39;Loss Rides&#39;]<br>values = [profitable_count, loss_count]<br><br>fig = go.Figure(data=[go.Pie(labels=labels, values=values, hole=0.4)])<br>fig.update_layout(title=&#39;Profitability of Rides (Dynamic Pricing vs Historical Pricing)&#39;)<br>fig.show()</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d16Myrjtm3ZH99DP7ZmsGg.png" /></figure><p>From the donut chart above, we can see a resounding 82.7% of all rides implementing dynamic pricing strategy turned out to be profitable rides.</p><p>We can now look at the relationship between the expected ride duration and the adjusted cost of the ride based on the dynamic pricing strategy:</p><pre>#Creating a scatter plot graph to view relationship between expected ride duration and the cost of the ride based on dynamic pricing strategy<br>fig = px.scatter(data,<br>                 x=&#39;Expected_Ride_Duration&#39;,<br>                 y=&#39;adjusted_ride_cost&#39;,<br>                 title=&#39;Expected Ride Duration vs Cost of Ride&#39;,<br>                 trendline=&#39;ols&#39;)<br>fig.show()</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*RnHBoPe0Ae8BIyQ6X04LZA.png" /></figure><p>From the scatter plot above, we are able to see more distribution of cost of the rides on certain durations since more variables have come into play to influence the cost of the ride.</p><p>We can now begin to train a machine learning model to aid in the cost of ride prediction using the dynamic pricing strategy. For this project I used a Random Forest Regression Model. First we create a data preprocessing pipeline to preprocess the raw data into a clean, organized and structured format suitable for analysis:</p><pre>#Training a predictive ML model<br>import pandas as pd<br>import numpy as np<br>from sklearn.preprocessing import StandardScaler<br><br>def data_preprocessing_pipeline(data):<br>  #ID numeric and categorical features<br>  numeric_features = data.select_dtypes(include=[&#39;float&#39;,&#39;int&#39;]).columns<br>  categorical_features = data.select_dtypes(include=[&#39;object&#39;]).columns<br><br>  #Handling missing values in numeric features<br>  data[numeric_features] = data[numeric_features].fillna(data[numeric_features].mean())<br><br>  #Detecting and handling outliers in numeric features using IQR<br>  for feature in numeric_features:<br>    Q1 = data[feature].quantile(0.25)<br>    q3 = data[feature].quantile(0.75)<br>    IQR = Q3 - Q1<br>    lower_bound = q1 - (1.5 * IQR)<br>    upper_bound = q3 + (1.5 * IQR)<br>    data[feature] = np.where((data[feature] &lt; lower_bound) | (data[feature] &gt; upper_bound),<br>                             data[feature].mean(), data[feature])<br>    <br>    #Handling missing values in categories features<br>    data[categorical_features] = data[categorical_features].fillna(data[categorical_features].mode().iloc[0])<br><br>    return data</pre><p>We will need variable “Vehicle_Type” but we will have to convert it to a numerical feature</p><pre>#Converting vehicle type to a numerical feature<br>data[&quot;Vehicle_Type&quot;] = data[&quot;Vehicle_Type&quot;].map({&quot;Premium&quot;: 1, &quot;Economy&quot;: 0})</pre><p>We will also need variable “Time_of_Booking” and convert it to a numerical feature</p><pre>#Converting time of booking to a numerical feature<br>data[&quot;Time_of_Booking&quot;] = data[&quot;Time_of_Booking&quot;].map({&quot;Afternoon&quot;: 0, &quot;Evening&quot;: 1, &quot;Morning&quot;: 2, &quot;Night&quot;: 3})</pre><p>Next is splitting the data to train the ML model to predict the cost of a ride:</p><pre>#splitting data to train and test<br>from sklearn.model_selection import train_test_split<br>x = np.array(data[[&quot;Number_of_Riders&quot;, &quot;Number_of_Drivers&quot;, &quot;Vehicle_Type&quot;, &quot;Time_of_Booking&quot;, &quot;Expected_Ride_Duration&quot;]])<br>y = np.array(data[[&quot;adjusted_ride_cost&quot;]])<br><br>x_train, x_test, y_train, y_test = train_test_split(x,<br>                                                    y,<br>                                                    test_size=0.2,<br>                                                    random_state=42)<br><br>#Reshape y to 1D array<br>y_train = y_train.ravel()<br>y_test = y_test.ravel()<br><br>#Training a random forest regression model<br>from sklearn.ensemble import RandomForestRegressor<br>model = RandomForestRegressor()<br>model.fit(x_train, y_train)</pre><p>We can now input values to test this Machine Learning model:</p><pre>#testing the ML model using some input values<br>def get_vehicle_type_numeric(vehicle_type):<br>  vehicle_type_mapping = {<br>      &quot;Premium&quot;: 1,<br>      &quot;Economy&quot;: 0<br>  }<br>  vehicle_type_numeric = vehicle_type_mapping.get(vehicle_type)<br>  return vehicle_type_numeric<br><br>def get_time_of_booking_numeric(time_of_booking):<br>  time_of_booking_mapping = {<br>      &quot;Afternoon&quot;: 0, <br>      &quot;Evening&quot;: 1, <br>      &quot;Morning&quot;: 2, <br>      &quot;Night&quot;: 3 <br>  }<br>  time_of_booking_numeric = time_of_booking_mapping.get(time_of_booking)<br>  return time_of_booking_numeric<br><br>#making predictions using user input values<br>def predict_price(number_of_riders, number_of_drivers, vehicle_type, time_of_booking, Expected_Ride_Duration):<br>  vehicle_type_numeric = get_vehicle_type_numeric(vehicle_type)<br>  if vehicle_type_numeric is None:<br>    raise ValueError(&quot;Invalid vehicle type&quot;)<br>  <br>  time_of_booking_numeric = get_time_of_booking_numeric(time_of_booking)<br>  if time_of_booking_numeric is None:<br>    raise ValueError(&quot;Invalid time of booking&quot;)<br><br>  input_data = np.array([[number_of_riders, number_of_drivers, vehicle_type_numeric, time_of_booking_numeric, Expected_Ride_Duration]])<br>  predicted_price = model.predict(input_data)<br>  return predicted_price<br><br>#User input example<br>user_number_of_riders = 65<br>user_number_of_drivers = 30<br>user_vehicle_type = &quot;Economy&quot;<br>user_time_of_booking = &quot;Afternoon&quot;<br>Expected_Ride_Duration = 50<br>predicted_price = predict_price(user_number_of_riders, user_number_of_drivers, user_vehicle_type, user_time_of_booking, Expected_Ride_Duration)<br>print(&quot;The predicted price for the ride is:&quot;, predicted_price)</pre><p>We are also going to test to real world environment cases to show the model’s effectiveness:</p><ol><li>The number of riders surges to 80 in the afternoon requesting the “Economy” and the number of available drivers is 25. The average estimates of the ride time is about 40 minutes.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZsN_TJu1RThnGL72ZYQQqw.png" /></figure><p>For this, we see the price is about 452.</p><p>2. The number of riders drops to about 30 requesting an “Economy” vehicle in the night and there are a number of available drivers, about 40 and the estimated duration on the ride remains at 40 minutes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*trXBKVz06jySH0eMi4xziQ.png" /></figure><p>We observe that the price drops by over half to 206.</p><p>3. The same number of riders (30) request a “Premium” vehicle at night and about 40 drivers are available. The estimated duration of the ride is still 40 minutes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4BmtRZkASdsLuNgckxD1JA.png" /></figure><p>The price now goes up to 254.</p><p>Throughout the test I left the Expected Ride Duration at 40 intentionally to display the effectiveness of implementing dynamic pricing strategy and leveraging other real-time variables to influence the final cost of the ride.</p><p>Finally we will take a look at the model’s prediction accuracy:</p><pre>#model prediction<br>y_pred = model.predict(x_test)<br><br>#checking model accuracy<br>from sklearn.metrics import r2_score<br><br>r2_score(y_test, y_pred)*100</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/1*iHOEsDx9Djqp_nrzliOeqQ.png" /></figure><p>The model has an accuracy of 86%, certainly not the only performance metric to be considered when testing a model (there’s precision and recall too when a confusion matrix is used in a classification model) nor its’ optimal performance level as the accuracy can be increased further by taking certain steps like hyperparameter tuning and increasing the amount of data samples in the training data. However with the recorded accuracy the results derived are still viable and in accordance to the influencing variables used to make the prediction.</p><p>We can then show a comparison between the actual and predicted values with a scatter plot graph:</p><pre>#comparison of actual and predicted results<br>import plotly.graph_objects as go<br><br>#predict on the test set<br>y_pred = model.predict(x_test)<br><br>#create a scatter plot with actual vs predicted values<br>fig = go.Figure()<br><br>fig.add_trace(go.Scatter(<br>    x=y_test.flatten(),<br>    y=y_pred,<br>    mode=&#39;markers&#39;,<br>    name=&#39;Actual vs Predicted&#39;<br>))<br><br>#Add a line representing the ideal case<br>fig.add_trace(go.Scatter(<br>    x=[min(y_test.flatten()), max(y_test.flatten())],<br>    y=[min(y_test.flatten()), max(y_test.flatten())],<br>    mode=&#39;lines&#39;,<br>    name=&#39;Ideal&#39;,<br>    line=dict(color=&#39;red&#39;, dash=&#39;dash&#39;)<br>))<br><br>fig.update_layout(<br>    title=&#39;Actual vs Predicted Values&#39;,<br>    xaxis_title=&#39;Actual Values&#39;,<br>    yaxis_title=&#39;Predicted Values&#39;,<br>    showlegend=True<br>)<br><br>fig.show()</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*pEehRt0ocKgx_eM5uRUvzA.png" /></figure><p>In summary, dynamic pricing when implemented can be powerful to businesses to not only set and adjust prices dynamically based on various real-time factors but to also maintain flexibility of their prices to remain competitive in their respective markets and make profits from their products or services.</p><p>Credits: <a href="https://amankharwal.medium.com/">Aman Kharwal</a></p><p>Reference material:</p><p>Dynamic Pricing: <a href="https://www.business.com/articles/what-is-dynamic-pricing-and-how-does-it-affect-ecommerce/">https://www.business.com/articles/what-is-dynamic-pricing-and-how-does-it-affect-ecommerce/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b898e0e5fbe3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>