Metadata-Version: 2.4
Name: faker_clickstream
Version: 0.2.0
Summary: Clickstream Faker Provider for Python.
Home-page: https://github.com/cnatsis/faker-clickstream
Author: Christos Natsis
Author-email: christos_na@hotmail.com
License: Apache License, Version 2.0
Project-URL: Issues Tracker, https://github.com/cnatsis/faker-clickstream/issues
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Operating System :: OS Independent
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: Utilities
Requires-Python: >=3.12
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: Faker
Dynamic: author
Dynamic: author-email
Dynamic: classifier
Dynamic: description
Dynamic: description-content-type
Dynamic: home-page
Dynamic: license
Dynamic: license-file
Dynamic: project-url
Dynamic: requires-dist
Dynamic: requires-python
Dynamic: summary

# Clickstream Faker Provider for Python

- [Clickstream Faker Provider for Python](#clickstream-faker-provider-for-python)
  * [Purpose](#purpose)
  * [Installation](#installation)
  * [Usage](#usage)
    + [One session](#one-session)
    + [Event streams](#event-streams)
    + [Reproducible output](#reproducible-output)
    + [Profiles: tuning behaviour](#profiles-tuning-behaviour)
    + [Time formats](#time-formats)
  * [Features](#features)
  * [Contributing](#contributing)

## Purpose

This is a custom `Faker` provider for Python that generates clickstream session data, one session at a time or as a
continuous, time-ordered event stream. Data generated from this provider
represent user clickstream sessions on an online e-commerce site that sells mobile phones.

## Installation

The Clickstream Faker Provider for Python is available to install from PyPi using `pip`. It requires Python 3.12 or newer (3.13 recommended).

```bash
pip install faker_clickstream
```

## Usage

```python
from faker import Faker
from faker_clickstream import ClickstreamProvider

fake = Faker()
fake.add_provider(ClickstreamProvider)

fake.session_clickstream()                          # one session (a list of events)
fake.session_clickstream(rand_session_max_size=50)  # at most 50 events

for event in fake.clickstream_events(n_sessions=1000):  # many overlapping sessions, in time order
    ...
```

### One session

`session_clickstream()` returns the events of one session, with at most `rand_session_max_size` events (25 by
default). Most sessions are much shorter; see [Features](#features). Example:

```json
[
  {
    "ip": "216.55.215.13",
    "user_id": 142983,
    "user_agent": "Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Mobile Safari/537.36",
    "session_id": "69183a18ab4e9ae5b6f1947f376e2620991833ebacdf3af3ac874d62d1df9155",
    "event_time": "2025-03-28T20:05:00.000000+00:00",
    "event_name": "Search",
    "channel": "Referral",
    "metadata": {
      "query": "Redmi 5 Plus"
    },
    "event_id": "7222c1d9-e3ab-4a7d-87e3-fbf360590589",
    "visitor_id": "73374ae0-759d-4578-b3fb-08f34b48c38b"
  },
  {
    "ip": "216.55.215.13",
    "user_id": 142983,
    "user_agent": "Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Mobile Safari/537.36",
    "session_id": "69183a18ab4e9ae5b6f1947f376e2620991833ebacdf3af3ac874d62d1df9155",
    "event_time": "2025-03-28T20:05:27.006264+00:00",
    "event_name": "Search",
    "channel": "Referral",
    "metadata": {
      "query": "lg g7 thinq"
    },
    "event_id": "1efb5a77-d599-4627-84e5-aecac0936540",
    "visitor_id": "73374ae0-759d-4578-b3fb-08f34b48c38b"
  },
  {
    "ip": "216.55.215.13",
    "user_id": 142983,
    "user_agent": "Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Mobile Safari/537.36",
    "session_id": "69183a18ab4e9ae5b6f1947f376e2620991833ebacdf3af3ac874d62d1df9155",
    "event_time": "2025-03-28T20:06:03.969560+00:00",
    "event_name": "AddToCart",
    "channel": "Referral",
    "metadata": {
      "product_id": 370,
      "quantity": 1
    },
    "event_id": "ccbb3669-997c-4f60-ba9b-767f894ddf59",
    "visitor_id": "73374ae0-759d-4578-b3fb-08f34b48c38b"
  }
]
```

| Field | Meaning |
|---|---|
| `event_id` | Unique id of the event (UUID), handy for de-duplication |
| `session_id` | Same for all events of a session |
| `visitor_id` | Stable id of the browser (cookie), shared by a returning visitor's sessions |
| `user_id` | `0` until the visitor logs in for the first time, then their user id |
| `event_time` | ISO 8601 in UTC by default; see [Time formats](#time-formats) |
| `event_name` | One of the [events](#events) |
| `ip`, `user_agent`, `channel` | Network, browser and traffic source of the session |
| `metadata` | Event-specific details, e.g. `query`, `product_id`, `quantity`, `order_id` |

### Event streams

`clickstream_events()` yields events from many sessions that overlap in time, merged in event-time order, the way a
clickstream pipeline receives them. Sessions arrive at `sessions_per_hour` on average (600 by default), following a
daily cycle with quiet nights and busy evenings. About 40% of sessions come from returning visitors, who keep their
`visitor_id`, device, usual IP, `user_id` and order history. A visitor starts a new session only after 30 minutes of
inactivity, matching how analytics tools split sessions.

```python
import itertools, json

with open("clicks.jsonl", "w") as out:
    for event in fake.clickstream_events(n_sessions=10_000):
        out.write(json.dumps(event) + "\n")

# n_sessions=None (the default) streams forever: slice it, or break when you have enough
latest = list(itertools.islice(fake.clickstream_events(), 500))
```

### Reproducible output

All randomness comes from the Faker generator, so seeding makes the output reproducible. Times start at the current
time by default; pass `start_time` to fix them too. Naive datetimes are treated as UTC.

```python
from datetime import datetime, timezone

fake.seed_instance(42)
fake.session_clickstream(start_time=datetime(2025, 3, 28, 12, 0, tzinfo=timezone.utc))  # same output every run
```

### Profiles: tuning behaviour

Every tunable value lives in a `Profile`, passed per call. Use a preset by name, or build your own:

```python
from faker_clickstream import EventTuning, Profile

fake.session_clickstream(profile="demo")  # presets: "realistic" (default), "demo"

busy_shop = Profile(
    bounce_rate=0.2,
    sessions_per_hour=5000,
    channel_shares={"Organic search": 50, "Direct": 30, "Social media": 20},
    events={"AddToCart": EventTuning(popularity=30), "Logout": EventTuning(exit_chance=0.9)},
    time_format="epoch_millis",
)
fake.clickstream_events(n_sessions=1000, profile=busy_shop)
slow_visitors = busy_shop.replace(gap_scale=2)  # a copy with one change
```

| Setting | Default | Meaning |
|---|---|---|
| `bounce_rate` | 0.35 | Share of sessions that end after their first event |
| `anonymous_share` | 0.3 | Share of new visitors with `user_id` 0 until they log in |
| `search_to_cart_share` | 0.7 | Chance `AddToCart` adds the product last searched for |
| `lowercase_query_share` | 0.4 | Chance a search is typed in lowercase |
| `device_affinity` | 1.0 | How strongly the device steers brand choice (iPhone → Apple); 0 turns it off |
| `gap_scale` | 1.0 | Multiplies every pause between events |
| `channel_shares` | organic 35, direct 25, social 15, referral 10, other 15 | Traffic sources |
| `device_shares` | mobile 65, desktop 30, tablet 5 | Device types |
| `events` | – | Per-event `EventTuning(popularity, exit_chance, mean_gap_seconds, followed_by)` |
| `time_format` | `"iso"` | See [Time formats](#time-formats) |
| `sessions_per_hour` | 600 | Stream arrival rate, averaged over a day |
| `daily_cycle` | True | Vary the stream's arrival rate by hour of day |
| `returning_visitor_share` | 0.4 | Chance a stream session belongs to an earlier visitor |
| `max_visitors` | 10000 | Visitors a stream remembers for returning sessions |

Invalid values (an unknown event or channel, a share above 1, …) raise `ValueError` when the profile is created.

### Time formats

`time_format` controls `event_time`:

| Value | Example |
|---|---|
| `"iso"` (default) | `"2025-03-28T20:05:00.000000+00:00"` |
| `"epoch_millis"` | `1743192300000` |
| `"datetime"` | a timezone-aware `datetime` object |
| `"legacy"` | `"28/03/2025 20:05:00.000000"` (the format before 0.2.0) |
| any strftime pattern | e.g. `"%Y-%m-%d %H:%M:%S"` |

## Features

Sessions are built to look like real traffic on a phone shop:

- **Session length**: about 35% of sessions bounce after one event; the median is 3 events, with a tail up to
  `rand_session_max_size`. Sessions tend to end after `CompleteOrder` or `Logout`.
- **Funnels**: the next event depends on the previous one (Search → AddToCart → Checkout → CompleteOrder), and only
  events that make sense at that point can happen. About a third of sessions add to cart, ~7% place an order, and
  ~78% of carts are abandoned. The `"demo"` preset raises these to ~76% and ~30%.
- **Timing**: pauses depend on the event: seconds for changing a quantity, about a minute and a half for filling in
  payment details before `CompleteOrder`, around 40 seconds between searches.
- **Visitors**: traffic is mostly mobile (65% phones, 30% desktops, 5% tablets) with current browser user agents, and
  arrives mostly from organic search. iPhone and Mac visitors look at Apple phones far more often; Samsung Internet
  users favour Samsung.
- **Returning visitors** (streams): keep their visitor id, device and usual IP (phones change networks more often),
  stay identified once they have logged in, and can check the status of an order placed in an earlier session.
- **Products**: drawn from a catalog of mobile phones, popular ones more often. Searches read like what people type
  (`"Samsung Galaxy S20 FE"`, `"redmi note 9"`, `"Apple"`), and `AddToCart` usually adds the product just searched for.

### Events

- `Search` (`metadata.query`)
- `AddToCart` (`metadata.product_id`, `metadata.quantity` added)
- `DeleteFromCart` (only while the cart is not empty; removes the product)
- `IncreaseQuantity` (a product already in the cart; `metadata.quantity` is its new quantity)
- `DecreaseQuantity` (a product in the cart with quantity above 1; `metadata.quantity` is its new quantity)
- `AddPromoCode` (once per checkout, after `Checkout` or `CheckoutAsGuest`)
- `Checkout` (only while logged in, with a non-empty cart; once per order)
- `Login` (only while logged out; a visitor's first login gives them a `user_id`)
- `Logout` (only while logged in)
- `CheckoutAsGuest` (only while logged out, with a non-empty cart; once per order)
- `CompleteOrder` (after a checkout; empties the cart; `metadata.order_id`)
- `CheckOrderStatus` (only while logged in; `metadata.order_id` is the visitor's latest order, or an earlier one)

## Contributing

Feel free to support this project and contribute! Support this project by giving a star!
