IntermediateSimulation & Finance25 points

Days a stock beats its moving average

A trader uses the simple moving average (SMA) as a trend filter: the price is bullish on a day when it closes above its recent average. Prices are in stocks.csv (60 trading days, four fictional tickers).

  • date: trading day, rows are in date order
  • ticker: stock symbol
  • close: closing price

Task: the first input line is a ticker, the second an integer window k. For a day, SMA(k) is the average of that day's close and the closes of the previous k-1 trading days of the same ticker; it exists only from the k-th day on. Print Days above SMA: A of M where M is the number of days that have an SMA and A is how many of them close strictly above it. Then print Last SMA: X and Last close: Y, both with 2 decimals. If the ticker has fewer than k rows print only Not enough data.

Files your program can read

stocks.csv241 lines
date,ticker,close
2025-01-02,ORBT,117.11
2025-01-02,VELA,48.96
2025-01-02,NOVA,311.32
2025-01-02,KITE,22.25
2025-01-03,ORBT,116.32
2025-01-03,VELA,49.69
2025-01-03,NOVA,313.66
...

Open them by name, for example open("stocks.csv").

Sample test

Input

ORBT
5

Expected output

Days above SMA: 31 of 56
Last SMA: 109.47
Last close: 110.32

Your answer is also checked against 5 hidden tests.

Need a hint?

Slice the list of closes for each day: closes[i-k+1:i+1].