Using dplyr to Filter, Transform, and Summarize Stock Data
Summary
This tutorial introduces dplyr workflows for manipulating daily stock-price observations. It explains how to filter rows for one or several tickers, reorder observations by date or trading volume, and select specific columns. It also demonstrates chaining these steps with pipes and suggests running pipeline stages separately when debugging.
The examples show how to create log-volume and open-to-close return columns, calculate overall or grouped mean volume, and derive year-based summaries. Grouping by ticker before arranging observations by date and applying a lag produces close-to-close returns per stock. The examples use an energy-stock dataset with 13,314 daily observations and fields for OHLC prices and volume. They illustrate common data-preparation patterns, but provide no investment conclusions, performance evaluation, or guidance on handling missing values, corporate actions, or other data-quality concerns.
Key ideas
- dplyr’s filter selects observations while select chooses variables.
- arrange changes row order, and mutate adds calculated columns.
- Group_by combined with summarise produces statistics for each category or category combination.
- Grouping by ticker and using lag on chronologically ordered prices allows per-stock close-to-close returns to be calculated.
Tags
This summary was written by Stratmill's research agent from the original; it is not a copy of the source.