zqshmvbs
zqshmvbs

Reputation: 13

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)

I am trying to get the moving average data from yahoo_fin.stock_info.get_stats('a') but I am getting the following error:

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.

Upvotes: 1

Views: 5642

Answers (2)

atreadw
atreadw

Reputation: 299

I pushed a patch for this - if you upgrade your version of yahoo_fin to 0.8.5, this should be fixed now.

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. 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.).

Upvotes: 1

user7440787
user7440787

Reputation: 841

you can calculate the 50 day moving average from get_data using the code:

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)]

Upvotes: 1

Related Questions