I have a time-series. The index is weekly dates and the values are a certain indicator that I made. I think I understand how to apply KNN in this situation but I'm not sure how exactly to do it.

This is what I currently have:

1. Set lookback period to 200 rows (which is 200 weeks)
2. Set the KNN value to 10 Nearest Neighbors
3. Start with the 201 st row
4. Get the previous 200 days
5. Do Knn.fit(x = prev_200_row, y = profit_after_each_row, neighbors = 10)
6. Do Knn.predict(current_row)
7. Save the prediction to a list
8. Go to the next row and repeat steps 4, 5, 6, 7, 8 until no more rows.

Is this is a correct use of the process? Eventually, I would like to compare different values for K (10 nearest neighbors or maybe 50 nearest neighbors). I am going to build on this so I want to make sure that I am starting correctly. I am wondering if it is correct that the Knn.fit is being called after every row but it seems correct to me.

  • $\begingroup$ Are you attempting to employ KNN as a smoothing technique? I'm not really seeing your endgame. $\endgroup$
    – AN6U5
    Jun 23, 2016 at 16:20

1 Answer 1


I never used KNN on time series. I didn't know it was possible before reading your question. But by googling it found this tutorial that feel pretty clear.

And if understand you correctly what you do with KNeighborsRegressor, by repeating 4 - 5 - 6 you will based the later predictions on what you predicted for the previous row.

If this is not intended you can just predict every row following the 200 used for training.

Hope it helps :)


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.