0

When I import more than one stock in yahoo finance I get a multindex. I'm trying to export as an csv file and them import the same dataset with the same indexes. I tried to use index = False in .to_csv method but it drops the row index, which is something that I don't want.

Basically I can't find a way to make stocks_sample_csv have the same index as stocks_sample.

import pandas as pd
from datetime import date
import yfinance as yf

list_symbols = ["CERS", "CERU", "CETV", "CEVA", "CFA", "CFBK",
                "CFFI", "CFFN", "CFGE", "CFNB", "CFNL", "CFO",
                "CFRX", "CFRXW", "CFRXZ", "CG", "CGEN", "CGIX",
                "CGNX", "CGO", "CHCI", "CHCO", "CHDN", "CHEF",
                "CHEV", "CHFC", "CHFN", "CHI", "CHKE", "CHKP", 
                "CHLN", "CHMG", "CHNR", "CHOP", "CHRS", "CHRW",
                "CHSCM", "CHSCN", "CHSCO", "CHSCP"]
start = date(2017, 10, 1)
end = date(2020, 6, 25)

stocks_sample = yf.download(list_symbols, start, end, group_by='ticker')

#for checking 
print(stocks_sample)
stocks_sample.columns.levels[0]
stocks_sample.columns.levels[1]

stocks_sample.to_csv('stocks_sample.csv')
stocks_sample_csv = pd.read_csv('stocks_sample.csv')

#now check the imported .csv file
print(stocks_sample_csv)
stocks_sample_csv.columns.levels[0]
stocks_sample_csv.columns.levels[1]

By the way, I'm doing this so I don't need to donwload everytime I open my python console.

Any help would be greatly appreciated.

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Artur Dutra
  • 515
  • 3
  • 18

1 Answers1

1

Try the following changes-

stocks_sample = stocks_sample.reset_index() #will create the multi index as separate columns
stocks_sample.to_csv('stocks_sample.csv')

#while importing 
stocks_sample_csv = pd.read_csv('stocks_sample.csv')
stocks_sample_csv.set_index(['index0', 'index1']) #change the list to the list of columns which contain the previous indexes.

Akshay Sehgal
  • 18,741
  • 3
  • 21
  • 51