How to lookup any index from Yahoo using pandas-datareader - python

I want to use look ups for any online index, including those with digits. A random example is:
https://uk.finance.yahoo.com/quote/YSM6.AX/futures?p=YSM6.AX
A naive method is to use pandas-datareader:
from pandas_datareader import data as datareader
online_data = datareader.DataReader('YSM6.AX', 'yahoo', start, end)
However, this doesn't work. I think the digits in the ticker aren't handled properly. This command works fine with e.g. "AAPL".
How do I get this to work for any index?

The YSM6.AX link shows that there is no data for this stock.
If you want to grab multiple stock, and get specifically the adjusted close, you can use this code. It takes into account any funny stock tickers that have either a "-", or in the case of YSM6.AX, a "." inside the ticker.
import pandas as pd
import datetime
from pandas_datareader import data, wb
tickers = ["BRK.B", "AAPL", "MSFT", "YHOO", "JPM"]
series_list = []
start = datetime.datetime(2012, 4, 5)
end = datetime.datetime(2017, 3, 28)
for security in tickers:
s = data.DataReader(security.replace(".","-"),"yahoo",start, end )["Adj Close"]
s.name = security
series_list.append(s)
df = pd.concat(series_list, axis=1)
stocks= pd.DataFrame(df)
stocks

If you look at the link you have provided, YSM6 is a futures contract on ASX. Specifically it is the M6 expiry, meaning 2016-06. And Yahoo has no data for this contract on their site anymore--perhaps because it is expired, or perhaps because there was never any data available for it. Furthermore, this product (3 year AU interest rate swap futures) seems to have been discontinued by the exchange.
Your question says you want "stock" data. Here's an example of an actual stock with a numeric symbol:
https://uk.finance.yahoo.com/quote/7203.KL/?p=7203.KL

Related

How do I export this pandas array of stock data into an excel spreadsheet?

import pandas as pd
import yfinance as yf
import pendulum
from datetime import date
today = str(date.today())
print(today)
pd.options.display.max_rows=390
start = pendulum.parse('2022-12-5 08:30')
end = pendulum.parse('2022-12-5 15:00')
stock = input("Enter a stock ticker symbol: ")
print(stock + " 1 Minute Data")
print(start)
print(yf.download(tickers= stock, interval="1m", start=start, end=end))
Running the code and typing in "TSLA" will load up every tick for the specified date. How would I export this array in a clean fashion to excel?
Side note: I was also trying to put today's date instead of pendulum's manual date '2022-12-5'
Is there a way to also use the current date for pendulum.parse instead of manually typing it out every time? I tried making the date a variable but got an error etc.
Well, I suspect yf.download is returning a pandas dataframe, so you could just save it to Excel using panda's to_excel function, unless there is more structure or processing you need to do.
df = yf.download(...)
df.to_excel('ticker_data.xlsx')
Question 1:
It returns a dataframe but you need to reset the index to bring Datetime column from index to column. You can chain all the commands together.
Question 2:
pendulum.parse() takes a str so you just need to use an fstring.
import pendulum
import yfinance as yf
start = pendulum.parse(f"{pendulum.now().date()} 08:30")
end = pendulum.parse(f"{pendulum.now().date()} 15:00")
stock = input("Enter a stock ticker symbol: ")
(yf
.download(tickers=stock, interval="1m", start=start, end=end)
.reset_index()
.to_excel(f"/path/to/file/{stock.lower()}.xlsx", index=False, sheet_name=stock)
)

How to collect data in range from Yahoo Finance?

I am using a script which uses this line:
res = requests.get('https://query1.finance.yahoo.com/v8/finance/chart/{symbol}?range={data_range}&interval={data_interval}'.format(**locals()))
to collect stock data from Yahoo Finance. Currently, I am inputting values such as '1d' for data_range which gives me the data from the past day. However, what do I enter if I want to collect data say from 2020-11-24 to 2020-11-25 (instead of from past x days)?
I would suggest using the Selenium library.Because you need to handle click event and for the page to relode to get the new updated stock data check bellow
http://lmari.hatenablog.com/entry/selenium-fin
Do the following
#!pip install pandas-datareader
import pandas as pd
from pandas_datareader import data
stock = 'RENT3.SA'
source = 'yahoo'
# Set date range
start = datetime.datetime(2019, 8, 19)
end = datetime.datetime(2020, 11, 27)
# Collect stock data
dataset = data.DataReader(stock, source, start, end)
goog_df['Adj Close'].plot(kind='line', grid=True, title='RENT3 Adjusted Closes')

How can I save yahooquery results including dates?

I am using yahooquery to download historical data for APPL
When I print the results I can see there is the Date alongside the price. However when I download the result in a csv file the date is no longer available.
As I would need to also have the date for the price I am wondering if I am doing anything wrong and if so how can I fix it
from yahooquery import Ticker
import numpy as np
aapl = Ticker('APPL')
price = aapl.history(period='max')
np.savetxt('C:\APPL.csv', price)
Yahooquery uses multiple index, so you should reset it to single index.
Use
price = price.reset_index(level=[0,1])
This will tranform the symbol column into index and the date column into first column

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