Weekly Walmart Sales Analysis

Utilizing SQL, R, and Python to analyze Walmart sales.

Welcome

This project is currently being re-written. There are major changes in progress. First, I am looking to include more statistical analysis on how sales correlate with every variable, which means that the code and analysis of insights will be updated on a daily basis. Second, I am changing the format of this report to be more similar to a business case study. Thus, sections are being reorganized and contain imperfect writing. Third, because of the following changes, the beautification of charts and tables may not be the main priority. Please proceed with this in mind.

For a more polished (but less relevant and more informal case study) to showcase my data analysis skills and interest in psychology, please click here!

Contents

Introduction

Impact of Variables on Weekly Sales

Geographical Data

Statistical Correlation

Introduction

The conventional theory of the firm states that the principal objective of any business is to maximize profits. Internally, the firm can attempt to control this through increasing revenue or decreasing costs. However, since firms do not exist within a closed ecosystem, their profits are always at the mercy of the external environment. All firms can do is align their internal strategy with the external environmental conditions.

Between January 2010 and December 2012, the Walmart Sales data set tracks weekly Walmart sales of 45 stores, alongside 5 external variables: Holiday_Flag, unemployment rate, CPI, fuel price, and temperature. This case study will compare Walmart’s experimental data with traditional literature to highlight the negligible impact of these 5 external variables on Walmart’s weekly sales.

First, the data is prepared by rounding values and removing missing values.

Show Python code
#import 
import pandas as pd
df = pd.read_csv('Walmart_sales.csv', parse_dates=['Date'], dayfirst=False)

#sort by store number and then date
df.sort_values(by=['Store', 'Date'])

#standarize dates to mm-dd-yyyy
df['Date'] = pd.to_datetime(df['Date'], format='%d-%m-%Y').dt.strftime('%m-%d-%Y')

#rounding data 
df.round({'Weekly_Sales':2, 'Temperature':0, 'Fuel_Price':2, 'CPI':3, 'Unemployment':3})

#removing missing values
df.dropna

#create cleaned csv
df.to_csv('./WalmartSalesClean.csv')

Stores 20, 4, and 14 have the most amount of sales

First, weekly sales data is analyzed without taking the other variables(e.g. holidays, unemployment) into consideration.

We can identify the stores with the highest sales:

Show SQL code
SELECT Store, sum(CAST(Weekly_Sales AS FLOAT)) AS Weekly_Sales
FROM WalmartSalesClean
GROUP BY Store
ORDER BY Weekly_Sales

It seems like store 33, 44, and 5 have the least amount of sales, while store 20, 4, and 14 have the most.

Show SQL code
SELECT TOP 3 Store, sum(Weekly_Sales) AS Weekly_Sales, avg(Temperature) AS Temperature, 
avg(CPI) AS CPI, avg(Fuel_Price) AS Fuel_Price, avg(Unemployment) AS Unemployment
FROM WalmartSalesClean
GROUP BY Store
ORDER BY Weekly_Sales
Table 1: Highest Unemployment
Store Weekly_Sales Temperature Fuel_Price CPI Unemployment
5 45475689 69.41014 3.219699 216.5656 6.295406
44 43293088 53.69713 3.286147 128.6797 6.735622
33 37160222 76.72818 3.575923 128.6797 8.533154
Show SQL code
SELECT TOP 3 Store, sum(Weekly_Sales) AS Weekly_Sales, avg(Temperature) AS Temperature, 
avg(CPI) AS CPI, avg(Fuel_Price) AS Fuel_Price, avg(Unemployment) AS Unemployment
FROM WalmartSalesClean
GROUP BY Store
ORDER BY Weekly_Sales desc
Table 2: Lowest Unemployment
Store Weekly_Sales Temperature Fuel_Price CPI Unemployment
14 288999911 57.79098 3.417608 186.2857 8.648748
4 299543953 62.25336 3.216972 128.6797 5.964692
20 301397792 55.45140 3.417608 209.0381 7.371413

However, there doesn’t seem to be an easily identifiable correlation between sales and the variables (e.g. unemployment, temperature, etc.). Further analysis must be conducted to determine the relationship between these variables.

Sales peak in December and fall in January

We can also see how Walmart sales varied from month to month.

There always seems to be a spike in December and a low in January. The high in December is likely caused by the holiday season, as consumers commonly buy large quantities of food, drinks, and gifts. The low in January could be explained by people saving because of New Year’s resolutions or ‘No-Spend’ January – trends that emphasize saving money. Consumers may also have less money after the December spending.

This graph also emphasizes the cyclic nature of consumer spending. The pattern is very consistent across the two years.

Super Bowl Week generates the most amount of sales

Holidays are notorious for driving sales since Walmart often runs promotional markdown events to incentivize purchases when consumers are celebrating. Clearly, it works.

Show SQL code
SELECT Holiday_Flag, avg(Weekly_Sales) AS Weekly_Sales
FROM WalmartSalesClean
GROUP BY Holiday_Flag

Holidays can be narrowed into a few specific categories. When looking at the data, the below weeks are deemed ‘Holiday Weeks’.

Show SQL code
SELECT Holiday_Flag, avg(CAST(Weekly_Sales AS FLOAT)) AS Weekly_Sales
FROM WalmartSalesClean
GROUP BY Holiday_Flag
Table 3: Weeks including a holiday
Date Weekly_Sales
02-12-2010 1641957
09-10-2010 1507461
11-26-2010 1955624
12-31-2010 1367320
02-11-2011 1649615
09-09-2011 1540471
11-25-2011 2033321
12-30-2011 1497463
02-10-2012 1802477
09-07-2012 1661767

The (repeating) holidays that appear in this data are:

With these holidays, it is implied that the curator of data would have been American and this data could have been taken from American stores. However, the geographical location of these stores are not contained within the data set, so we should be wary of this assumption.

First, the days had the highest profit should be examined:

Show SQL code
ALTER TABLE WalmartSalesClean
ALTER COLUMN Holiday_Flag Int;

 --filtering for holiday flags and sorting 
SELECT Date, SUM(CAST(Weekly_Sales AS FLOAT)) AS Weekly_Sales
FROM WalmartSalesClean 
WHERE Holiday_Flag='1'
GROUP BY Date
ORDER BY Weekly_Sales DESC;
Table 4: Holiday weeks with the most amount of sales
Date Weekly_Sales
11-25-2011 3004702
11-25-2011 2950199
11-26-2010 2939946
11-26-2010 2921710
11-25-2011 2906233
11-25-2011 2864171

It seems like Thanksgiving (for all stores) consistently ranks the highest amongst all the holidays. To be more accurate, the total sales per holiday can be extracted.

Show SQL code
SELECT 
CASE 
WHEN Holiday = 02 THEN 'Super Bowl' --changing months to holiday names
WHEN Holiday = 09 THEN 'Labor Day'
WHEN Holiday = 11 THEN 'Thanksgiving'
WHEN Holiday = 12 THEN 'Christmas'
END AS Holiday, SUM(Weekly_Sales) AS Weekly_Sales
    FROM (  --subquery to have two GROUP BY statements 
    SELECT SUBSTRING (DATE, 1, 2) AS Holiday, SUM(CAST(Weekly_Sales AS FLOAT)) AS Weekly_Sales 
    FROM WalmartSalesClean 
    WHERE Holiday_Flag='1'
    GROUP BY Date
    ) AS temptable 
GROUP BY Holiday --Summarizing and reordering data 
ORDER BY Weekly_Sales DESC

Despite Thanksgiving dominating the upper echelons of highest individual store profit, it seems like people spend the most on the Super Bowl! This could be caused by the cultural significance of Thanksgiving, where it “symbolizes intercultural peace, America’s opportunity for newcomers, and the sanctity of home and family”.1 However, I am more inclined to believe that Thanksgiving is typically used as an opportunity to invite all your friends and family and spend the entire day cooking – that means food costs can balloon quickly!

Stores 12, 28, and 38 have the highest unemployment rate

Show SQL code
-- highest unemployment rate 
SELECT TOP 6 Store, avg(CAST(Unemployment AS decimal)) AS Unemployment, avg(CAST(Weekly_Sales AS decimal)) AS Weekly_Sales
FROM WalmartSalesClean
GROUP BY Store
ORDER BY Unemployment desc, Weekly_Sales desc -- need to use weekly sales as a parameter as stores may have the same unemployment rate
Table 5: Highest Unemployment
Store Unemployment Weekly_Sales
12 13.116483 1009001.6
28 13.116483 1323522.2
38 13.116483 385731.7
34 9.934804 966781.6
43 9.934804 633324.7
29 9.806385 539451.4
Show SQL code
-- lowest unemployment rate
SELECT TOP 6 Store, avg(CAST(Unemployment AS decimal)) AS Unemployment, avg(CAST(Weekly_Sales AS decimal)) AS Weekly_Sales
FROM WalmartSalesClean
GROUP BY Store
ORDER BY Unemployment, Weekly_Sales desc
Table 6: Lowest Unemployment
Store Unemployment Weekly_Sales
23 4.796014 1389864.5
40 4.796014 964128.0
4 5.964692 2094713.0
8 6.091846 908749.5
9 6.099881 543980.6
5 6.295406 318011.8

Interestingly, there’s not a strong correlation between high unemployment and low weekly sales. I’d expect that places with higher unemployment meant that consumers had less disposable income to spend at Walmart. But, Walmart is known for having super cheap products and consumers could’ve primarily bought inelastic goods and other necessities.

It could also be that Walmart’s penetration pricing worked too well. Walmart is notorious for significantly impacting the local economy of the neighborhood, positively and negatively. On one hand, low prices means that consumers can afford more things in a one-stop location, and stores near the Walmart get more business due to the influx of foot traffic. On the other, Walmart is known for hiring many workers and paying minimum wage, as well as displacing small businesses due to their low prices, and subsequently, low profit margins. Only large corporations could offer these low margins as they have the financial resources to temporarily suffer short-term losses in hopes of long-term gains. Local businesses simply can’t afford to compete.

Evidently, the positive and negative effects differ depending on the neighborhood that Walmart enters, with this data being a good example of the impacts that Walmart can have.

It should also be noted that this data comes from 2010 - 2012 – aftermath of the Great Recession. Pre-recession, unemployment was at 4.7% in America. However, between 2010 - 2012, unemployment was at a high of 9.8% in January of 2009 and decreased until reaching a low of 7.7% in November 2012.2

No correlation between CPI and average weekly sales

The Consumer Price Index (CPI) tracks the weighted average of prices of a metaphorical basket of consumer goods. The goods within this basket are specially selected items that represent the goods and services that a typical US consumer would consume. By tracking the prices of this basket, consumers can understand inflation – the increases of prices resulting in a lack of purchasing power.

As an example, the 2023 CPI basket contained the following weighted components:

Category Percentage
Food 16.69
Shelter 29.15
Household operations, furnishings and equipment 13.01
Clothing and footwear 4.55
Transportation 16.9
Health and personal care 5.23
Recreation, educaiton and reading 10.27
Alcoholic beverages, tobacco products, and recreational cannabis 4.2
Total 100

We can also see the seasonally adjusted Canadian CPI3 since 2022.

Date CPI
2024/04 160.2
2024/01 159.3
2023/09 158.6
2023/05 156.2
2023/01 154.9
2022/09 152.8
2022/05 151.2
2022/01 146.3

There is a clear relationship of the CPI increasing as time goes on – an indicator of inflation.

However, we can compare the change in prices in the same time period:

Date CPI Fuel Prices (¢/Litre)
2024/04 160.2 169.76
2024/01 159.3 145.90
2023/09 158.6 162.45
2023/05 156.2 160.62
2023/01 154.9 153.48
2022/09 152.8 154.09
2022/05 151.2 183.99
2022/01 146.3 153.88

During this time, the average prices of regular unleaded gasoline in Canada do not follow the same pattern of increasing as time goes on.

This is because of the price elasticity of demand for fuel. Price elasticity is the percentage change in the quantity demanded of a good or service divided by the percentage change in price and shows how sensitive an item’s demand is to changes in price. For example, a demand elasticity of -1 would mean that for every 1% increase in price, the demand of a good would fall by 1%. An elasticity of 0 would mean that the demand does not change, even if the price changes.

Fuel is an inelastic good, meaning that the change in demand is quite small, relative to the change in price. This is because fuel is a difficult product to substitute – gas is most likely the only option you have to fuel your car– and is necessary for daily transportation.

Although fuel has always been comparatively inelastic good, recent research shows that fuel is more price elastic than we thought. Previously, a widely cited study by Hughes et. al. in 2008 claimed that the price elasticity for gas was between -0.03 and -0.08, meaning that demand barely changes when prices increase. However, in 2017, Coglianese et. al. found that the price elasticity of gasoline was -0.37, with their findings being corroborated by two other studies.

The errors in previous studies are likely caused by flawed estimation methods and/or questionable data. However, larger societal shifts may also play a part, where major car companies are pushing more fuel-efficient or electric vehicles and more consumers are using public transit as cities become more urbanized and transit infrastructure improves.4

Hence, one may conclude that an increase in CPI and fuel prices could result in more Walmart sales. With inflation reducing consumer purchasing power, consumers tend to spend less as their necessities have increased in price. Subsequently, they would be likely to go to Walmart – a store known for having low prices – to shop, attempting to keep their spending low, resulting in increased sales for Walmart. A similar effect could occur with the rise of fuel prices. Since fuel has inelastic demand, consumers would need to spend more money on fuel, resulting in less money being spent on other necessities. Hence, consumers would likely opt for cheaper products and shop at Walmart compared to more expensive stores.

However, in regard to this data set, the following relationships are found.

This data set does not contain CPI values between ~143 to ~ 180. It is likely because the CPI of stores were never in this range, however, the possibility of having missing data should be considered.

CPI also seems to be separated into 4 main clusters:

Although there doesn’t seem to be a correlation between CPI and weekly sales, it seems like stores with the same CPI tend to perform similarly.

No correlation between fuel price and average weekly sales

There is also no correlation between fuel price and total sales. However, this graph does have a strange divide, where stores either make ~0.5 million or ~0.7 million and above. The cause of this discrepancy is unknown, as it happens a various fuel price points.

It’s clear that the trends do not follow the hypothesized positive relationship between these variables and weekly sales. The most probable answer to this is discrepancy is that the economic changes were not enough to shift consumer spending behavior. For example, consumers may not switch to a different store because it’s more convenient for them to go (or not go) to Walmart. Furthermore, economics assumes that all consumers are rational as given a large enough sample, the macro trends of consumer spending will gravitate towards rational behavior. However, the sample within this data set may be too small to observe rational trends. A further extension could be diving into behavioral economics and how it affects this data set.

No correlation between temperature and average weekly sales

Surprisingly, the relationship between temperature and weekly sales in this study contradict recent research papers, as there seems there is no correlation between temperature and sales.

Show SQL code
SELECT Temperature, avg(Weekly_Sales) AS Weekly_Sales
FROM WalmartSalesClean
GROUP BY Temperature 
ORDER BY Weekly_Sales desc

Studies done by Muro et. al.5 show that natural sunlight has a positive correlation with spending by increasing positive affect. Furthemore, Zwebner and Goldenburg6 say that exposure to physical warmth result in emotional warmth, subsequently increasing product valuation. They also discovered that the ‘optimal’ temperature for increased spending was 78 degrees Fahrenheit. This misattribution of warmth has been called the ‘temperature-premium’ effect.

However, both studies test this against specific products, such as cakes, batteries, M&Ms, Gap T shirts. The discrepancy between research and results could be that the objects that were tested in the studies are not common consumer purchases and would not significantly affect weekly sales. Or, the temperature premium may not apply for all products. Furthermore, the studies always utilized artificial heating tools (thermostats or heating pads) within an indoors location. On the other hand, the Walmart data recorded the outdoors temperature, not the temperature within the store. Lastly, the store atmosphere, influenced by indoors lighting, could potentially play an even larger role in customer purchases than weather or temperature. Mitigating the effect of store atmospheres when conducting studies would be crucial.

There is lots of further research to be done within this topic. Further research could potentially be conducted in the following topics:

This dataset contains stores from 11 different countries

Using the information in the data set, it may be possible to make educated guesses regarding the geographic region of the stores.

In 2010, Walmart was open in the following countries:

Hence, the unemployment rate data for each store could be corroborated against country-wide unemployment data from the Organisation for Economic Co-operation and Development (OECD) and World Bank Group to determine which region the store could likely fall into.

According to past records:

Country Unemployment
US 9.610
Chile 8.500
Brazil 8.400
Canada 8.175
UK 7.870
Nicaragua 7.800
Argentina 7.700
Costa Rica 7.200
India 5.500
Mexico 5.380
El Salvador 4.900
China 4.500
Honduras 4.100
Guatemala 3.500

This can be graphed like so:

The plot highlights the different parts of the world each store may be located. It seems like the most data was obtained from Chile and India, while the least amount of data was obtained from Mexico, Argentina, and Nicaragua.

Sample Pearson correlation coefficient supports previous analysis

We can also use statistics to back up these claims by checking the correlation between weekly sales and other variables. This gives us insight into the relationship between each of the variables.

The sample Pearson correlation coefficient was used to determine whether there was a linear correlation between the two sets of data. The coefficient ranges from \(-1\) \(\le\) \(r_{X,Y}\) \(\le\) \(1\), where \(-1\) means a perfect negative linear relationship (as weekly sales go up, the other variable goes down) and \(1\) means a perfect positive linear relationship (as weekly sales go up, the other variable goes up.)

Subsequently:

Based on the above analysis, the following relationships are predicted:

The following formula will be used:

\(r_{xy}={\frac {n\sum x_{i}y_{i}-\sum x_{i}\sum y_{i}}{\sqrt{(n\sum x^2 - \sum x \sum x)(n\sum y^2 - \sum y \sum y)}}}\)

where \(x\) is Weekly_Sales, and \(y\) the variable we want to test the correlation of.

The sample Pearson correlation coefficient calculated is:

Show SQL code
-- calculating the Pearson coefficient for weekly sales and unemployment. 
-- Replacing the y value (in this case, unemployment) with the other variables 
-- would yield the coefficient for that specific variable 

WITH rdata AS (
SELECT CAST(Unemployment AS decimal) AS Unemployment, CAST(Weekly_Sales AS decimal) AS Weekly_Sales
FROM WalmartSalesClean
),

rawdata AS ( -- calculating expectation 
SELECT Unemployment AS x, Weekly_Sales AS y, Unemployment*Weekly_Sales AS xy, Unemployment*Unemployment AS xsquared, 
Weekly_Sales*Weekly_Sales AS ysquared   
FROM rdata
),

pdata AS ( -- reorganizing data 
SELECT SUM(x) AS sumx, SUM(y) AS sumy, SUM(xy) as sumxy, SUM(xsquared) as sumx2, SUM(ysquared) as sumy2, COUNT(x) as n
FROM rawdata
)

--- covariance(xy) / (std. dev. x) * (std. dev. y)
SELECT (n*sumxy - sumx * sumy) / (sqrt((n*sumx2 - sumx*sumx)*(n*sumy2 - sumy*sumy))) AS "Pearson's Correlation"
FROM pdata
Table 7: Calculated pearson correlation coefficient values
Variable Correlation Coefficient
Unemployment -0.1014370
CPI -0.0724960
Fuel Prices -0.0064690
Temperature -0.0637689

Point-Biserial correlation coefficient does not support previous analysis

For Holiday_Flag, we need to use a point-biserial correlation coefficient instead of the Pearson correlation coefficent. This is because Holiday_Flag is a dichotomous variable (values can only be 1 or 0 to symbolize yes/no) compared Weekly Sales, which is not a dichotomous variable (values can be any number).

Although you can use Pearson’s with dichotomous variables, the usefulness of the correlation would be debatable since it’s not meant to be utilized with dichotomous variables. Hence, it’s best to use a point-biserial, as it is equivalent to the Pearson correlation coefficient.7

We will be using the following formula:

\({r_{pb}={\frac {M_{1}-M_{0}}{s_{n}}}{\sqrt {\frac {n_{1}n_{0}}{n^{2}}}}}\)

where:

\(M_1\) = Mean weekly sales when the Holiday_Flag = 1
\(M_0\) = Mean weekly sales when the Holiday_Flag = 0
\(s_n\) = Standard deviation of weekly sales
\(n_1\) = Number of data points where Holiday_Flag = 1
\(n_2\) = Number of data points where Holiday_Flag = 0
\(n\) = Total number of data points in the sample

Show SQL code

--grabbing avg weekly sales for holiday / no holiday
WITH meanflag AS ( 
SELECT Holiday_Flag, avg(CAST(Weekly_Sales AS decimal)) AS Avg_Weekly_Sales
FROM WalmartSalesClean
GROUP BY Holiday_Flag
), 

-- grabbing number of holiday / no holiday days
countflag AS ( 
SELECT Holiday_Flag, count(Holiday_Flag) AS n_Holiday_Flag
FROM WalmartSalesClean
GROUP BY Holiday_Flag
),

-- combining it into one table
joinmeancount AS ( 
SELECT meanflag.Holiday_Flag, meanflag.Avg_Weekly_Sales, countflag.n_Holiday_Flag
FROM meanflag
INNER JOIN countflag
    ON countflag.Holiday_Flag = meanflag.Holiday_Flag
),

-- adding standard deviation and total count of weekly sales
joinstdn AS ( 
SELECT STDEV(CAST(Weekly_Sales AS decimal)) AS sn, count(Weekly_Sales) as n, 
(SELECT n_Holiday_Flag FROM joinmeancount WHERE Holiday_Flag = 1) AS n1, 
(SELECT n_Holiday_Flag FROM joinmeancount WHERE Holiday_Flag = 0) AS n0, 
(SELECT Avg_Weekly_Sales FROM joinmeancount WHERE Holiday_Flag = 1) AS m1,
(SELECT Avg_Weekly_Sales FROM joinmeancount WHERE Holiday_Flag = 0) AS m0
FROM WalmartSalesClean
)

-- calculating correlation, need to convert into floats for division
SELECT ((m1-m0)/sn) * SQRT((CAST(n1 * n0 AS FLOAT)) / (CAST(n * n AS FLOAT))) AS r_pb 
FROM joinstdn

which results in an \(r_{pb}\) value of ~ 0.037 – a slight positive correlation.

Table 8: Pearson and Point-Biserial Correlation Values
Variable Correlation Coefficient
Holiday 0.0368881
Unemploymment -0.1014370
CPI -0.0724960
Fuel Prices -0.0064690
Temperature -0.0637689

The correlation coefficient does not match with the data observed within the tables in charts, as there is a notable increase in sales due to holidays.


  1. https://www.britannica.com/topic/Thanksgiving-Day↩︎

  2. https://www.bls.gov/charts/employment-situation/civilian-unemployment-rate.htm↩︎

  3. This CPI score eliminates seasonal movements, such as events caused by climate and holidays.↩︎

  4. https://www150.statcan.gc.ca/n1/daily-quotidien/240220/dq240220d-eng.htm↩︎

  5. https://www.ualberta.ca/business/media-library/centres/sor/documents/murrayetal2010-theeffectofweatheronconsumerspending.pdf↩︎

  6. https://web2-bschool.nus.edu.sg/wp-content/uploads/media_rp/publications/zLb1d1490932501.pdf↩︎

  7. https://en.wikipedia.org/wiki/Point-biserial_correlation_coefficient↩︎