I am trying to pull current price data for a list of stocks into a pandas dataframe. I am trying to pull the data using a loop into a dataframe in which the rows are the list items and the column is the current price. This loop keeps replacing all of the values in the Price column with the current price of the last stock in the list (JNJ 178.29). How do I fix this?
Input:
Target_Equities_List = ["MSFT",
"K",
"JNJ"]
Target_Frame = pd.DataFrame(index=Target_Equities_List)
for ticker in Equities_List:
yahoo_financials = YahooFinancials(ticker)
json_obj_price = yahoo_financials.get_stock_price_data()
current_price = json_obj_price[ticker]['regularMarketPrice']
Target_Frame["Price"] = current_price
Output:
Price
MSFT 178.29
K 178.29
JNJ 178.29
Thank you all!
CodePudding user response:
I think this question has yet an answer (I don't comment because I have no enough reputation)
Insert a row to pandas dataframe
CodePudding user response:
Because you're targeting the column name instead of index in the last bit of code. You should also declare the 'price' column in the beginning. Like below:
import pandas as pd
Target_Equities_List = ["MSFT",
"K",
"JNJ"]
prices = {'prices': [0,0,0]}
Target_Frame = pd.DataFrame(index=Target_Equities_List, data=prices)
print(Target_Frame)
OUTPUT:
prices
MSFT 0
K 0
JNJ 0
Process finished with exit code 0
Then to change the specific ticker target you use the loc function:
Target_Frame.loc[[ticker]] = 12345
That should work if your ticker format is exactly the same as the ones in the list you have: Here's an example with me manually overriding it:
Target_Frame.loc[['MSFT']] = 56.7
OUTPUT:
prices
MSFT 56.7
K 0.0
JNJ 0.0
Process finished with exit code 0