-2

Below code will get multiple stocks data into dictionary. But I need them into a single csv file

Code:

import pandas as pd
from datetime import datetime as dt
from nsepy import get_history

stocks = ['JSWSTEEL','RELIANCE','AXISBANK','HCLTECH','TECHM']
df = {}
for tickers in stocks:
    df[tickers] = get_history(tickers,dt(2020,1,1),dt(2021,1,1))
James Z
  • 12,209
  • 10
  • 24
  • 44
  • a quick search yields, is this what you want? https://stackoverflow.com/questions/16923281/writing-a-pandas-dataframe-to-csv-file – sg1234 Jun 19 '21 at 19:28
  • Does this answer your question? [Writing a pandas DataFrame to CSV file](https://stackoverflow.com/questions/16923281/writing-a-pandas-dataframe-to-csv-file) – Thomas Weller Jun 19 '21 at 19:29
  • 1
    The answer is "yes". There is a way and it wouldn't even be difficult if you attempted to do it yourself. You could always iterate over the dictionary and write the values to a CSV file. – Thomas Weller Jun 19 '21 at 19:31

1 Answers1

0

Use pandas to create a DataFrame out of the dict and then pandas.to_csv() function like this:

import pandas as pd
from datetime import datetime as dt
from nsepy import get_history

stocks = ['JSWSTEEL','RELIANCE','AXISBANK','HCLTECH','TECHM']
df = {}
for tickers in stocks:
    df[tickers] = get_history(tickers,dt(2020,1,1),dt(2021,1,1))

dataset = pd.DataFrame([df], index=[0])
csv_data = dataset.to_csv("your_file_path.csv")

Works beautifully!

Fredy
  • 1
  • 2