[英]How can I calculate the moving average with yahoo_fin in Python?
I am trying to make a program that emails alerts when a stock price crosses a moving average and I am using the library yahoo_fin
(Here are the docs )我正在尝试制作一个程序,当股票价格超过移动平均线时通过电子邮件发送警报,并且我正在使用库
yahoo_fin
(这里是文档)
I am trying to get the moving average data from yahoo_fin.stock_info.get_stats('a')
but I am getting the following error:我正在尝试从
yahoo_fin.stock_info.get_stats('a')
获取移动平均数据,但出现以下错误:
File "lib\site-packages\yahoo_fin\stock_info.py", line 241, in get_stats
table.columns = ["Attribute" , "Value"]
File "lib\site-packages\pandas\core\generic.py", line 5287, in __setattr__
return object.__setattr__(self, name, value)
File "pandas\_libs\properties.pyx", line 67, in pandas._libs.properties.AxisProperty.__set__
File "lib\site-packages\pandas\core\generic.py", line 661, in _set_axis
self._data.set_axis(axis, labels)
File "lib\site-packages\pandas\core\internals\managers.py", line 178, in set_axis
f"Length mismatch: Expected axis has {old_len} elements, new "
ValueError: Length mismatch: Expected axis has 9 elements, new values have 2 elements
Any help on fixing this would be great!解决此问题的任何帮助都会很棒!
If you don't know how to get this particular function to work, another alternative I tried and which seems to work is to use the method yahoo_fin.stock_info.get_data('a')
, but I would need help to know how to calculate the moving average from this data.如果您不知道如何让这个特定的 function 工作,我尝试过的另一种选择似乎可行的是使用方法
yahoo_fin.stock_info.get_data('a')
,但我需要帮助才能知道如何计算该数据的移动平均线。
you can calculate the 50 day moving average from get_data
using the code:您可以使用以下代码从
get_data
计算 50 天移动平均线:
import yahoo_fin
from yahoo_fin import stock_info
yahoo_fin.stock_info.get_data('a', interval='1d')['close'][-50:].mean()
if you want yo calculate it over a certain period:如果你想在一段时间内计算它:
df = yahoo_fin.stock_info.get_data('a', interval='1d')
moving_average = [df['close'][i-50:i].mean() for i in range(50, df.shape[0]+1)]
I pushed a patch for this - if you upgrade your version of yahoo_fin to 0.8.5, this should be fixed now.我为此推送了一个补丁 - 如果您将 yahoo_fin 的版本升级到 0.8.5,现在应该已修复。
from yahoo_fin import stock info as si
si.get_stats("a")
From this, you can get the 50-day and 200-day moving averages.由此,您可以获得 50 天和 200 天移动平均线。 However, as mentioned in @user7440787's response, you can use the get_data method to pull the price history, and then calculate whatever window-size moving average you need to (10-day, 100-day, 150-day, etc.).
但是,正如@user7440787 的回复中提到的,您可以使用 get_data 方法来提取价格历史记录,然后计算您需要的任何窗口大小的移动平均线(10 天、100 天、150 天等)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.