Dynamic pricing and algorithmic marketing: the complete technical playbook
TL;DR
Difficulty: Advanced
Run pricing and advertising as one nightly loop. Read your own sales, stock and costs and competitors' public prices, propose a price per product from strategy, stock and elasticity, cap every move, and log the reason. Use the markup rule only where a real elasticity estimate is below minus one. Judge ads by profit on ad spend, not ROAS, and split budget by margin, conversion, stock and price position. Price products, never people: no protected characteristics, no data without consent. Show was prices only for real promotions, using the 30 day lowest price. Use public data only, never coordinate with rivals.
Most shops set a price once, set an ad budget separately, and adjust both by hand once a month. This playbook builds the alternative in a Ruby on Rails shop on Solidus: a nightly loop that prices each product from its cost, stock, elasticity and competitors' public prices, inside limits a person sets, and moves ad spend towards profit. It covers the economics with corrected worked examples for an invented Leeds cookware shop, the UK law on was prices, personal prices and algorithmic collusion, and the code.
Most shops set a price once and then advertise against it
Here is how pricing and advertising run in most online shops. Someone sets a price when the product goes live. Someone else sets an advertising budget. The campaigns run, a dashboard fills up, and once a month somebody adjusts a few numbers by hand. Price, stock, margin and ad spend are decided by different people at different times, and none of them can see the others.
The alternative is a loop. Every night the shop reads its own sales, stock and costs, and the public prices of the competitors it actually meets. It works out a price for each product inside limits a person has set, writes that price into the shop and the product feed, and moves the advertising budget towards the products that earn the most profit, not the most revenue. Then it measures what happened and does it again.
This article is the playbook for building that loop in a Ruby on Rails shop on Solidus: the economics, the formulas, the law that decides what the loop may do in the UK, and the code. It is a rewrite. The first version had a worked example whose numbers did not add up, a pricing formula that breaks for some products, a hook for charging individual customers different prices, and no word on the law. All four are fixed below, and I say where.
To keep the numbers concrete I use an invented shop. Kirkstall Cookware sells cast iron casseroles, knife sets and pans from a unit in Leeds, at kirkstallcookware.example. Nobody real, every number made up.
Why one price leaves money on the table
Different customers will pay different amounts for the same product. Economists call charging them different prices price discrimination, and they usually sort it into three degrees. First degree means charging each person exactly what they would pay at most. Second degree means offering versions, bundles or quantity breaks and letting each customer choose: buy two and save, the gift edition or the plain one. Third degree means charging different prices to groups you can see from the outside, such as students, trade customers or a different country.
The first version of this article said dynamic pricing "increasingly" approaches first degree by reading behavioural signals about each customer. I have taken that out of the engine. This playbook prices products, editions, channels and moments, never individual people. The legal reasons are further down, and there is a commercial one too: customers who find out they paid more than their neighbour for the same casserole do not come back.
Worked example: two groups of buyers, one casserole
Kirkstall's 24cm casserole costs £20 to buy in, pack and ship. Suppose there are two groups of buyers. Four hundred people would pay up to £50 (they are buying a present). Six hundred would pay up to £35 (they are buying for their own kitchen).
With one price for everyone, Kirkstall has to choose. At £50 only the gift buyers buy, so profit is , or £12,000. At £35 everybody buys, so profit is , or £15,000. At £40, a price that looks like a sensible compromise, only the gift buyers buy and profit falls to , or £8,000.
The old version of this example said the shop sold 1,000 casseroles at £40 and then, two lines later, that the £35 group would not buy at £40. Both cannot be true, so its "5% more profit" was wrong.
Now give the gift buyers their own edition: the same casserole in a printed box with a recipe card, at £50. The box and card cost £2, so each gift edition earns pounds. If the groups sort themselves cleanly, profit is , or £20,200. That is about 35% more than the best single price.
The words "if the groups sort themselves cleanly" carry the whole example. Some gift buyers will buy the plain casserole and wrap it themselves. Designing editions, bundles and timing so that the groups really do separate is the hard part of second degree pricing, and it is a product decision before it is an algorithm.
Elasticity is the number the engine needs
The engine cannot know what each person would pay. It can know, roughly, how sales of each product respond when the price moves. That is the price elasticity of demand, defined in the Foundations:
is the elasticity, is the percentage change in the quantity sold and is the percentage change in price. An elasticity of means a 10% price rise loses about 20% of unit sales. An elasticity of means the same rise loses only about 5%.
If the elasticity is roughly constant around the current price, there is a simple rule for the price that maximises profit, the markup rule:1
is the price, is the marginal cost of one more unit (purchase price plus packaging, payment fees and any delivery you subsidise, not an average that includes rent), is the elasticity and is the profit maximising price. The left side, , is the margin as a share of the price. The rule only holds where demand is elastic, which means . The full derivation, and how to estimate from your own order history with a regression, is in modelling demand and price elasticity with regression, and the Foundations entry on elasticity covers the definition.
Worked example: the markup rule on the casserole
With and , the rule gives , so £40. With , a much more price sensitive product, it gives , so £26.67.
Two warnings follow from the same formula, and the first version of this article missed both. With the rule says , so £60. Moving the estimate from to , well inside the error range of most real estimates, moves the "optimal" price by half. And with the rule gives , a negative price. That is not a bug in the arithmetic. It means demand at today's price is inelastic, a price rise would increase profit, and the rule cannot say by how much because the assumption behind it does not hold there. The old code fed every product through this formula with a default elasticity of when none was known. The new code below only uses the rule when there is a real estimate below , blends it with the current price instead of jumping to it, and caps every move.
Passive and active marketing, side by side
In the passive model, a change takes weeks to show up: you move something, wait for data, argue about what it means, and move something else. In the active model the shop runs the same loop every night with limits a person has set, and a person reviews the log rather than every price.
Nightly is deliberate. The old version ran every hour. Prices that move every hour are hard to explain to a customer, they get out of step with the price Google has crawled from your page, and, as the UK section below shows, they make every "was" price you ever show look suspicious.
Competitor prices: collect them politely, use them alone
You cannot price sensibly without knowing what the shops you actually compete with charge. A competitor monitor does four things: it fetches competitors' public product pages on a schedule, matches their products to yours (by barcode number, GTIN, where both sides publish it, otherwise by a mapping a person has checked), stores the history, and flags significant changes.
How you collect matters as much as what you collect. Public pages only, no logins, an honest user agent with a contact address, robots.txt respected, a polite rate, and if a site blocks you, you stop. The legal reasons, from the database right to the Ryanair cases, are in competitor price monitoring in the EU: what is actually legal, and the same conduct is the safe ground in the UK.
Once you have the data, each product gets a strategy. Undercut the lowest competitor by a fixed amount, for commodity products where you have a cost advantage. Match the market average, where price is not what you compete on. Hold a set premium, where brand, service or quality earn it. Or switch between them by stock: undercut when you are overstocked, hold a premium when stock is short, match otherwise. The strategies sit side by side in one catalogue. Kirkstall undercuts on a basic frying pan that every shop sells, matches on knife sets, and holds a premium on its own casserole colours.
Two rules apply to every strategy. The engine never goes below a floor of cost plus a minimum margin, whatever a competitor does. And competitor prices are one input among several, not a command. An engine that only ever follows the cheapest rival hands its pricing to that rival, and two engines that only follow each other can drift into exactly the pattern competition law worries about, which is covered below.
Margin aware advertising: spend where the profit is
Most ad accounts are judged by return on ad spend (ROAS): revenue from the ads divided by what the ads cost. Revenue is the wrong thing to divide.
Take two Kirkstall products, both sold at £100. The knife block costs £80, so its gross margin is 20%. The casserole set costs £40, so its margin is 60%. If both convert at the same rate for the same cost per click, their ROAS is identical, yet the casserole set earns three times the gross profit per sale. The measure that sees the difference is profit on ad spend (POAS):
is the revenue the ads brought in, is the cost of the goods sold in those orders, is the ad spend and is the gross margin as a fraction of revenue, so . This is a ratio of two flows over the same period, explained under ratios and rates in the Foundations. A POAS above 1 means the gross profit from the ads covers their cost, before any other variable costs.
Worked through: a campaign with a ROAS of 4 on 20% margin products has . It loses 20 pence of gross profit on every pound spent, while its dashboard shows a healthy 4. A campaign with a ROAS of 2 on 60% margin products has , and it is the one making money.
Splitting a budget by score
The simplest margin aware allocation gives each product a score and splits the budget in proportion:
is product 's share of the budget, its score and the sum of all scores. is the gross margin as a fraction, the conversion rate from ad clicks over the last 30 days, a stock factor and a competitive factor. Each share is a simple proportion, as in percentages in the Foundations. The stock factor I start with is 1.5 when there are more than eight weeks of stock, 1.3 for four to eight weeks, 1.0 for two to four, 0.8 for one to two and 0.5 under one week. The competitive factor is 1.2 when you are at or below the cheapest competitor, 1.0 near the market average and 0.7 when you are the most expensive.
Worked example: £3,000 across three products
Kirkstall spends £3,000 a month on Google Shopping across three products. The casserole has a margin of 50%, converts at 3.0%, has six weeks of stock (factor 1.3) and sits at the market average (1.0), so its score is . The knife set has a margin of 35%, converts at 2.0%, has normal stock (1.0) and has the lowest price in the market (1.2), so . The frying pan has a margin of 20%, converts at 4.5%, has under a week of stock (0.5) and is the most expensive (0.7), so .
The scores add up to . The casserole gets of the budget, £1,884. The knife set gets , £812. The pan gets , £304. The pan converts best of the three, and a revenue optimiser would feed it. Here it gets the least, because it earns little per sale, it is about to sell out and a competitor undercuts it.
A score is a starting point, not an optimum. Ad spend has diminishing returns: the first £300 on the pan buys the most eager searchers, the next £300 buys less eager ones. The split that maximises profit is the one where the last pound on every product earns the same extra profit, which is the difference between marginal and average returns. A score cannot see that. So I treat the score as the first allocation, move budget in small steps, and keep a product's share only where the extra spend kept earning.
The law decides what the engine may do
Consumer law does not ban dynamic pricing. The Competition and Markets Authority (CMA) says so plainly, and adds that what the law cares about is how a business implements and communicates it.2 Since 6 April 2025 the rules on unfair commercial practices sit in Part 4 of the Digital Markets, Competition and Consumers Act 2024 (DMCCA), enforced directly by the CMA.3 I am not a lawyer and this is not legal advice. This is the map I build to, and a shop with an unusual model should take it to a solicitor.
Telling customers that prices move
The CMA's tips for businesses that use dynamic pricing are short: be clear that prices can change, explain what drives the changes where that helps, say so prominently rather than in small print, do not push people into snap decisions, and do not change the price while a customer is paying.4 A misleading action under the DMCCA includes an overall presentation likely to deceive the average consumer, even when each fact on the page is true,5 and the list of practices banned outright includes falsely claiming that an offer is available only for a very limited time to rush a decision.6
For the engine that means: a plain line on the product page or the delivery and pricing page that prices change with demand and stock; no countdown next to a price that is not about to change; and a basket freeze, so a variant sitting in an order that has reached payment is not repriced until the order completes or is abandoned.
"Was" prices and the 30 day rule
The UK did not adopt the EU's rule that a price reduction must show the lowest price of the previous 30 days. The UK test is whether the comparison misleads. The CMA's examples of misleading price reduction claims include a "was" price at which few items ever sold, a short price hike just before a sale, an old price from months ago, and a price that has been flip flopping between two levels, where the higher price "is no more the usual selling price than the lower promotional price".7 The CMA expects you to be able to show that a reference price was a genuine and realistic selling price.7 Those examples were written under the old Consumer Protection from Unfair Trading Regulations, which the DMCCA replaced, but the test they illustrate is the same.
A dynamic pricing engine is a flip flopping machine by design. My rule therefore is: prices the engine moves are shown as plain prices, never as reductions. A strike through price appears only for a deliberate promotion, and the reference price shown is the lowest price the shop charged in the 30 days before the promotion started, taken from the price log. That is the EU standard, and using it in the UK too makes the claim easy to defend.
If you sell to customers in the EU from the UK, that standard is the law there, not a house rule. The Omnibus Directive inserted Article 6a into the Price Indication Directive: any announcement of a price reduction must show the prior price, the lowest price the trader applied in at least the 30 days before the reduction.8 The Court of Justice ruled in 2024 that a percentage discount, or a promotional claim that a price is a bargain, must be calculated from that prior price.9
One more UK change landed this year. Since 6 April 2026 the Price Marking Order 2004 says that where a trader sells a product at more than one selling price, for example a member price and a standard price, the price indication must set out each price and, prominently and close to the product, any conditions for getting it.10 If your engine sets separate prices for a loyalty tier, both prices and the conditions belong on the page.
Personal prices: the line I do not cross
Personalised pricing means showing different people different prices for the same product based on what is known about them. The CMA's work on algorithms describes how it can be opaque to the consumer, and treats discrimination on protected characteristics as a harmful form of it.11 In the EU a shop must tell the customer before the contract when a price was personalised on the basis of automated decision making.8 That duty came after the UK left, and UK consumer law has no rule worded like it, but hiding a personalised price is the kind of omission the DMCCA's misleading practices rules are about, and data protection law applies anyway. Under the UK GDPR, a significant decision based solely on automated processing needs safeguards, including information about the decision, human intervention and a way to contest it.12
Three rules follow, and they are not negotiable in anything I build. First, the engine never takes a protected characteristic as an input, nor a stand in for one: under the Equality Act 2010 a business must not discriminate in the terms on which it provides goods or services, and an apparently neutral rule that hits a protected group harder can be indirect discrimination.13 Postcode, first name or device type can all act as a proxy. Openly advertised concessions, such as a student discount, are a deliberate business decision with their own legal check, not something an algorithm should discover. Second, the engine never uses personal data that was collected without a lawful basis, and never uses browsing data from cookies or similar technologies that needed consent the visitor did not give.14 Third, the engine prices products, editions, channels and moments, so neither question arises. The price_for_user hook from the first version of this code is gone.
Algorithmic collusion: react to the market, never coordinate with it
Reacting on your own to the prices your rivals publish is the competition the law wants. Agreeing prices with a rival, or sharing confidential pricing information, is prohibited by Chapter I of the Competition Act 1998, which names agreements and concerted practices that directly or indirectly fix selling prices.15 Software does not change that. In 2016 the CMA fined an online seller over £160,000 for an agreement with a competitor not to undercut each other on Amazon's UK site, carried out through automated repricing software.16
The CMA's paper on algorithms adds two subtler routes: hub and spoke, where competitors use the same pricing software or intermediary and it becomes a channel for information, and autonomous tacit collusion, where pricing algorithms learn to keep prices high without anyone communicating.11 In a simulated market, pricing agents based on Q learning did learn to sustain prices above the competitive level and to punish a rival who cut.17 That was a laboratory result, not a finding against a real shop, but it is the reason for three design rules. The engine reads only the shop's own data and competitors' public prices. If you buy a repricing service, ask in writing whether its recommendations use any other client's non public data. And every price in the log carries a reason a person can read in terms of the shop's own costs, stock and strategy, never in terms of what a competitor is expected to do next.
The Solidus implementation
Now the code. It assumes a Solidus store on a recent Rails, a crawler that already follows the rules above and stores what it finds, and API access to Google Ads and Meta. It is a working skeleton, not a drop in gem: the class names are mine, and you will adapt the strategies, factors and limits to your catalogue.
Tables: competitor prices and a price log
Two tables. One holds the latest public price per competitor and variant. The other is the price log: every price the shop has charged, with the reason and the inputs. The log is your evidence for any reference price, your training data for the next elasticity estimate, and your answer when a customer or a regulator asks why a price moved.
# db/migrate/20260806000001_create_pricing_tables.rb
class CreatePricingTables < ActiveRecord::Migration[7.2]
def change
create_table :competitor_prices do |t|
t.references :variant, null: false, foreign_key: { to_table: :spree_variants }
t.string :competitor_domain, null: false
t.decimal :price, precision: 10, scale: 2, null: false
t.decimal :shipping_cost, precision: 10, scale: 2, null: false, default: 0
t.boolean :in_stock, null: false, default: true
t.datetime :seen_at, null: false
t.timestamps
end
add_index :competitor_prices, [:variant_id, :competitor_domain], unique: true
create_table :price_changes do |t|
t.references :variant, null: false, foreign_key: { to_table: :spree_variants }
t.string :currency, null: false
t.decimal :old_amount, precision: 10, scale: 2
t.decimal :new_amount, precision: 10, scale: 2, null: false
t.string :reason, null: false
t.jsonb :inputs, null: false, default: {}
t.timestamps
end
add_index :price_changes, [:variant_id, :currency, :created_at]
end
end
# app/models/competitor_price.rb
class CompetitorPrice < ApplicationRecord
belongs_to :variant, class_name: "Spree::Variant"
scope :fresh, -> { where(seen_at: 36.hours.ago..) }
scope :in_stock, -> { where(in_stock: true) }
def total_price
price + shipping_cost
end
def self.for_variant(variant)
fresh.in_stock.where(variant: variant)
end
def self.lowest_total(variant)
for_variant(variant).map(&:total_price).min
end
def self.average_total(variant)
totals = for_variant(variant).map(&:total_price)
totals.empty? ? nil : totals.sum / totals.size
end
end
# app/models/price_change.rb
class PriceChange < ApplicationRecord
belongs_to :variant, class_name: "Spree::Variant"
# Lowest price charged in the `days` before `at`, including the price that was
# already in force when the window opened. In the EU this is the prior price a
# price reduction must show. In the UK it is the house rule for any reference price.
def self.lowest_before(variant, at:, currency: "GBP", days: 30)
scope = where(variant: variant, currency: currency)
window_start = at - days.days
in_window = scope.where(created_at: window_start..at).minimum(:new_amount)
in_force = scope.where(created_at: ...window_start).order(created_at: :desc).pick(:new_amount)
[in_window, in_force].compact.min
end
end
Syncing competitor prices
The sync job reads from your crawler's own store. Matching is the step that goes wrong most often, so it relies on a mapping table that a person has confirmed, filled first by GTIN where both shops publish one. The first version looked competitor barcodes up in the Solidus sku column, which only works if your SKUs happen to be barcodes.
# app/jobs/competitor_price_sync_job.rb
class CompetitorPriceSyncJob < ApplicationJob
queue_as :default
def perform
CrawlerStore.observations_since(26.hours.ago).each do |obs|
mapping = CompetitorProductMapping.confirmed.find_by(
competitor_domain: obs.domain, competitor_url: obs.url
)
next unless mapping
CompetitorPrice.upsert(
{
variant_id: mapping.variant_id,
competitor_domain: obs.domain,
price: obs.price,
shipping_cost: obs.shipping_cost || 0,
in_stock: obs.in_stock,
seen_at: obs.fetched_at,
created_at: Time.current,
updated_at: Time.current
},
unique_by: [:variant_id, :competitor_domain]
)
end
end
end
The pricing engine
The engine proposes, it does not decide alone. Its inputs are the variant's cost, stock, the competitors' public prices and the product's elasticity estimate. Nothing about the customer goes in.
# app/services/pricing_engine.rb
class PricingEngine
Proposal = Struct.new(:amount, :reason, :inputs, :needs_review, keyword_init: true)
MAX_STEP = 0.05 # never move more than 5% in one run
ELASTICITY_WEIGHT = 0.3 # how far to lean towards the markup rule each run
def initialize(variant, currency: "GBP")
@variant = variant
@product = variant.product
@currency = currency
@config = PricingConfig.for(@product)
end
def propose
return nil if in_checkout?
cost = @variant.cost_price
return nil unless cost && current_price
target = strategy_price
target = lean_towards_markup_rule(target, cost)
target *= stock_adjustment
capped = target.clamp(current_price * (1 - MAX_STEP), current_price * (1 + MAX_STEP))
final = capped.clamp(floor(cost), ceiling).round(2)
Proposal.new(
amount: final,
reason: "#{@config.strategy}, #{weeks_of_stock.round(1)} weeks of stock",
inputs: inputs(cost),
needs_review: final == floor(cost) || final == ceiling
)
end
private
def current_price
@current_price ||= @variant.price_for_options(pricing_options)&.amount
end
def pricing_options
Spree::Config.pricing_options_class.new(currency: @currency)
end
def strategy_price
lowest = CompetitorPrice.lowest_total(@variant)
average = CompetitorPrice.average_total(@variant)
case effective_strategy
when :undercut then lowest ? lowest - @config.undercut_amount : current_price
when :match then average || current_price
when :premium then (average || current_price) * (1 + @config.premium_share)
end
end
def effective_strategy
return @config.strategy.to_sym unless @config.strategy == "by_stock"
return :undercut if weeks_of_stock > 8
return :premium if weeks_of_stock < 1
:match
end
# The markup rule P* = C * e / (1 + e) only holds where demand is elastic (e < -1),
# and only for a real estimate. Without one, the strategy price stands.
def lean_towards_markup_rule(price, cost)
e = @product.price_elasticity
return price unless e && e < -1.0
optimal = cost * e / (1 + e)
price * (1 - ELASTICITY_WEIGHT) + optimal * ELASTICITY_WEIGHT
end
def stock_adjustment
case weeks_of_stock
when ...1 then 1.03
when 1...4 then 1.0
when 4...8 then 0.98
else 0.95
end
end
def weeks_of_stock
@weeks_of_stock ||= begin
weekly = SalesVelocity.weekly_average(@variant, weeks: 8)
weekly.positive? ? @variant.total_on_hand.to_f / weekly : 99.0
end
end
def floor(cost)
[cost / (1 - @config.minimum_margin), @config.price_floor || 0].max
end
def ceiling
@config.price_ceiling || current_price * 1.5
end
# A variant in an order that has reached payment keeps its price until the
# order completes or is abandoned.
def in_checkout?
Spree::LineItem.joins(:order)
.where(variant_id: @variant.id)
.where(spree_orders: { state: %w[payment confirm], completed_at: nil })
.where("spree_orders.updated_at > ?", 2.hours.ago)
.exists?
end
def inputs(cost)
{
cost: cost.to_f,
current_price: current_price.to_f,
competitor_lowest: CompetitorPrice.lowest_total(@variant)&.to_f,
competitor_average: CompetitorPrice.average_total(@variant)&.to_f,
elasticity: @product.price_elasticity,
weeks_of_stock: weeks_of_stock.round(2),
strategy: effective_strategy
}
end
end
Writing prices into Solidus
Solidus stores prices as Spree::Price records per currency and, optionally, per country, and a configurable price selector picks the one that applies. The default selector chooses by currency and country.18 The engine therefore writes a normal price record, and the storefront, the cart and the feeds read it the usual way. You can swap the selector class through Spree::Config.variant_price_selector_class when you need prices per country or channel. I do not use that hook to price per customer, for the reasons above.
# app/services/price_writer.rb
class PriceWriter
def apply!(variant, proposal, currency: "GBP")
return if proposal.nil? || proposal.needs_review
price = variant.prices.find_or_initialize_by(currency: currency, country_iso: nil)
old_amount = price.amount
return if old_amount && (proposal.amount - old_amount).abs < 0.01
Spree::Price.transaction do
price.update!(amount: proposal.amount)
PriceChange.create!(
variant: variant, currency: currency,
old_amount: old_amount, new_amount: proposal.amount,
reason: proposal.reason, inputs: proposal.inputs
)
end
end
end
Proposals that hit the floor or the ceiling are not applied. They go to a short daily list for a person, because an engine pinned against a limit is usually telling you that a cost, a competitor match or an elasticity estimate is wrong.
The budget allocator
The allocator implements the score from the worked example. The first version filtered on a total_on_hand column and averaged price in SQL, but Solidus keeps stock in stock items and prices in their own table, so neither column exists on the variants table. This version computes both in Ruby.
# app/services/budget_allocator.rb
class BudgetAllocator
def initialize(monthly_budget:, platform:)
@monthly_budget = monthly_budget
@platform = platform
end
def allocation
scores = eligible_products.to_h { |product| [product, score(product)] }
total = scores.values.sum
return {} if total.zero?
scores.transform_values { |s| (@monthly_budget * s / total).round(2) }
end
private
def eligible_products
Spree::Product.available.includes(:variants).select do |product|
product.variants.any? { |v| v.cost_price.present? && v.total_on_hand.positive? }
end
end
def score(product)
margin(product) *
(ConversionMetrics.rate_for(product, days: 30) || 0.0) *
stock_factor(product) *
competitive_factor(product)
end
def margin(product)
options = Spree::Config.default_pricing_options
rates = product.variants.filter_map do |v|
price = v.price_for_options(options)&.amount
next unless price&.positive? && v.cost_price
(price - v.cost_price) / price
end
rates.empty? ? 0.0 : rates.sum / rates.size
end
def stock_factor(product)
weekly = SalesVelocity.product_weekly_average(product, weeks: 8)
weeks = weekly.positive? ? product.variants.sum(&:total_on_hand).to_f / weekly : 99.0
case weeks
when ...1 then 0.5
when 1...2 then 0.8
when 2...4 then 1.0
when 4...8 then 1.3
else 1.5
end
end
def competitive_factor(product)
options = Spree::Config.default_pricing_options
positions = product.variants.filter_map do |v|
lowest = CompetitorPrice.lowest_total(v)
highest = CompetitorPrice.for_variant(v).map(&:total_price).max
price = v.price_for_options(options)&.amount
next unless lowest && price
if price <= lowest then 1.2
elsif price >= highest then 0.7
else 1.0
end
end
positions.empty? ? 1.0 : positions.sum / positions.size
end
end
Sending budgets and prices to the platforms
In the Google Ads API a campaign budget is set in micros, a millionth of the account currency, and Google caps the effective monthly spend at 30.4 times the daily amount.19 So a monthly allocation becomes a daily budget by dividing by 30.4, not 30: the casserole's £1,884 becomes about £61.97 a day.
# app/services/google_ads_budgets.rb
class GoogleAdsBudgets
def initialize(client: GoogleAdsClientFactory.build,
customer_id: Rails.application.credentials.google_ads[:customer_id])
@client = client
@customer_id = customer_id
end
def set_daily!(budget_resource_name:, monthly_amount:)
daily = monthly_amount / 30.4
operation = @client.operation.update_resource.campaign_budget(budget_resource_name) do |b|
b.amount_micros = (daily * 1_000_000).round
end
@client.service.campaign_budget.mutate_campaign_budgets(
customer_id: @customer_id, operations: [operation]
)
end
end
Meta sets budgets on the ad set through its Marketing API, with daily_budget in the account currency's smallest unit.20 Keep the Graph API version in configuration rather than in code: the first version hard coded v18.0, which is long out of date.
# app/services/meta_budgets.rb
class MetaBudgets
def initialize
creds = Rails.application.credentials.meta_ads
@token = creds[:access_token]
@base = "https://graph.facebook.com/#{creds[:graph_version]}"
end
def set_daily!(adset_id:, monthly_amount:)
minor_units = (monthly_amount / 30.4 * 100).round
response = Faraday.post("#{@base}/#{adset_id}", daily_budget: minor_units, access_token: @token)
raise "Meta budget update failed: #{response.body}" unless response.success?
end
end
Prices in the product feeds must follow the shop. Google crawls your landing pages and compares the price there with the price in your product data, and a mismatch can get products disapproved.21 Google sunset the Content API for Shopping on 18 August 2026 and requests now fail progressively, so feed updates go through the Merchant API.22 I keep that behind a small MerchantFeed wrapper, built from Google's migration guide, so the rest of the code does not care which API version is current.
The nightly job
# app/jobs/nightly_pricing_job.rb
class NightlyPricingJob < ApplicationJob
queue_as :default
def perform
return unless PricingSwitch.on? # one switch turns the whole loop off
CompetitorPriceSyncJob.perform_now
writer = PriceWriter.new
Spree::Variant.joins(:product)
.where(spree_products: { dynamic_pricing: true })
.where.not(cost_price: nil)
.find_each do |variant|
writer.apply!(variant, PricingEngine.new(variant).propose)
end
MerchantFeed.push_changed_prices(since: 1.hour.ago)
MetaCatalogue.push_changed_prices(since: 1.hour.ago)
google = BudgetAllocator.new(monthly_budget: AdBudget.monthly(:google), platform: :google)
google.allocation.each do |product, amount|
mapping = CampaignMapping.find_by(product: product, platform: "google")
next unless mapping
GoogleAdsBudgets.new.set_daily!(budget_resource_name: mapping.budget_resource_name, monthly_amount: amount)
end
end
end
# config/recurring.yml (Solid Queue), or the equivalent in sidekiq-cron
production:
nightly_pricing:
class: NightlyPricingJob
schedule: every day at 3am
Measuring whether it works
Measure the loop by profit, not by activity. Five numbers, weekly, against the weeks before the loop went live and, where you can, against a control group of products the loop does not touch.
Gross margin per order, which should rise if prices move towards the markup rule on elastic products. Gross profit per session, which combines price and conversion into the one number that matters. POAS per campaign, which should rise as budget moves towards profit. Price changes per product per week, where zero means the loop is not doing anything and many means it is chasing noise. And the review list: how many proposals hit a limit, and why.
The control group is the part people skip. Prices are rarely set at random, so a rise in margin after launch could be the season, a competitor going out of stock or a new product. Leaving a matched set of products on fixed prices for six to eight weeks is what tells you the loop earned the difference. The test design is in the elasticity article, and a simpler first step, with rules before models, is in dynamic pricing with AI.
What changes when marketing owns the levers
Marketing is usually handed a product, a price and a budget and asked to make the most of them. Price belongs to someone else, stock to operations and margin to finance. That is how a team can run excellent campaigns that sell, at a loss, a product nobody would have advertised if they had seen its margin.
The loop above puts price, stock, margin and ad spend into one place, with limits a person sets and a log a person reads. It is not autopilot. It is a set of decisions you would make anyway, made every night with the numbers in front of you, inside the law, and written down.
If you run a Solidus or Rails shop and want this built, I start with a free workshop and the first two weeks of work are on me. Bespoke Solidus code I write for your shop becomes yours on full payment. The elasticity estimates and pricing models are data science work: your raw data stays yours, and the terms for code and models are in the analytics and data science terms. Book the workshop and bring a year of orders.