#C253. Moving Average Calculation from CSV Input

    ID: 45856 Type: Default 1000ms 256MiB

Moving Average Calculation from CSV Input

Moving Average Calculation from CSV Input

You are given a CSV input representing time series data of stock prices. Your task is to compute the moving average of the stock prices after handling missing data using the forward-fill method. The CSV content is given via standard input (stdin).

Procedure:

  • First, read an integer representing the window size W.
  • Next, read a string that specifies the name of the column (e.g., "StockPrice") that contains the stock prices.
  • The following lines form the CSV data. The first line of the CSV data is the header. Subsequent lines contain the data records. Each record has at least two columns (date and stock price). If the stock price is missing (an empty field), it should be replaced by the most recent valid value (forward-fill). Note that if the first value is missing, it remains missing.
  • Compute the moving average using a rolling window of size W. For rows where there are fewer than W entries, output nan (not a number).
  • Output the resulting moving average for each row in order on a separate line. If a value is defined, print it formatted to two decimal places; otherwise, print nan.

Note: Although the original specification mentioned plotting, for this contest problem you only need to perform the calculations and output the result via stdout.

inputFormat

The input is provided via standard input (stdin) with the following structure:

  1. An integer W representing the window size for the moving average.
  2. A string representing the column name (e.g., "StockPrice").
  3. A CSV formatted text where the first line is the header and the subsequent lines are records. Each record contains at least two fields separated by commas: a date and the stock price. Missing stock prices will be represented as an empty field.

outputFormat

Output the moving average value for each row on its own line. For rows with insufficient data to compute a full window, output nan. For computed values, display the floating point result rounded to two decimal places.

## sample
3
StockPrice
Date,StockPrice
2020-01-01,100
2020-01-02,101
2020-01-03,
2020-01-04,103
2020-01-05,
2020-01-06,105
2020-01-07,106
2020-01-08,107
2020-01-09,
2020-01-10,109
nan

nan 100.67 101.67 102.33 103.67 104.67 106.00 106.67 107.67

</p>