从全局字典(长脚本)中提取数据帧



警告:长帖子。我尽了最大的努力把它分解成易于消化的东西,这样上帝的恩典就会有人帮助我。

堆栈的酷猫,看看吧,我正在构建一个有效的前沿工具,用于投资组合分析。通过直接从excel文件(df = pd.read_csv(foo.csv))调用数据,我有工具工作得很好。然而,现在我有数百个excel文件,可能很快就会有数千个,我想把它们一次加载到字典中,这样经过数十万次迭代将节省实时时间。

我编写了一个快速函数(如下)来将数据加载到全局字典中。这本字典似乎很好用。

equityLibrary = {}
def listFiles(path):
if os.path.isfile(path):
return[path]
else:
files = []
for filename in os.listdir(path):
files += listFiles(path + '/' + filename)
return files
def loadData():
##This function jsut lists the files in my data dir
library = listFiles('./data')

for stock in library:
startKeyName = stock[7:]
keyName = startKeyName[:-4]
variableName = keyName.lower()
df = readData(keyName)
equityLibrary[variableName] = df

好的,酷。数据帧被加载到一个全局字典中。现在,让我们获取必要的投资组合数据,我正在使用以下函数编译股票投资组合的波动性和回报率:

def PortfolioVolAndReturn(holdings, weights):
table = pd.DataFrame()
weights = np.array(weights)
for i in holdings:
df = equityLibrary[i.lower()]
table[i] = df.close
df.index = pd.to_datetime(df.index)
##Convert to log return eventually
dailyReturns = table.pct_change()
annualReturn = dailyReturns.mean() * 252
dailyCOVAR = dailyReturns.cov()
annualCOVAR = dailyCOVAR * 252
returnOut = np.dot(weights, annualReturn)
volOut = np.sqrt(np.dot(weights.T, np.dot(annualCOVAR, weights)))

return returnOut, volOut

##Return Sharp ratio
def sharpeRatio(vol, returns):
return returns/vol

工作! !…但只有一次。这里是核心问题:当我在蒙特卡罗模拟中运行它时,我返回的dataFrame有一个正确的行,而所有其他的dataFrame都返回所有列的NaN值。我使用这个函数来运行模拟:

##takes in number of simulations for 
def runSim(holdings, simulations):
weightsArray = []
returnsArray = []
volArray = []
df = pd.DataFrame()
for i in range(simulations):
weights = np.random.rand(len(holdings))
weights /= np.sum(weights)
returns, vol = PortfolioVolAndReturn(holdings, weights)
weightsArray.append(weights)
returnsArray.append(returns)
volArray.append(vol)

df['weights'] = weightsArray
df['return'] = returnsArray
df['vol'] = volArray
return df

My return is broken:

weights    return      vol
0   [0.047066195990327415, 0.27999255422401625, 0....  0.269764  0.35462
1   [0.6172192455260814, 0.08842975803644981, 0.29...       NaN      NaN
2   [0.3610819481882519, 0.5059521988331586, 0.132...       NaN      NaN
3   [0.01626716037860542, 0.16093554050483386, 0.8...       NaN      NaN

我知道问题出在全局字典。如果我直接从csv文件中调用数据帧,这很好,但速度很慢。我一辈子也弄不明白为什么我的字典在第二次打电话后就会输入废话。我做错了什么,为什么我不够聪明,不能发现它?

更新:问题在于Function PortfolioVolAndReturn。无论holding参数是长是短,最后一列都作为NaN附加到数据帧。例子:

CSCO   INTC  CAT
0     26.84  34.23  NaN
1     26.52  34.47  NaN
2     26.15  34.19  NaN

CSCO   INTC     CAT  JPM
0     26.84  34.23   69.24  NaN
1     26.52  34.47   69.22  NaN
2     26.15  34.19   68.25  NaN

这对我来说完全没有意义。运行代码,我不知道是什么导致的。我没有正确地遍历字典吗?我觉得一切都是合乎逻辑的,数据帧不应该被错误地拉。O_o

好吧,休息一下回来后,我使用另一个函数调用使一切运行得相当顺利:

def closingPriceTable(holdings):
table = pd.DataFrame()
for i in holdings:
df = equityLibrary[i.lower()]
table[i] = df.close

return table

仍然不知道为什么我原来的呼叫不起作用。我真的不介意有人看看,让我知道我做了什么蠢事。

最新更新