HomeData EngineeringData DIYHow To Efficiently Merge Stock Data in Python

How To Efficiently Merge Stock Data in Python

How To Efficiently Merge Stock Data in Python 2
The Adj. Close Prices of ten stocks merged in a single DataFrame
#The historical stock prices saved in adj_prices are passed to 
#reduce()to apply the merge function recursively from left to right

reduce(lambda x, y: pd.merge(x, y, left_index = True, right_index =
True, how=’outer’), adj_prices)
reduce(function, iterable [, initializer])

A Little Bit Of Theory

import functools
# Imports the full module and then use functools.reduce()

from functools import reduce
# Only imports reduce() from functools to use it directly
from functools import reduce

numbers = [7,2,5,9]def

 simple_prod(x,y):
 return x * y

reduce(simple_prod, numbers)

Output:
630
from functools import reduce

numbers = [7,2,5,9]

reduce(lambda x,y: x * y, numbers)

Output:
630

Put Theory Into Practice

import pandas as pd
import yfinance as yf
from functools import reduce

# Changes numeric fields format to include 2 digits only
pd.set_option('display.float_format', '{:.2f}'.format) 

tickers = ['AAPL', 'AMZN', 'BLK' ,'CSCO', 'FB', 'MSFT', 'NFLX', 'T', 'UBER' ,'ZM']

adj_prices = []
for i in range(len(tickers)):
    close_price = pd.DataFrame(yf.download(tickers[i])['Adj Close'].dropna(axis=0, how='any'))
    close_price = close_price.loc[~close_price.index.duplicated(keep='last')]
    close_price.columns = [tickers[i]]
    adj_prices.append(close_price)

df = reduce(lambda x, y: pd.merge(x, y, left_index = True, 
                                  right_index = True ,how='outer'), adj_prices)
df.sort_index(ascending = False, inplace = True)
df.index = pd.to_datetime(df.index ).date

df.head(5)
How To Efficiently Merge Stock Data in Python 3
Example of yf.download() function applied on AAPL.
How To Efficiently Merge Stock Data in Python 4
Single groups of prices appended to the adj_prices list

Conclusion

This article has been published from the source link without modifications to the text. Only the headline has been changed.

Source link

Most Popular