> ## 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/prices_clean.py

> Clean the raw price files with Spark and save clean/prices.parquet.

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

## What it does

Clean the raw price files with Spark and save clean/prices.parquet.

Run from anywhere:   python3 etl/prices\_clean.py
Output: the `prices` contract (ticker, date, adj\_close, volume, ret, vol\_ratio).

## 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/prices_clean.py" lines expandable theme={null}
"""Clean the raw price files with Spark and save clean/prices.parquet.

Run from anywhere:   python3 etl/prices_clean.py
Output: the `prices` contract (ticker, date, adj_close, volume, ret, vol_ratio).
"""
from pyspark.sql import SparkSession, functions as F
from pyspark.sql.window import Window

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

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

raw = (spark.read.option('header', True).option('inferSchema', True).csv(str(RAW_DIR / 'prices' / '*.csv'))
    .filter(F.col('ticker').isin(price_tickers())))  # a leftover file of an out-of-scope ticker is ignored

# A window is a "look at the neighbouring rows" rule:
# each ticker on its own, rows in date order.
w = Window.partitionBy('ticker').orderBy('date')

prices = (raw
    .withColumn('date', F.to_date('Date'))
    # inferSchema reads volume as a 32-bit int; the contract says long (64-bit)
    .select('ticker', 'date', F.col('Close').alias('adj_close'), F.col('Volume').cast('long').alias('volume'))
    .filter(F.col('date').between(STUDY_START, STUDY_END))  # raw files from an older period may reach further
    .dropna(subset=['adj_close', 'volume'])
    .dropDuplicates(['ticker', 'date'])
    # ret: today's price / yesterday's price - 1 (empty on each ticker's first day)
    .withColumn('ret', F.col('adj_close') / F.lag('adj_close').over(w) - 1)
    # vol_ratio: today's volume / average of the 20 days BEFORE today (-20 to -1),
    # so it never peeks at today or the future
    .withColumn('vol_ratio', F.col('volume') / F.avg('volume').over(w.rowsBetween(-20, -1))))

out = prices.orderBy('ticker', 'date').toPandas()
require_contract('prices', pandas_columns(out))
out.to_parquet(clean_path('prices'), index=False)
print('rows:', len(out))
prices.filter(F.abs('ret') > 0.4).show()  # days with a >40% move: should be empty or tiny
spark.stop()
```


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