Is it possible to get monthly stock prices from Google Finance? - python

In Python, monthly stock prices from Yahoo Finance as follows...
import pandas_datareader.data as web
data = web.get_data_yahoo('IBM','01/01/2016',interval='m')
I tried to get monthly stock prices from Google Finance, but daily stock prices are returned
data = web.get_data_google('IBM','2016')
How can I get monthly stock prices from Google Finance in Python ? Thanks in advance

According to the documentation, this is indeed possible.
EDIT: The example below, despite being part of the documentation, does not seem to work. I have found that the following works as an alternative:
import pandas_datareader.data as web
quotes = web.DataReader('NYSE:IBM', 'google')
Where 'NYSE:IBM' is the exchange code and ticker separated by a colon, and 'google' is the pricing source.
OLD (NON-WORKING) EXAMPLE:
In [42]: import pandas_datareader.data as web
In [43]: q = web.get_quote_google(['AMZN', 'GOOG'])
In [44]: q
Out[44]:
change_pct last time
AMZN 0.01 780.22 2016-11-25 13:00:00
GOOG 0.09 761.68 2016-11-25 13:00:00

Related

How to get all At-The-Money options using yahoo_fin

I am trying to create a list of all At-The-Money (ATM) option contracts using yahoo_fin options module.
Yahoo_fin offers 2 methods for getting all call and put contracts:
from yahoo_fin import options as ops
# ops.get_call(Ticker, expiration_date=None)
# ops.get_pull(Ticker, expiration_date=None)
# If no expiration_date is passed, the nearest expiration date is used
ops.get_calls("aapl")
ops.get_puts("aapl")
These two methods return the following dataframes, respectively:
I have done some research at possibly using the strike price and comparing it with the underlying stock price. This is probably the most basic way, but the underlying stock may hay a price that is not exactly the same as an option's strike price. Another alternative I have read is to use delta. Can anybody provide insight into how I could find the ATM options using the data provided by yahoo_fin? Is it possible?
For ATM options the strike price is equal to the underlying asset’s current market price, as explained here.
However, there is no option for every possible market price, as options are oganized in grids. You could get the price of the option for which the strike price is closest to the underlying's market price. You can implement it as:
from yahoo_fin import options, stock_info
symbol = "AAPL"
last_adj_close = stock_info.get_data(symbol)["adjclose"][-1]
calls = options.get_calls("aapl")
puts = options.get_puts("aapl")
atm_call = calls.iloc[(calls["Strike"] - last_adj_close).abs().argsort()[:1]]
Output:
Contract Name Last Trade Date Strike Last Price Bid Ask Change % Change Volume Open Interest Implied Volatility
43 AAPL221118C00149000 2022-11-16 3:59PM EST 149.0 1.58 1.5 1.66 -1.12 -41.48% 22594 14120 40.09%
for the AAPL stock:
open high low close adjclose volume ticker
2022-11-14 148.970001 150.279999 147.429993 148.279999 148.279999 73374100 AAPL
2022-11-15 152.220001 153.589996 148.559998 150.039993 150.039993 89868300 AAPL
You can also obtain the two closest options by adjusting the parameter in
.argsort()[:2].

Getting TTM income statement yahoo finance using yahoo_fin

I try to get ttm values of the income statement for ticker symbol AAPL by using
from yahoo_fin import stock_info as si
import yfinance as yf
import pandas as pd
import matplotlib.pyplot as plt
import pandas_datareader
pd.set_option('display.max_columns', None)
income_statement = si.get_income_statement("aapl")
income_statement
but the result doesn't show the ttm values, only the yearly values are shown
On yahoo finance, we can also see the ttm values:
Anyone who can help?
The reason you don't get the exact same table you see on the website is because of the way yahoo_fin gets data from Yahoo. Rather than getting them from the table you see, they get them from json data that Yahoo provides. In this data, there are both quarterly and yearly income statements. When Yahoo renders the table on their website, they most likely use the yearly data for the yearly columns and then sum the last 4 quarterly results to get the TTM column (as TTM results are nothing else than the sum of the last 4 quarterly results).
If you want to get the TTM data, the best approach would be to do it the same way I assume Yahoo does. Get the quarterly data using yahoo_fin and then sum the quarters to calculate the TTM results. You can do this by setting the optional yearly parameter to False:
quarterly_income_statement = si.get_income_statement("aapl", yearly=False)
You can check out their method _parse_json to better understand how they get and parse data from Yahoo. (Assuming you have some knowledge of requests and json.)
Summing the data
To get the sum of the quarters you can for example do this:
quarterly_income_statement = si.get_income_statement("aapl", yearly=False)
ttm = quarterly_income_statement.sum(axis=1)
This will give you a new Dataframe ttm with the same data fields with values being TTM (You can test it and see if it matches the numbers on the website).

Getting a specific element from a Pandas Dataframe

This is probably a rookie question, but I haven't been able to find the solution.
I'm trying to collect some data from Yahoo Finance using pandas.
from pandas_datareader import data
tickers = ['EQNR.OL','BP','CL=F']
start_date = '2001-01-02'
end_date = '2021-02-26'
panel_data = data.DataReader(tickers, 'yahoo', start_date, end_date)
I wanna take a look at the BP stock (I need all 3, so excluding EQNR.OL and CL=F from tickers is not the right solution). I know how to get all the close prices of a single stock:
close_BP = panel_data['Close','BP']
But is there a way I can get all BP data (open, close, high, low) withdrawn from 'panel_data', and not only a specific column like 'close'?
I was thinking something like BP = panel_data[:,'BP'] or BP = panel_data.loc[:,'BP'] but it doesn't work.
A big thanks in advance.
I think what you're looking for is pandas.IndexSlice...
import pandas as pd
panel_data.loc[:, pd.IndexSlice[:, 'BP']]
You can swap multi-columns and then extract them with loc.
panel_data = panel_data.swaplevel(axis=1)
panel_data.loc[:, ('BP',)]
Attributes Adj Close Close High Low Open Volume
Date
2021-01-04 20.551737 20.830000 21.129999 20.549999 21.090000 14485100.0
2021-01-05 22.081030 22.379999 22.780001 21.370001 21.430000 25447500.0
2021-01-06 23.097271 23.410000 23.860001 22.940001 23.370001 25221400.0
2021-01-07 23.590591 23.910000 24.150000 23.500000 23.719999 16470700.0
2021-01-08 24.074045 24.400000 24.490000 23.990000 24.170000 20189600.0
...

Python - Get yahoo finance data and retaining the data identifier

I am trying to download data from Yahoo Finance and I have the following code to accomplish this; the code works well.
import pandas as pd
from pandas_datareader import data as pdr
ticker=['CBRL','DRI','MSFT']
start_date = '2015-01-01'
end_date = '2016-06-30'
data=pd.DataFrame()
for x in ticker:
panel_data = pdr.DataReader(x, 'yahoo', start_date, end_date)
data = data.append(panel_data)
My only problem is that the above doesn't retain the stock identifiers, ie once I have all data in one dataframe, I can't which ticker symbol each series corresponds to. I have tried using panel_data.to_frame() after running all of the above, but nothing changes. I am still stuck with all the data, but no ticker identifiers for each of my rows. Can I please have someone's thoughts?

How can I get the data for the nasdaq index using the pandas data_reader?

Using the Pandas data_reader, I can get the historical stock information in the form of a DataFrame such as:
import pandas_datareader.data as web
import datetime as dt
start = dt.datetime(2015, 1, 1)
end = dt.datetime.now()
df = web.DataReader("TSLA", 'morningstar', start, end)
Can i get the composite data for the NASDAQ index in this way, rather than just one stock?
Your question asked for it using the pandas_datareader module. It used to be very straightforward to get this information using pandas_datareader before Yahoo! altered their API in late 2017 and the csv endpoint was retired. More on some these developments can be in the pandas_datareader docs (link here).
There is another fairly straightforward option for getting the NASDAQ Composite index into a dataframe. That is, to use the Quandl module for this purpose (Link here).
Here's how you can use Quandl
import datetime, quandl
ndq = quandl.get("NASDAQOMX/COMP-NASDAQ",
trim_start='2018-03-01',
trim_end='2018-04-03')
print(ndq.head(4))
With expected Output:
Trade Date Index Value High Low Total Market Value
2018-03-01 7180.56 7307.84 7117.66 1.096433e+13
2018-03-02 7257.87 7267.19 7084.83 1.108254e+13
2018-03-05 7330.70 7350.07 7205.31 1.119375e+13
2018-03-06 7372.01 7378.03 7319.68 1.125703e+13

Categories