I show below a script that imports historical quotes of different stocks from Yahoo, using 'pandas_datareader' .
# 1 - Define `tickers` & `company names` for every instrument
stocks = {'AAPL':'Apple', 'MSFT':'Microsoft', 'AMZN' : 'Amazon', 'GOOG': 'Google', 'FB':'Facebook','NFLX':'Netflix' , 'NVDA' : 'NVIDIA'}
bonds = {'HCA' : 'HCA', 'VRTX' : 'VRTX'}
commodities = {'BTC-USD' : 'Bitcoin', 'PA=F' : 'Palladium'}
instruments = {**stocks, **bonds, **commodities}
tickers = list(instruments.keys())
instruments_data = {}
N = len(tickers)
# 2 - We will look at stock prices over the past years, starting at January 1, 2015
# 01-01-2015 - 16-04-2020
start = datetime.datetime(2015,1,1)
end = datetime.datetime(2020,4,16)
# 3 - Let's get instruments data based on the tickers.
# First argument is the series we want, second is the source ("yahoo" for Yahoo! Finance), third is the start date, fourth is the end date
for ticker, instrument in instruments.items():
print("Loading data series for instrument {} with ticker = {}".format(instruments[ticker], ticker))
instruments_data[ticker] = web.DataReader(ticker, data_source = 'yahoo', start = start, end = end)
The statement instruments = {**stocks, **bonds, **commodities}
, I guess creates a dictionary with three dictionaries. I don't understand what function the two '**' have. I will be grateful if you explain this sentence to me.
Thanks to this python treats what you give it as a key-value, with this it copies the dictionary with key-value into the new dictionary.
Having the following dictionaries:
Example:
The part of your code:
This shows the following dictionary (All dictionaries in one):
However, if you put only an asterisk (*) it copies only the key.
Examples (Using the dictionaries from before):
Returns the following set (The keys of all dictionaries in a set):
And this other example:
Return the following tuple (The keys of all dictionaries in one tuple):
And finally:
Show the following list (The keys of all the dictionaries in a list):
I would like to add that the two asterisks ** mean an arbitrary number of arguments.
They are useful when a function can take an arbitrary/unknown number of arguments. It turns those variables into a dictionary, effectively, and the function can verify that a certain variable was entered by checking the curly braces.
Functions that take an arbitrary number of arguments are useful when you are processing texts of arbitrary size/length. Each word is being tagged with semantic or grammatical information, for example, to process the sentiment of a comment.
It is worth noting that already in python3.9 this statement
can be reformulated:
I see it as more readable, what programming should be.