Created
January 27, 2023 03:08
-
-
Save mfwarren/fe6ea0c10d5e2752b0a5d5818ea4007e to your computer and use it in GitHub Desktop.
calculate a 60-day LTV out of the most recent 90 days of sales history
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from datetime import datetime, timedelta | |
import shopify | |
ACCESS_TOKEN = 'YOUR ADMIN TOKEN' | |
def shopify_orders(): | |
shop_url = "YOURSTORE.myshopify.com" | |
api_version = '2022-07' | |
order_rows=[] | |
with shopify.Session.temp(shop_url, api_version, ACCESS_TOKEN): | |
orders = shopify.Order.find(created_at_min=(datetime.now()-timedelta(days=90)).isoformat()) | |
for order in orders: | |
order_rows.append({ | |
'name': order.name, | |
'shopify_order_id': order.id, | |
'customer_id': order.customer.id, | |
'customer_created_at': datetime.fromisoformat(order.customer.created_at), | |
'created_at': datetime.fromisoformat(order.created_at), | |
'tags': order.tags, | |
'app_id': order.app_id, | |
'cancelled_at': datetime.fromisoformat(order.cancelled_at) if order.cancelled_at else None, | |
"currency": order.currency, | |
"current_total_discounts": order.current_total_discounts, | |
"fulfillment_status": order.fulfillment_status, | |
'subtotal_price': order.subtotal_price, | |
'total_discounts': order.total_discounts, | |
'total_line_items_price': order.total_line_items_price, | |
'total_price': order.total_price, | |
'total_tax': order.total_tax, | |
'updated_at': datetime.fromisoformat(order.updated_at)}) | |
return order_rows | |
def calc_ltv(orders): | |
first_orders = [order for order in orders if order['customer_created_at'].date() == order['created_at'].date() and order['created_at'].date() > (datetime.today()-timedelta(days=60)).date() and 'Wholesale' not in order['tags']] | |
customer_value=0 | |
for first_order in first_orders: | |
customer_value += sum([float(order['subtotal_price']) for order in orders if first_order['created_at'] <= order['created_at'] < (first_order['created_at'] + timedelta(days=60)) and order['customer_id'] == first_order['customer_id']]) | |
print(f'60-day LTV: ${customer_value/len(first_orders):.2f}') | |
if __name__=='__main__': | |
calc_ltv(shopify_orders) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment