我有一个学校项目,我需要从Yahoo Finance获取历史数据,然后母鸡对此进行一些计算并编写报告。
import numpy as np
import csv
import pandas_datareader as pdr
def dataanalysis(stock1, comp1, comp2, comp3): # Function to download data from Yahoo
stk1 = pdr.get_data_yahoo(str(stock1), start="1999-11-01", end="2019-11-01") # Downloading 20 years of data
cmp1 = pdr.get_data_yahoo(str(comp1), start="1999-11-01", end="2019-11-01")
cmp2 = pdr.get_data_yahoo(str(comp2), start="1999-11-01", end="2019-11-01")
cmp3 = pdr.get_data_yahoo(str(comp3), start="1999-11-01", end="2019-11-01")
stk1.sort_index(ascending=False, inplace=True) # Put dem badboys in descending order
cmp1.sort_index(ascending=False, inplace=True)
cmp2.sort_index(ascending=False, inplace=True)
cmp3.sort_index(ascending=False, inplace=True)
stk1['Returns'] = (np.log(stk1['Close'] / stk1['Close'].shift(-1)))
cmp1['Returns'] = (np.log(cmp1['Close'] / cmp1['Close'].shift(-1)))
cmp2['Returns'] = (np.log(cmp2['Close'] / cmp2['Close'].shift(-1)))
cmp3['Returns'] = (np.log(cmp3['Close'] / cmp3['Close'].shift(-1)))
stk1.to_csv(str(stock1) + '.csv') # Out putting data to csv files
cmp1.to_csv(str(comp1) + '.csv')
cmp2.to_csv(str(comp2) + '.csv')
cmp3.to_csv(str(comp3) + '.csv')
stk1_returns = list(stk1['Returns']) # Creating a list from the 'Returns' column
cmp1_returns = list(cmp1['Returns'])
cmp2_returns = list(cmp2['Returns'])
cmp3_returns = list(cmp3['Returns'])
del stk1_returns[-1], cmp1_returns[-1], cmp2_returns[-1], cmp3_returns[-1]
stk1_ret_avg, cmp1_ret_avg, cmp2_ret_avg, cmp3_ret_avg = np.average(stk1_returns), np.average(cmp1_returns), np.average(cmp2_returns), np.average(cmp3_returns)
stk1_volit, cmp1_volit, cmp2_volit, cmp3_volit = np.std(stk1_returns), np.std(cmp1_returns), np.std(cmp2_returns), np.std(cmp3_returns)
tickers = ["", str(stock1), str(comp1), str(comp2), str(comp3)]
averages = ["Averages = ", stk1_ret_avg, cmp1_ret_avg, cmp2_ret_avg, cmp3_ret_avg]
volatility = ["Volatility = ", stk1_volit, cmp1_volit, cmp2_volit, cmp3_volit]
correlations = np.corrcoef([stk1_returns, cmp1_returns, cmp2_returns, cmp3_returns])
data_analyzed = [tickers, averages, volatility, correlations]
# print(data_analyzed)
return data_analyzed
def print_results(group):
ticker_list = list(group[0])
with open(str(ticker_list[1]) + " and Comp"".csv", "w") as group_anal:
groupCSV = csv.writer(group_anal)
for i in range(3):
groupCSV.writerow(group[i])
for i in range(2):
groupCSV.writerow([])
groupCSV.writerow(["Correlation Matrix"])
groupCSV.writerow(ticker_list[1:5])
for r in group[3]:
groupCSV.writerow(r)
group1 = dataanalysis("AAPL", "AMZN", "INTC", "MSFT") # Running the function
# group2 = dataanalysis("BARC.L", "BK", "GS", "DB")
group3 = dataanalysis("BRK-B", "ALL", "PGR", "MKL")
group4 = dataanalysis("MCD", "SBUX", "YUM", "WEN")
# group5 = dataanalysis("TSCO.L", "CA.PA", "SBRY.L", "WMT")
group6 = dataanalysis("WWE", "DISH", "DIS", "CMCSA")
print_results(group1)
# print_results(group2)
print_results(group3)
print_results(group4)
# print_results(group5)
print_results(group6)
这没有问题,但是如果我将其他注释掉的group2和5包括在内,则会出现以下错误:
File "C:/Users/HHF/OneDrive/Programming/Python/Assignments/Final Assignment/Financial Records/calculations.py", line 62, in <module>
group2 = dataanalysis("BARC.L", "BK", "GS", "DB")
File "C:/Users/HHF/OneDrive/Programming/Python/Assignments/Final Assignment/Financial Records/calculations.py", line 40, in dataanalysis
correlations = np.corrcoef([stk1_returns, cmp1_returns, cmp2_returns, cmp3_returns])
"TypeError: unsupported operand type(s) for /: 'list' and 'int'" error.
我已经尝试了所有我能想到的,但没有任何效果。如果我删除所有带有周期符号的股票行情指标,它会起作用,但是我不确定为什么会这样,因为如果我打印stk1_returns,它似乎是常规列表。
非常感谢您能给我的任何帮助。
答案 0 :(得分:0)
您传递给np.corrcoef
的一件事与您想像的不一样。
例如,这将引发相同的错误:
import numpy as np
np.corrcoef([[[1,2,3,4]], [4,5,6,7]])
请注意,第一个“数组”实际上是一个列表的列表。也许将stk1['Returns']
等投射到列表的地方出了问题。 (如果我是我,我会坚持使用数组。)