Time series
Time series data consists of observations on the same variable(s) collected repeatedly over time—for example, daily stock prices, monthly crop prices, or annual population counts. Working with time series data in Stata requires a few extra setup steps: you need a properly formatted date/time variable, and you need to tell Stata which variable represents time before Stata's time-series commands and operators (like lags, differences, and tsline) will work correctly.
This page walks through that setup using Stata's built-in sp500 dataset — daily S&P 500 trading data for 2001.
Loading the data
sysuse sp500
br
This dataset already has a properly formatted date variable, date, along with daily open, high, low, close, and volume values.
Declaring your data as time series
With a date variable already in hand, tell Stata to treat the dataset as time series data using tsset:
tsset date
Stata will confirm the range of dates and note if there are any gaps (which is expected here — stock markets are closed on weekends and holidays).
Visualizing your time series
tsline is a line-graph command built specifically for time series data — it handles the date axis automatically in a way that plain line or twoway line doesn't.
tsline close
Working with lags and differences
Once your data is tsset, Stata's time-series operators become available. L. gives you the previous period's value (a lag), and D. gives you the period-to-period change (a difference) — useful for things like calculating daily returns:
gen daily_return = D.close / L.close * 100
If your date variable starts out as text
Real-world date data doesn't always arrive already formatted the way sp500's is — it's common to get something like "Sept00" or "10/2001" as plain text, which Stata won't recognize as a date on its own. In that case, you'll need to convert it using one of Stata's date-conversion functions (monthly() for monthly data, date() for daily data, and so on) before you can tsset it. For example, converting a monthly string like "Sept00" (month abbreviation, year assumed "20__"):
gen double eventdate = monthly(month, "M20Y")
format eventdate %tm
gen double, rather than a plain gen, matters here — date values can be large numbers, so storing them as double avoids precision loss. See help datetime for the full set of conversion functions across daily, weekly, quarterly, and other frequencies.
Additional resources:
- tsset documentation (Stata)
- introduction to time series (Stata)
- graphing data with dates (UCLA)