如何创建返回移动平均线斜率的列?

发布于 2025-01-09 05:08:33 字数 1068 浏览 0 评论 0原文

在包含比特币价格的数据框中,我想通过在每行上显示移动平均线(计算超过 20 个周期)的斜率角度来衡量趋势的强度。

移动平均线允许您分析时间序列,消除瞬时波动以突出长期趋势。 为了计算用于交易目的的简单 20 周期移动平均线,我们采用最后 20 个收盘价,将它们相加并将结果除以 20。

我开始尝试使用 scipy 的 linregress 函数,但出现异常“len( )的未调整大小的对象”,我无法解决:

from scipy.stats import linregress
x = df.iloc[-1, 8] # -1:last row, 8: sma20
y = df['sma20']
df['slope_deg'] = df.apply(linregress(x, y))

然后我使用了数学模块的 atan 函数,但返回的结果始终为 nan,无论行是什么:

import math
df['sma20'] =  df['Close'].rolling(20).mean()
slope=((df['sma20'][0]-df['sma20'][20])/20)
df['slope_deg'] = math.atan(slope) * 180 / math.pi

...或 45 :

import math
df['sma20'] =  df['Close'].rolling(20).mean()
df['slope_deg'] = math.atan(1) * 180 / math.pi
df

这是一个代码示例,日期为一个指数、用于计算移动平均线的价格以及移动平均线(例如超过 5 个周期):

df= pd.DataFrame({'date':np.tile( pd.date_range('1/1/2011', 
periods=25, freq='D'), 4 ),
'price':(np.random.randn(100).cumsum() + 10),
'sma5':df['price'].rolling(5).mean() 
})

df.head(10)

有人可以帮助我创建一个返回移动平均线斜率的列吗?

on a dataframe that contains the price of bitcoin, I want to measure the strength of a trend by displaying the angle of the slope of a moving average (calculated over 20 periods) on each row.

A moving average allows you to analyze a time series, removing transient fluctuations in order to highlight longer term trends.
To calculate a simple 20-period moving average for trading purposes, we take the last 20 closing prices, add them together and divide the result by 20.

I started by trying to use the linregress function of scipy but I get the exception "len() of unsized object" that I could not solve:

from scipy.stats import linregress
x = df.iloc[-1, 8] # -1:last row, 8: sma20
y = df['sma20']
df['slope_deg'] = df.apply(linregress(x, y))

I then used the atan function of the math module but the result returned is always nan, whatever the row is:

import math
df['sma20'] =  df['Close'].rolling(20).mean()
slope=((df['sma20'][0]-df['sma20'][20])/20)
df['slope_deg'] = math.atan(slope) * 180 / math.pi

... or 45 :

import math
df['sma20'] =  df['Close'].rolling(20).mean()
df['slope_deg'] = math.atan(1) * 180 / math.pi
df

Here is an example of code with the date as an index, the price used to calculate the moving average, and the moving average (over 5 periods for the example):

df= pd.DataFrame({'date':np.tile( pd.date_range('1/1/2011', 
periods=25, freq='D'), 4 ),
'price':(np.random.randn(100).cumsum() + 10),
'sma5':df['price'].rolling(5).mean() 
})

df.head(10)

Can someone help me to create a column that returns the slope of a moving average?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

背叛残局 2025-01-16 05:08:33

好的,我做了20天的sma,我不太确定斜率部分,因为你没有明确指定你需要什么。

我假设坡度值(以度为单位)如下:

arctan( (PriceToday - Price20daysAgo)/ 20 )

这里有代码:

EDIT 1: 简化 '斜率'代码并根据#Oliver的建议进行了修改。

import pandas as pd
import yfinance as yf

btc          = yf.download('BTC-USD', period='1Y')
btc['sma20'] = btc.rolling(20).mean()['Adj Close']
btc['slope'] = np.degrees(np.arctan(btc['sma20'].diff()/20))
btc          = btc[['Adj Close','sma20','slope']].dropna()

输出:

btc

               Adj Close           sma20        slope
      Date          
2021-03-15  55907.199219    51764.509570     86.767651
2021-03-16  56804.902344    52119.488086     86.775283
2021-03-17  58870.894531    52708.340234     88.054732
2021-03-18  57858.921875    53284.298242     88.011217
2021-03-19  58346.652344    53892.208203     88.115671
... ... ... ...
2022-02-19  40122.156250    41560.807227     79.715989
2022-02-20  38431.378906    41558.219922     -7.371144
2022-02-21  37075.281250    41474.820312    -76.514600
2022-02-22  38286.027344    41541.472461     73.297321
2022-02-23  38748.464844    41621.165625     75.911862

正如您所看到的,斜率值的意义不大。这是因为 20 天垃圾邮件的价格变化远远大于 20 个单位,该值代表您选择使用的时间窗口。

绘制价格和 sma20 与日期的关系。

btc[['Adj Close','sma20']].plot(figsize=(14,7));

输入图片此处描述

OK, I did the 20 day sma, I am not so sure about the slope part, since you didnt clearly specify what you need.

I am assuming slope values, in degrees, as follows:

arctan( (PriceToday - Price20daysAgo)/ 20 )

Here you have the code:

EDIT 1: simplified 'slope' code and adapted following #Oliver 's suggestion.

import pandas as pd
import yfinance as yf

btc          = yf.download('BTC-USD', period='1Y')
btc['sma20'] = btc.rolling(20).mean()['Adj Close']
btc['slope'] = np.degrees(np.arctan(btc['sma20'].diff()/20))
btc          = btc[['Adj Close','sma20','slope']].dropna()

Output:

btc

               Adj Close           sma20        slope
      Date          
2021-03-15  55907.199219    51764.509570     86.767651
2021-03-16  56804.902344    52119.488086     86.775283
2021-03-17  58870.894531    52708.340234     88.054732
2021-03-18  57858.921875    53284.298242     88.011217
2021-03-19  58346.652344    53892.208203     88.115671
... ... ... ...
2022-02-19  40122.156250    41560.807227     79.715989
2022-02-20  38431.378906    41558.219922     -7.371144
2022-02-21  37075.281250    41474.820312    -76.514600
2022-02-22  38286.027344    41541.472461     73.297321
2022-02-23  38748.464844    41621.165625     75.911862

As you can see, the slope value means little as it is. Thats because the variation in price from a 20 days spam is far greater than 20 units, the value representing the time window you chose to use.

Plotting prices and sma20 vs date.

btc[['Adj Close','sma20']].plot(figsize=(14,7));

enter image description here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文