简体   繁体   English

如何更新而不是用python用python重写csv以获取股票数据?

[英]How to update instead of rewriting csv by python with pandas to fetch stock data?

I am an absolute noob in terms of programming. 就编程而言,我绝对是菜鸟。
I wish to fetch historical data of a list of stock from yahoo for data analysis. 我希望从雅虎获取股票清单的历史数据以进行数据分析。
I modified the script I found and got this. 我修改了找到的脚本并得到了它。

#settings for importing built-in datetime and date libraries
#and external pandas_datareader libraries

import pandas_datareader.data as web
import datetime
from datetime import timedelta


#read ticker symbols from a file to python symbol list
symbol = []
with open('E:\Google drive\Investment\Python Stock pick\Stocklist1.txt') as f:  
    for line in f:
        symbol.append(line.strip())
f.close

end = datetime.datetime.today()

start = end - timedelta(days=400)

#set path for csv file
path_out = 'E:/Google drive/Investment/Python Stock pick/CSV/'


i=0
while i<len(symbol):
    try:
        df = web.DataReader(symbol[i], 'yahoo', start, end)
        df.insert(0,'Symbol',symbol[i])
        df = df.drop(['Adj Close'], axis=1)
        if i == 0:
            df.to_csv(path_out+symbol[i]+'.csv')
            print (i, symbol[i],'has data stored to csv file')
        else:
            df.to_csv(path_out+symbol[i]+'.csv',header=True)
            print (i, symbol[i],'has data stored to csv file')
    except:
        print("No information for ticker # and symbol:")
        print (i,symbol[i])
        i=i+1
        continue
    i=i+1

And I run the script everyday and it fetches stock data in the past. 而且我每天都运行脚本,并且该脚本过去会获取库存数据。
It would replace the entire csv file and always replacing the old data with the new one. 它将替换整个csv文件,并始终将旧数据替换为新数据。

Is there anyway for the script to just add the new data into the csv file? 无论如何,脚本仅将新数据添加到csv文件中?

Thanks a lot in advance. 非常感谢。 I am all new to the programming world and have no idea how to do this. 我是编程界的新手,不知道如何执行此操作。

I think you need to add 'a+' instead. 我认为您需要添加“ a +”来代替。 Otherwise the file will keep looping itself. 否则文件将继续循环播放。 It is what happened to me. 这是发生在我身上的事情。

You have to add param 'a': 您必须添加参数“ a”:

with open('E:\Google drive\Investment\PythonStockpic\Stocklist1.txt','a') as f:
    f.write(line.strip())

see: append new row to old csv file python 请参阅: 将新行附加到旧的csv文件python

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM