我想写一个script
,它会经历txt-file
中的每个股票代码,并通过googlefinance
运行以收集其所有历史数据并将其输出到CSV-file
。我知道这应该不是那么困难,但我似乎无法弄清楚我在这段代码中做错了什么。它适用于第一支股票,然后崩溃。我有一个假设,它与\n
有关,但我尝试了splitlines()
函数和其他一些东西。如何让脚本遍历每一行txt文件并执行一个函数?
我的代码:
import datetime as dt
import matplotlib.pyplot as plt
from matplotlib import style
from matplotlib.finance import candlestick_ohlc
import matplotlib.dates as mdates
import pandas as pd
import pandas_datareader.data as web
from googlefinance import getQuotes
import json
from datetime import datetime
from forex_python.converter import CurrencyRates
from yahoo_finance import Share
sp500 = open('sp500tickers.txt').read().splitlines()
for x in sp500:
share = Share(sp500[x])
print (share.get_price())
start = dt.datetime(2001,1,1)
end = dt.datetime(2017,1,1)
df = web.DataReader(share, 'google', start, end)
df.to_csv(''+x+'.csv', parse_dates=True, index_col=0)
文本文件:
MMM
ABT
ABBV
ACN
ATVI
AYI
ADBE
AAP
AES
AET
AMG
AFL
A
APD
AKAM
ALK
ALB
ALXN
ALLE
AGN
ADS
LNT
ALL
GOOGL
GOOG
MO
AMZN
AEE
AAL
...
编辑的代码:
with open('p1.txt', 'r') as f:
for line in f:
line = line.rstrip()
share = Share(line)
style.use('ggplot')
print (share.get_price())
start = dt.datetime(2001,1,1)
end = dt.datetime(2017,1,1)
df = web.DataReader(share, 'google', start, end)
df.to_csv(''+line+'.csv', parse_dates=True, index_col=0)
由于您已经在使用'pandas',为什么不使用'pd.read_csv()'? –
含义...?将我的代号列表变成csv然后运行它?我最终会遇到同样的问题。 – sgerbhctim
您的tickers列表是一个txt文件。一个txt文件可以通过'read_csv()'导入。你已经在构建价格的数据框,所以我不明白为什么要多步完成。 –