I created a list of stocks symbol in list symbol and tried to get data for each of the stock through yahoo and made csv files for each of the stocks containing daily price of stocks.
for ticker in symbol:
if not os.path.exists('F&OStocks/{}.csv'.format(ticker)):
df = web.DataReader(ticker+'.NS', 'yahoo', start, end)
df.reset_index(inplace=True)
df.set_index('Date', inplace=True)
df.to_csv('F&OStocks/{}.csv'.format(ticker))
else:
print('Already have {}'.format(ticker))
The above code worked completely fine and I was able to make csv file for each of the stocks. Next I am trying to make a new dataframe containing closing price of all the stocks by reading data from all th csv files. I used the code below to do it.
main_df = pd.DataFrame()
for ticker in symbol:
df = pd.read_csv('F&OStocks/{}.csv'.format(ticker))
df.set_index('Date', inplace=True)
df.rename(columns = {'Adj Cose': ticker}, inplace=True)
df.drop(['Open','High','Low','Close','Volume'], 1, inplace=True)
if main_df.empty:
main_df = df
else:
main_df.merge(df, how='outer')
print(main_df.head())
main_df.to_csv('F&Ostocks_joined_closes.csv')
I am only getting the closing price of the 1st company on the main_df and that to only with the head closing price ( as show on table below). All the columns are similar in each csv files. I also tried join instead of merge but it is still not working.
Date | Adj Close |
---|---|
2015-02-02 | 138.406876 |
2015-02-03 | 142.602432 |
2015-02-04 | 140.155045 |
2015-02-05 | 136.961731 |
2015-02-06 | 136.215836 |
Assumig all that is left in your dataframe is the adjusted close price after you dropped the others columns you could just convert df to a series and assign it to main_df in each loop:
if not df.empty:
main_df[ticker] = pd.Series(df)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.