Stock prices and comparison - python

I parsed a html table for financial transactions and have 3 different lists:
1. DATE
2. TICKER
3. MOTHER COMPANY
I would like to populate a stock prices for stocks from my TICKER list for a maximum possible period
I am new to python and cant figure out how to get the data for the stocks from my TICKER list... Any guidance would be of great help
Many thanks in advance
TICKERS
['OSR', 'NWSA', 'MNK', 'ZTS', 'FNAC', 'WWAV', 'NRZ', 'CST', 'BPY', 'ERA', 'AXLL', 'LMCAD', 'ABBV']
I am trying with a simple code but cant get through:
import yfinance as yf
for ticker in tickers:
data = yf.download(ticker, period="max")

The download function in yfinance accepts a list of tickers separated by spaces.
In order to download the data for all your tickers for a max period simply call it this way.
For example, if you want to download the data for 'OSR', 'NWA' and 'MNK':
import yfinance as yf
tickers = 'OSR NWA MNK'
data = yf.download(tickers, period='max')
You can then access each ticker's data using data[ticker].
If you have your tickers as a list and want to convert to a space-delimited string use join:
ticker_list = ['OSR', 'NWA', 'MNK']
ticker_str = ' '.join(ticker_list)

Related

How to convert a string to a variable / list name?

I have a list of stock indexes (indizies) and several lists of stock tickers (e.g. gdaxi, mdaxi).
I want to download the stocks from yahoo in two loops.
Background: In the real program the user can choose which index, indexes he wants to download.
The problem is, that the type of index_name is a string and for the second loop index_name has to be a list. But the second loop takes index_name as a string.
Result :It trys to download the csv for g,d,a,x,i
Question: How can I transform index_name from string to list?
from pandas_datareader import data as pdr
indizies = ['GDAXI', 'MDAXI']
gdaxi = ["ADS.DE", "AIR.DE", "ALV.DE"]
mdaxi = ["AIXA.DE", "AT1.DE"]
for index_name in indizies:
for ticker in index_name:
df = pdr.get_data_yahoo(ticker)
df.to_csv(f'{ticker}.csv')
In ticker in index_name you are iterating over the letters in given strings.
I guess you to change your code to something like:
from pandas_datareader import data as pdr
gdaxi = ["ADS.DE", "AIR.DE", "ALV.DE"]
mdaxi = ["AIXA.DE", "AT1.DE"]
indizies = [gdaxi, mdaxi]
for index_name in indizies:
for ticker in index_name:
df = pdr.get_data_yahoo(ticker)
df.to_csv(f'{ticker}.csv')```

Get historical stock data with delisted tickers

I need to get historical stock data of S&P 500 including delisted tickers for backtesting in Python.
I tried to parse wiki (https://en.wikipedia.org/wiki/List_of_S%26P_500_companies), then download data
yf.download(delisted_tickers)
but i can't get big part of data because of that error
No data found, symbol may be delisted
So, are there other methods to get all data?
"Only Premium Plus members can view delisted company data"
Source : https://finance.yahoo.com/news/premium-plus-feature-historical-financial-201155209.html
im pretty sure yfinance only pulls stock data of current stocks, but you can give it a time frame, for example:
# Define the ticker list
import pandas as pd
tickers_list = ['AAPL', 'WMT', 'IBM', 'MU', 'BA', 'AXP']
# Fetch the data
import yfinance as yf
data = yf.download(tickers_list,'2015-1-1')['Adj Close']
# Print first 5 rows of the data
print(data.head())

yfinance api return multiple ticker data

I am trying to pull out multiple ticker data from the yfinance API and save it to a csv file (in total I have 1000 tickers I need to get the data for, that data being the entire table of date, open, high, low, close, volume, etc etc), so far I am able to successfully get data for 1 ticker by using the following Python code:
import yfinance as yf
def yfinance(ticker_symbol):
ticker_data = yf.Ticker(ticker_symbol)
tickerDF = ticker_data.history(period='1d', start='2020-09-30', end='2020-10-31')
print(tickerDF)
yfinance('000001.SS')
However if I try on multiple tickers this doesn't work. Following the yfinance docs which say for multiple tickers use:
tickers = yf.Tickers('msft aapl goog')
# ^ returns a named tuple of Ticker objects
# access each ticker using (example)
tickers.tickers.MSFT.info
tickers.tickers.AAPL.history(period="1mo")
tickers.tickers.GOOG.actions
I have a couple of issue here, the docs use a string such as 'aapl' my tickers are all of digit format like '000001.SS', the ".SS" part is proving to be an issue when passing it into the code:
tickers.tickers.000001.SS.history(period="1mo")
# Clearly this wont for for a start
The next issue I am having is, even if I pass in for example 3 tickers to my function like so:
yfinance('000001.SS 000050.KS 00006.KS')
# similar to yfinance docs of tickers = yf.Tickers('msft aapl goog')
I get errors like:
AttributeError: 'Tickers' object has no attribute '000001.SS'
(I have also tried to run these into a for loop and pass each on to the Tickers object but get the same error.)
Im stuck now, I dont know how to pass in multiple tickers to yfinance and get back data that I want and the docs aren't very helpful.
Is anyone able to help me with this?
Could you not just store them in an array specifying the type as dtype object then use that pull the data from.
import yfinance as yf
import numpy as np
tickers = ['msft', 'aapl', 'goog']
totalPortfolio = np.empty([len(tickers)], dtype=object)
num = 0
for ticker in tickers:
totalPortfolio[num] = yf.download(ticker, start='2020-09-30', end='2020-10-31', interval="1d")
num = num + 1
Take a look at the code below:
test = yf.Tickers("A B C")
# creates test as a yf.tickers object
test_dict = test.tickers
# creates a dict object containing the individual tickers. Can be checked with type()
You are trying to use "tickers.tickers.MSFT.info" to retrieve the ticker data from your dictionary "tickers.tickers" but like your error message says, a dict object has no attributes named after your specific ticker names. This is in general not how you access elements in a dictionary.
Instead you should use the code as below (like with all dict objects):
#old code from above
test = yf.Tickers("A B C")
test_dict = test.tickers
#new code accessing the dict correctly
a_data = test_dict["A"]
a_data = test.tickers["A"] #does the same as the line above
b_data = test.tickers["B"] #and so on for the other tickers
In a loop this could look something like this:
ticker_list = ["A", "B", "C"] #add tickers as needed
tickers_data = {}
tickers_history = {}
for ticker in ticker_list:
tickers_data[ticker] = yf.Ticker(ticker)
tickers_history = tickers_data[ticker].history(period='1d', start='2020-09-30', end='2020-10-31')
#access the dicts as needed using tickers_data[" your ticker name "]
alternatively you can also use the "yf.Tickers" function to retrieve multiple tickers at once, but because you save the history seperately I don't think this will necessarily improve your code much.
You should pay attention however, that "yf.Ticker()" and "yf.Tickers()" are different functions from each other with differing syntax and are not interchangeable.
You did mix that up when you tried accessing multiple tickers with your custom "yfinance()" function, that has been previously defined with the "yf.Ticker()" function and thus only accepts one symbol at a time.

Get closing stock prices for yesterday for multiple stocks

I'm trying to get yesterday's closing stock prices for all stocks listed on the BSE using https://www.quandl.com/data/BSE-Bombay-Stock-Exchange as the data source. I have a list of company codes that I can use to pull that data but I need to figure out how to iterate over it correctly.
According to the quandl documentation, I can use quandl.get('BSE/BOM500002', column_index = '4', start_date='2019-03-19', end_date='2019-03-20') to get yesterday's closing price for a stock where BOM500002 would be the company code. If my list of company codes is listed in companyCodes['code'], could you help me figure out how to generate the company code dynamically to get yesterday's closing stock prices for all stocks listed on this exchange?
Bonus Question: How would I list the name of the stock next to the closing price?
Here is way to get date name together with the results:
import quandl
df = pd.DataFrame([("BOM500002", "ABB India Limited"),("BOM500003", "AEGIS")], columns=["Code", "Name"])
results = []
for i, r in df.iterrows():
result = quandl.get('BSE/'+r["Code"], column_index = '4', start_date='2019-03-19', end_date='2019-03-20')
result["Name"] = r["Name"]
results.append(result)
final = pd.concat(results)
Give this a try.
import quandl
quandl.ApiConfig.api_key = 'your quandl code'
stocks = [
'BSE/BOM533171',
'BSE/BOM500002'
]
mydata = quandl.get(stocks, start_date = '2019-03-19', end_date='2019-03-21')
mydata.loc[:,(mydata.columns.str.contains('Close'))].T

Some ETF Tickers Not Working in Yahoo Finance DataReader

I'm gathering data from a bunch of ETFs through Yahoo Finance using Pandas-Datareader and I'm getting odd errors with a handful of the tickers even though the data seems available. The code is very simple:
start = datetime.datetime(2010, 1, 1)
end = datetime.datetime(2017,1,1)
for ticker in TICKERS:
f = dr.DataReader(ticker, 'yahoo', start, end)
and works for most of my tickers but not all:
EMLP GDVD (Failed to get data for GDVD) AMZA RFDI ARKK ARKW SECT (Failed to get data for SECT)
EMLP works fine. Datareader produces urls like this url for GDVD even though the historical data for GDVD is available on the website. I see the following error in Chrome using the GDVD url:
{"finance": {"error": {"code": "Unauthorized","description": "Invalid cookie"}}}
Is there a way to get historical prices for these tickers? The full list of failed tickers in case anyone can see a pattern:
['GDVD', 'SECT', 'DWLD', 'CCOR', 'DFNL', 'DUSA', 'AIEQ', 'CACG', 'QSY', 'ACT', 'TAXR', 'TTAI', 'FLIO', 'FMDG', 'VGFO', 'FFSG', 'LRGE', 'YLDE', 'VESH', 'DEMS', 'SQZZ']
Using the yahoo_fin package, I was able to get the data for the tickers you listed. Check out this link: http://theautomatic.net/yahoo_fin-documentation/.
My code looks like this:
from yahoo_fin.stock_info import get_data
tickers = ['GDVD', 'SECT', 'DWLD', 'CCOR', 'DFNL', 'DUSA', 'AIEQ', 'CACG',
'QSY', 'ACT', 'TAXR', 'TTAI', 'FLIO', 'FMDG', 'VGFO', 'FFSG',
'LRGE', 'YLDE', 'VESH', 'DEMS', 'SQZZ']
stocks = {}
for ticker in tickers:
stocks[ticker] = get_data(ticker)
So the data gets stored into a dictionary, where the keys are the tickers, and the values are the data frames containing each stock's data.
Alternatively, you could use a dictionary comprehension, like this:
stocks = {ticker : get_data(ticker) for ticker in tickers}
If you want to collapse all of the data sets into a single data frame, you could use the functools package like this:
from functools import reduce
combined = reduce(lambda x,y: x.append(y), stocks.values())

Categories

Resources