2015-09-13 44 views
0

我有以下代码可以帮助我为工作表中存储的多个股票提供日常数据。我希望完成的是将日常数据返回并存储在另一个工作表中。如何使用python将数据写入excel从雅​​虎提取股票数据

我正在努力编写完成此任务的代码。目前,我能够为每只个股提取数据,但我无法存储这些信息。任何帮助将不胜感激。为了测试,我只尝试存储打开和关闭,理想情况下我希望存储来自雅虎财务的所有参数。

import numpy as np 
import pandas as pd 
import xlsxwriter 


df=pd.read_csv('Stock Companies Modified.csv', sep=',',header=True) 
df.columns = ['StockSymbol', 'CompanyName', 'ClosingPrice', 'MarketCap', 'IPOYear', 'Sector', 'Industry'] 

workbook = xlsxwriter.Workbook('New Workbook.xlsx') 
worksheet = workbook.add_worksheet() 

df = df.convert_objects(convert_numeric=True) 
df.dtypes 

from pandas.io.data import DataReader 
from datetime import datetime 
for x in df.StockSymbol: 
    if len(x)<=4: 
     ClosingPrice = DataReader(x, 'yahoo', datetime(2015,1,1), datetime(2015,7,1)) 

     row = 0 
     col = 0 
     #This is the area where I am getting an error, and to be honest I dont know how to do it correctly 

     for Open, Close in (ClosingPrice): 
      worksheet.write(row, col, (ClosingPrice['Open'])) 
      worksheet.write(row,col+1,(ClosingPrice['Close'])) 
      row+=1 

      workbook.close() 

     print x 
    else: 
     print("This is not working") 
+0

见http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame .to_excel.html –

+0

我能够使用您提供的链接使其工作,感谢您指引我在正确的方向! – Raptor776

回答

1

我还没有找到一个干净的方式将数据追加到与xlsxwriter片,所以通常我创建的所有值的临时数据帧,以及当前的表,如果现有的 - 然后覆盖。我肯定会更喜欢,如果我们可以追加到床单,但你似乎不可能。

import pandas as pd 
from pandas.io.data import DataReader 
from datetime import datetime 

symbols = ['GOOG','AAPL'] 

try: 
    df = pd.read_excel('NewFile.xlsx') 
except: 
    df = pd.DataFrame() 

for symbol in symbols: 
    ClosingPrice = DataReader(symbol, 'yahoo', datetime(2015,1,1), datetime(2015,9,1)) 
    ClosingPrice = ClosingPrice.reset_index() 
    ClosingPrice['Symbol'] = symbol 
    df = df.append(ClosingPrice) 

writer = pd.ExcelWriter('NewFile.xlsx', engine='xlsxwriter') 
df.to_excel(writer,sheet_name='Sheet1',index=False) 
writer.save() 

如果您后来追加到同一个文件,这将是确定:

df = pd.read_excel('NewFile.xlsx') 
symbols = ['G'] 

for symbol in symbols: 
    ClosingPrice = DataReader(symbol, 'yahoo', datetime(2015,1,1), datetime(2015,9,1)) 
    ClosingPrice = ClosingPrice.reset_index() 
    ClosingPrice['Symbol'] = symbol 
    df = df.append(ClosingPrice) 

writer = pd.ExcelWriter('NewFile.xlsx', engine='xlsxwriter') 
df.to_excel(writer,sheet_name='Sheet1',index=False) 
writer.save() 
+0

这是一个非常方便的解决方法,谢谢你!! – Raptor776

+0

@ Raptor776没问题! – ryanmc

相关问题