0

I would like to save the output from the following Python loop to CSV

ticker_list = ['GBX', 'AYI', 'SMPL', 'BSET']

from yahoofinancials import YahooFinancials as yf

yahoo_financials = yf(ticker_list)

price = yahoo_financials.get_historical_price_data('2019-07-02', '2019-07-02', 'daily')

df = pd.DataFrame(price)


def get_price():
    df1 = pd.DataFrame()
    for i in ticker_list:
        df1_i = pd.DataFrame(df[i]['prices'])
        df1_i['ticker'] = i
        df1 = df1.append(df1_i)

    df1.to_csv(r'price_20190702.csv')

I want to save the price info for all four tickers to a single CSV file. However, when I call def get_price(), no CSV file is saved.

5
  • 2
    Did you mean df1.to_csv(r'price_20190702.csv')? Commented Sep 25, 2019 at 13:23
  • Can you show sample output data? Commented Sep 25, 2019 at 13:39
  • Yes, I meant df1.to_csv(r'price_20190702.csv') Commented Sep 25, 2019 at 13:52
  • Can you be kindly more specific about using an array? Thanks. Commented Sep 25, 2019 at 13:53
  • adjclose close date formatted_date high low open volume ticker 0 30.141232 30.400000 1561728600 2019-06-28 30.600000 29.370001 29.379999 874200 GBX Commented Sep 25, 2019 at 13:54

2 Answers 2

1

You can append dataframes:

import pandas as pd
from yahoofinancials import YahooFinancials as yf

TICKER_LIST = ['GBX', 'AYI', 'SMPL', 'BSET']
yahoo_financials = yf(TICKER_LIST)
price = yahoo_financials.get_historical_price_data('2019-07-02', '2019-07-02', 'daily')

df = pd.DataFrame()
for t in TICKER_LIST:
    df = df.append(price[t], ignore_index=True)
df.to_csv('price_20190702.csv', index=False)

Output:

eventsData,firstTradeDate,id,isPending,prices,timeZone
{},"{'formatted_date': '1994-07-14', 'date': 774172800}",1d15620256001562025600,0.0,[],{'gmtOffset': -14400}
{},"{'formatted_date': '2001-12-03', 'date': 1007370000}",1d15620256001562025600,0.0,[],{'gmtOffset': -14400}
{},"{'formatted_date': '2017-07-05', 'date': 1499241600}",1d15620256001562025600,0.0,[],{'gmtOffset': -14400}
{},"{'formatted_date': '1980-03-17', 'date': 322131600}",1d15620256001562025600,0.0,[],{'gmtOffset': -14400}
Sign up to request clarification or add additional context in comments.

Comments

1

You can use with open

For Example:

while True:
   data = 'Changes every time'
   with open('t.csv','a') as f:
      wr = csv.writer(f)
      wr.writerow(data)

1 Comment

Thank you very much for your suggestion!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.