0

i downloaded the information about multiple shares using nsepy library for the last 10 days, but could not save it in the pandas dataframe.

Below code to download the multiples share data:

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

symbol=['SBIN','GAIL','NATIONALUM' ]

data={}
for s in symbol:
    data[s]=get_history(s,start=date(2022, 11, 29),end=date(2022, 12, 12))

Below code using to convert the data to pd datafarme, but i am getting error

new = pd.DataFrame(data, index=[0])
  
new 

error message:

ValueError: Shape of passed values is (14, 3), indices imply (1, 3) 
user286076
  • 131
  • 3
  • 14

1 Answers1

0

Documentation of get_history sais:

Returns:
    pandas.DataFrame : A pandas dataframe object 

Thus, data is a dict with the symbol as keys and the pd.DataFrames as values. Then you are trying to insert a DataFrame inside of another DataFrame, that does not work. If you want to create a new MultiIndex Dataframe from the 3 existing DataFrames, you can do something like this:

result = {}
for df, symbol in zip(data.values(), data.keys()):
    data = df.to_dict()
    for key, value in data.items():
        result[(symbol, key)] = value
df_multi = pd.DataFrame(result)
df_multi.columns

Result (just showing two columns per Symbol to clarifying the Multiindex structure)

MultiIndex([(      'SBIN',             'Symbol'),
            (      'SBIN',             'Series'),
            (      'GAIL',             'Symbol'),
            (      'GAIL',             'Series'), 
            ('NATIONALUM',             'Symbol'),
            ('NATIONALUM',             'Series')

Edit

So if you just want a single index DF, like in your attached file with the symbols in a column, you can simply to this:

new_df = pd.DataFrame()
for symbol in data:
    # sequentally concat the DataFrames from your dict of DataFrames
    new_df = pd.concat([data[symbol], new_df],axis=0)
new_df

Then the output looks like in your file.

  • Hi, i want to append the multi-symbol in the pandas data frame, in this code all the sysmbols coming in columns direction but i want it to be in rows disrection, sample output file is attached in the below link https://drive.google.com/file/d/12poShdhEtDzqtKcJ4pLkpUth2DZ4iWYl/view?usp=share_link – user286076 Dec 12 '22 at 18:12
  • I'll edit my code :) – Frank Gallagher Dec 14 '22 at 16:54