AM EXPO
AM EXPO

Reputation: 75

Forward looking average

I have a data frame and I want to take the average of three points forward.. I know how to do the min but I need the mean any ideas?

!pip install yfinance
import yfinance as yf 
from scipy.stats import linregress
import pandas as pd
import numpy as np

# test data
df = yf.download('^GSPC',start='2009-11-26',end='2014-12-31',interval='1d')

df['min'] = np.fmin(np.fmin(df['Close'].values, df['Close'].shift(-1).values), df['Close'].shift(-2).values)

thanks

Upvotes: 0

Views: 74

Answers (1)

SeaBean
SeaBean

Reputation: 23217

You can use numpy.mean() with axis=0 on the numpy.array() consisting of the closing prices of current date plus 2 days ahead to get the mean, as follows:

df['mean'] = np.mean(np.array([df['Close'].values, df['Close'].shift(-1).values, df['Close'].shift(-2).values]), axis=0)

Result:

print(df.head(10))

                   Open         High          Low        Close    Adj Close      Volume         mean
Date                                                                                                
2009-11-25  1106.489990  1111.180054  1104.750000  1110.630005  1110.630005  3036350000  1099.250000
2009-11-27  1105.469971  1105.469971  1083.739990  1091.489990  1091.489990  2362910000  1098.659993
2009-11-30  1091.069946  1097.239990  1086.250000  1095.630005  1095.630005  3895520000  1104.576660
2009-12-01  1098.890015  1112.280029  1098.890015  1108.859985  1108.859985  4249310000  1106.006673
2009-12-02  1109.030029  1115.579956  1105.290039  1109.239990  1109.239990  3941340000  1105.046672
2009-12-03  1110.589966  1117.280029  1098.739990  1099.920044  1099.920044  4810030000  1103.050008
2009-12-04  1100.430054  1119.130005  1096.520020  1105.979980  1105.979980  5781140000  1100.389974
2009-12-07  1105.520020  1110.719971  1100.829956  1103.250000  1103.250000  4103360000  1097.046631
2009-12-08  1103.040039  1103.040039  1088.609985  1091.939941  1091.939941  4748030000  1096.746623
2009-12-09  1091.069946  1097.040039  1085.890015  1095.949951  1095.949951  4115410000  1101.569987

Upvotes: 1

Related Questions