我想将以下Python循环的输出保存为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')
我想将所有四个股票的价格信息保存到一个CSV文件中。但是,当我呼叫def get_price()
时,没有保存CSV文件。
答案 0 :(得分:0)
您可以附加数据框:
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)
输出:
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}
答案 1 :(得分:0)
可以与open一起使用
例如:
while True:
data = 'Changes every time'
with open('t.csv','a') as f:
wr = csv.writer(f)
wr.writerow(data)