Skip to content
Tutorials Center
My learning

Topics

Lesson 40 of 42 ยท Projects and Practice

Project: Stock Prices and Time Series

Analyze price time series with Plotly and pandas: line charts with range sliders, returns, rolling averages, Bollinger bands, candlestick and volume subplots with a shared axis.

Time series are the most common data in business and science: prices, traffic, sensors, temperatures. In this project you will build the standard toolkit for looking at prices over time: a multi-line chart with a range slider, daily returns, a rolling average with Bollinger bands, and a candlestick chart with volume underneath.

This lesson is about charts, not investing. All data is either the small sample dataset that ships with Plotly (weekly prices normalized to 1.0 at the start) or simulated with a fixed seed. Nothing here is financial advice or a real market feed.

Step 1: compare several series

px.data.stocks() returns one date column and six price columns, all scaled to start at 1.0, so you can compare growth directly. Plotly Express expects "long" data for multiple lines, but it also accepts a wide DataFrame and a list of columns for y.

Python Step 1: normalized prices and the best performer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

hovermode="x unified" gives one tooltip for all lines at the cursor, and the range slider lets readers zoom into a period.

Step 2: returns instead of levels

Prices drift upward, which hides how volatile a series is. Returns (percentage changes) are stationary and comparable. pct_change() computes them, and a histogram shows the distribution.

Python Step 2: weekly returns and their spread

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The standard deviation of the returns is the most common simple measure of volatility. A box plot per ticker shows both the typical week and the outliers at once. melt converted the wide table into the long format that px.box wants (one row per observation).

Step 3: trend and Bollinger bands

A rolling mean smooths the series; a Bollinger band is the mean plus and minus two rolling standard deviations, so it widens when the series gets more volatile. Plotly draws a band with two lines and fill="tonexty".

Python Step 3: a simulated price with a 20-day band

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The first trace has line=dict(width=0) and no legend entry: it only provides the upper edge. The second trace fills "to the next y" (tonexty), which means up to the previous trace, creating the shaded band. The order of the traces matters.

Step 4: candlesticks with volume

A candlestick summarizes one period (a day) with four numbers: open, high, low, close. The body spans open to close and is colored by direction; the thin "wicks" show the high and low. A volume bar chart sits in a second row sharing the x-axis, as you learned in subplots.

Step 4: OHLC candlestick and volume (Plotly.js)

Two details improve candlesticks. rangebreaks: [{bounds: ["sat", "mon"]}] removes the weekend gaps from the axis, so candles sit next to each other instead of leaving holes. And rangeslider: {visible: false} hides the default slider that the candlestick would otherwise add. In Python the same traces are go.Candlestick(x=, open=, high=, low=, close=) and fig.update_xaxes(rangebreaks=[dict(bounds=["sat", "mon"])]). Holidays can be removed with values=["2025-12-25"].

Step 5: show what happened

Time series gain meaning from events. Mark them with annotations and shapes:

Python
fig.add_vline(x="2025-02-14", line_dash="dot", annotation_text="earnings", annotation_position="top")
fig.add_vrect(x0="2025-03-03", x1="2025-03-14", fillcolor="orange", opacity=0.15, line_width=0)

Other useful tools for time series: px.area for cumulative views, px.line with facet_row to compare many series with a shared axis (see facets), fig.update_xaxes(tickformat="%b %Y") for readable dates, and fig.update_yaxes(type="log") for series that grow exponentially, where equal percentage changes then look equal.

Dates must be real dates. If Plotly shows a category axis with text labels in the wrong order, convert the column with pd.to_datetime. Date axes sort correctly, support range selectors and understand rangebreaks.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why look at returns (percentage changes) instead of price levels when comparing volatility?

    Returns remove the level and the drift, so the spread of changes can be compared between series.
  2. 2. How is a shaded band drawn between two lines?

    tonexty fills the area between this trace and the previous one, so trace order matters.
  3. 3. What do the four numbers of a candlestick represent?

    A candle summarizes one period by its opening, highest, lowest and closing price.
  4. 4. What does rangebreaks with bounds ["sat", "mon"] do?

    The break removes the time between Saturday and Monday from the axis so trading days line up.

Summary

  • Compare series on a common base (normalized) and add a range slider and hovermode="x unified".
  • Use returns and standard deviation to compare volatility; melt prepares wide data for box plots.
  • Bollinger bands are a rolling mean plus or minus two rolling standard deviations drawn with fill="tonexty".
  • Candlestick plus volume in two rows with rangebreaks gives the classic price chart.
  • Convert dates to real datetimes and mark events with vertical lines and shaded regions.

Next: Project: A World Data Explorer