> ## Documentation Index
> Fetch the complete documentation index at: https://calendar-effects.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# etl/pageviews_clean.py

> Clean the raw page view files and save clean/pageviews.parquet.

`etl/pageviews_clean.py` · chapter [Building a row](https://calendar-effects.mintlify.site/tour/03-building-a-row.md), file 4 · 59 lines · [open in the repository](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/etl/pageviews_clean.py)

## What it does

Clean the raw page view files and save clean/pageviews.parquet.

Run from anywhere:   python3 etl/pageviews\_clean.py
Output: the `pageviews` contract (article, ticker, date, views), one row per
in-scope retailer per day of the study period.

Renamed articles: some tickers have two titles in config/wiki\_articles.csv
(e.g. Amazon.com became Amazon\_(company) in Sept 2017; The\_Home\_Depot became
Home\_Depot in May 2024). Their views are added together per ticker and day, and
`article` is the title used most in the latest year (the current name).

## Connections

**Uses:** [`src/common/contracts.py`](https://calendar-effects.mintlify.site/reference/src/common/contracts), [`src/common/settings.py`](https://calendar-effects.mintlify.site/reference/src/common/settings), [`src/common/study.py`](https://calendar-effects.mintlify.site/reference/src/common/study)

## Source

```python title="etl/pageviews_clean.py" lines expandable theme={null}
"""Clean the raw page view files and save clean/pageviews.parquet.

Run from anywhere:   python3 etl/pageviews_clean.py
Output: the `pageviews` contract (article, ticker, date, views), one row per
in-scope retailer per day of the study period.

Renamed articles: some tickers have two titles in config/wiki_articles.csv
(e.g. Amazon.com became Amazon_(company) in Sept 2017; The_Home_Depot became
Home_Depot in May 2024). Their views are added together per ticker and day, and
`article` is the title used most in the latest year (the current name).
"""
import pandas as pd
from pyspark.sql import SparkSession, functions as F

from common.contracts import load_wiki_articles, pandas_columns, require_contract
from common.settings import RAW_DIR, clean_path
from common.study import STUDY_END, STUDY_START

spark = SparkSession.builder.master('local[*]').appName('pageviews').getOrCreate()
spark.sparkContext.setLogLevel('ERROR')  # hide Spark's routine warnings

raw = spark.read.json(str(RAW_DIR / 'wiki' / '*.json'))
views = (raw
    .withColumn('date', F.to_date(F.substring('timestamp', 1, 8), 'yyyyMMdd'))
    .filter(F.col('date').between(STUDY_START, STUDY_END))  # raw files from an older period may reach further
    .select('article', 'date', F.col('views').cast('int').alias('views')))
# Only in-scope retailers' titles, so a leftover file of a dropped ticker is ignored.
mapping = spark.createDataFrame(
    [(row['article'], row['ticker']) for row in load_wiki_articles(in_scope_only=True)], 'article string, ticker string')
views = views.join(mapping, 'article')

# Current title per ticker: the one with the most views in the latest year.
latest_year = views.agg(F.max(F.year('date'))).first()[0]
current = (views.filter(F.year('date') == latest_year)
    .groupBy('ticker', 'article').agg(F.sum('views').alias('total'))
    .toPandas().sort_values('total').groupby('ticker')['article'].last())

# Add the titles together per ticker and day (a no-op for tickers with one title).
daily = views.groupBy('ticker', 'date').agg(F.sum('views').cast('int').alias('views'))

pdf = daily.toPandas()
pdf['date'] = pd.to_datetime(pdf['date'])
days = pd.date_range(STUDY_START, STUDY_END)
out = []
for t, g in pdf.groupby('ticker'):
    s = g.set_index('date')['views'].reindex(days)
    print(t, 'days with no data, filled with 0:', int(s.isna().sum()))
    out.append(pd.DataFrame({'article': current[t], 'ticker': t, 'date': days.date,
                             'views': s.fillna(0).astype('int32').values}))
result = pd.concat(out, ignore_index=True)
require_contract('pageviews', pandas_columns(result))
result.to_parquet(clean_path('pageviews'), index=False)

# Checks: one row per ticker per day, and average daily views per year.
# A year far below its neighbours usually means the article was renamed.
print(result.groupby('ticker').size())
yearly = result.assign(year=pd.to_datetime(result['date']).dt.year)
print(yearly.pivot_table(index='ticker', columns='year', values='views', aggfunc='mean').round(0))
spark.stop()
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.