简体   繁体   中英

How to calculate slope of moving average's endpoints?

I am trying to get data from marketstack API and calculate its moving average and then calculate the moving average's slope between the endpoints.

I have done something like

    api_result = requests.get('http://api.marketstack.com/v1/eod?access_key='+apikey+'&symbols='+symbol)
    api_response = api_result.json()
    df=pd.DataFrame.from_dict(api_response['data'])
    df=df.drop(['volume','adj_high','adj_low','adj_close','adj_open','adj_volume','split_factor','symbol','exchange'], axis = 1)
    df['SMA'] = df.iloc[:,3].rolling(window=3).mean()
    slope=(df['SMA'][99]-df['SMA'][2]/98))
    print(slope)

df has 100 rows.

this gives value like for AAPL - 121.14384353741498

I am sure this is wrong, I checked manually by seeing the chart.

However, the formula for slope is (y2-y1/x2-x1), which is what I have done. (98 because of window size as 3)

What am I doing wrong here? How can I find the slope of the moving average in DEGREES?


If you want this what the data looks like

     open    high     low   close                      date           SMA
0   132.04  134.07  131.83  132.54  2021-05-03T00:00:00+0000           NaN
1   131.78  133.56  131.07  131.46  2021-04-30T00:00:00+0000           NaN
2   136.47  137.07  132.45  133.48  2021-04-29T00:00:00+0000    134.900000
3   134.31  135.02  133.08  133.58  2021-04-28T00:00:00+0000    135.216667
4   135.01  135.40  134.11  134.39  2021-04-27T00:00:00+0000    135.830000
..     ...     ...     ...     ...                       ...           ...
95  122.60  123.35  121.54  121.78  2020-12-14T00:00:00+0000    126.540000
96  122.43  122.76  120.55  122.41  2020-12-11T00:00:00+0000    124.670000
97  120.50  123.87  120.15  123.24  2020-12-10T00:00:00+0000    123.326667
98  124.53  125.95  121.00  121.78  2020-12-09T00:00:00+0000    124.193333
99  124.37  124.98  123.09  124.38  2020-12-08T00:00:00+0000    124.933333

Any help would be greatly appreciated. :)

Hmm, sma[99] = 124.933333 and sma[2] = 134.900000 . (134.900000 - 124.933333) / 98 = 0.10170 not 121.14384353741498 You actually calculated (134.900000 - 124.933333/98) . You should have slope=(df['SMA'][99]-df['SMA'][2])/98) .

And the slope in degrees will be slope_deg = math.atan(slope) * 180 / math.pi

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM