4

I have dataset:

print (df['price'])

0      0.435
1     -2.325
2     -3.866
...
58   -35.876
59   -37.746
Name: price, dtype: float64

moving average:

m_a = df['price'].rolling(window=5).mean()
m_a.plot()
print(m_a)
0         NaN
1         NaN
2         NaN
3         NaN
4     -2.8976
5     -4.9628
...
58   -36.2204
59   -36.4632

M/A

How can I determine the trend for the last n rows - FLAT/UP/DOWN? In text, or int def result, like:

trend = gettrend(df,5)
print(trend)
>>UP
goodw1n
  • 53
  • 1
  • 4

2 Answers2

3

You can use something like this with np.where and expand on the logic as required:

df['Trend'] = np.where(df['m_a'] < df['m_a'].shift(),'DOWN',
              np.where(df['m_a'] > df['m_a'].shift(),'UP','FLAT'))


  price m_a Trend
0   1   2   FLAT
1   2   2   FLAT
2   3   4   UP
3   4   5   UP
4   5   6   UP
5   6   7   UP
6   7   -1  DOWN
7   8   2   UP
8   6   7   UP
9   7   -6  DOWN
10  8   -7  DOWN
nipy
  • 5,138
  • 5
  • 31
  • 72
3

I'd do it this way:

Setup sample DF:

In [31]: df = pd.DataFrame(np.random.rand(20)*100, columns=['price'])

In [32]: df
Out[32]:
        price
0   20.555945
1   58.312756
2    3.723192
3   22.298697
4   71.533725
5   71.257019
6   87.355602
7   55.076239
8   67.941031
9   77.437012
10  94.496416
11  16.937017
12  68.494663
13  79.112648
14  88.298477
15  59.028143
16  16.991677
17  14.835137
18  75.095696
19  95.177781

Solution:

In [33]: df['trend'] = np.sign(df['price']
    ...:                         .rolling(window=5)
    ...:                         .mean()
    ...:                         .diff()
    ...:                         .fillna(0)) \
    ...:                         .map({0:'FLAT',1:'UP',-1:'DOWN'})
    ...:

In [34]: df
Out[34]:
        price trend
0   20.555945  FLAT
1   58.312756  FLAT
2    3.723192  FLAT
3   22.298697  FLAT
4   71.533725  FLAT
5   71.257019    UP
6   87.355602    UP
7   55.076239    UP
8   67.941031    UP
9   77.437012    UP
10  94.496416    UP
11  16.937017  DOWN
12  68.494663    UP
13  79.112648    UP
14  88.298477    UP
15  59.028143  DOWN
16  16.991677    UP
17  14.835137  DOWN
18  75.095696  DOWN
19  95.177781    UP

Plot:

In [39]: df.price.plot(figsize=(16,6))
Out[39]: <matplotlib.axes._subplots.AxesSubplot at 0xc16e4a8>

In [40]: plt.locator_params(nbins=len(df))

enter image description here

MaxU - stand with Ukraine
  • 205,989
  • 36
  • 386
  • 419