Template that gives average in hours over the last couple of weeks

In my HA I have a sensor that gives the power that is consumed bij the house (grid - solar), sensor.power_home. I would like to have a prediction for a day a head. I was thinking to just average the days of the last couple of weeks. So over a period of 24 hours I would like to have for each hour the average of the last couple of days.

I tried using templates for this, but I can not figure out how you can use historical date.
Need something like average(power, power -1d, power -2d, etc)
I also checked the historical stats sensor, but that seems also not a solution.

Does have any one an idea?