这小段代码给我带来了不必要的麻烦。如果可以的话,我将不胜感激。预先感谢您为我研究一下。
我试图对之前的22个数据点的价格和交易量进行总结,我添加了一个名为dtt的列来保存该值。
我要在这里表示的公式是:
vamp = [sum(1, dtt) price * volume] / [sum(1,dtt) volume]
这是我的代码
# Import necessary libraries
import numpy as np
import pandas as pd
import os
# Load SPY dataset
spy_data = pd.read_csv('SPY.csv', parse_dates=['Date'])
# Compute Daily Return
spy_data['daily_ret'] = (spy_data['Adj Close'] - (spy_data['Adj Close']).shift(1)) / ((spy_data['Adj Close']).shift(1)) * 100
spy_data['daily_ret'] = spy_data['daily_ret'].fillna(0.0)
# calculate Annualized Volatility
rsquare = (spy_data['daily_ret']) ** 2
spy_data['annualized_volatility']=(np.sqrt(rsquare.rolling(252).sum() / 251) * np.sqrt(252))
spy_data['annualized_volatility'] = spy_data['annualized_volatility'].fillna(0)
spy_shares = 889112600
# Calculate Days to Trade
spy_data['dtt'] = spy_shares / (spy_data['Volume'].rolling(22).sum()/22)
spy_data['dtt'] = spy_data['dtt'].fillna(1).astype(int)
# Calculate VWAP
#numerator is equal to the sum of the price * volume of the latest DTT
numerator = spy_data.loc[0:spy_data['dtt'], 'Adj Close'].sum()#*spy_data.loc[0:spy_data['dtt'], 'Volume']
#denominator = spy_data.loc[0:spy_data['dtt'], 'Volume']
#spy_data['vwap'] = numerator / denominator
print(spy_data)
我注释了其他几行,因为我一次尝试一步解决问题。我需要的价格列是Adj Close
。
无论我尝试切片如何,我都会不断出错。这是当前的一个:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-68-ade975138e12> in <module>
7 # Calculate VWAP
8 #numerator is equal to the sum of the price * volume of the latest DTT
----> 9 numerator = spy_data.loc[0:spy_data['dtt']].sum()#*spy_data[0:spy_data['dtt'], 'volume']
10 #denominator = spy_data.loc[0:spy_data['dtt'], 'Volume']
11 #spy_data['vwap'] = numerator / denominator
~/.local/lib/python3.6/site-packages/pandas/core/indexing.py in __getitem__(self, key)
1408
1409 maybe_callable = com.apply_if_callable(key, self.obj)
-> 1410 return self._getitem_axis(maybe_callable, axis=axis)
1411
1412 def _is_scalar_access(self, key: Tuple):
~/.local/lib/python3.6/site-packages/pandas/core/indexing.py in _getitem_axis(self, key, axis)
1770 if isinstance(key, slice):
1771 self._validate_key(key, axis)
-> 1772 return self._get_slice_axis(key, axis=axis)
1773 elif com.is_bool_indexer(key):
1774 return self._getbool_axis(key, axis=axis)
~/.local/lib/python3.6/site-packages/pandas/core/indexing.py in _get_slice_axis(self, slice_obj, axis)
1438 labels = obj._get_axis(axis)
1439 indexer = labels.slice_indexer(
-> 1440 slice_obj.start, slice_obj.stop, slice_obj.step, kind=self.name
1441 )
1442
~/.local/lib/python3.6/site-packages/pandas/core/indexes/base.py in slice_indexer(self, start, end, step, kind)
5025 slice(1, 3)
5026 """
-> 5027 start_slice, end_slice = self.slice_locs(start, end, step=step, kind=kind)
5028
5029 # return a slice
~/.local/lib/python3.6/site-packages/pandas/core/indexes/base.py in slice_locs(self, start, end, step, kind)
5245 end_slice = None
5246 if end is not None:
-> 5247 end_slice = self.get_slice_bound(end, "right", kind)
5248 if end_slice is None:
5249 end_slice = len(self)
~/.local/lib/python3.6/site-packages/pandas/core/indexes/base.py in get_slice_bound(self, label, side, kind)
5155 # we need to look up the label
5156 try:
-> 5157 slc = self.get_loc(label)
5158 except KeyError as err:
5159 try:
~/.local/lib/python3.6/site-packages/pandas/core/indexes/range.py in get_loc(self, key, method, tolerance)
377 except ValueError:
378 raise KeyError(key)
--> 379 return super().get_loc(key, method=method, tolerance=tolerance)
380
381 @Appender(_index_shared_docs["get_indexer"])
~/.local/lib/python3.6/site-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
2888 )
2889 try:
-> 2890 return self._engine.get_loc(key)
2891 except KeyError:
2892 return self._engine.get_loc(self._maybe_cast_indexer(key))
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
TypeError: '0 1
1 1
2 1
3 1
4 1
..
4694 9
4695 9
4696 10
4697 10
4698 11
Name: dtt, Length: 4699, dtype: int64' is an invalid key