TypeError:无法使用<class'int'>

2024-05-19 09:15:57 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,我试图制作一个使用MFI和交易量的交易算法。到目前为止,代码如下:

import pandas as pd
import numpy as np
import pandas_datareader as web
import datetime as dt
import matplotlib.pyplot as plt
from matplotlib import style

    #get stock prices
    start = dt.datetime(2017, 1, 1)
    end = dt.datetime(2020, 1, 1)
    d = web.DataReader('AMD', 'yahoo', start, end)
    pd.set_option('display.max_rows', 1000)
    pd.set_option('display.max_columns', 1000)

    #MOVING AVERAGES
    d['20_sma'] = d['Adj Close'].rolling(window=20).mean()
    d['50_sma'] = d['Adj Close'].rolling(window=50).mean()
    d['20_va'] = d['Volume'].rolling(window=20).mean()

    #MONEY FLOW INDEX
    d['typical_price'] = (d['High'] + d['Low'] + d['Close'])/3 
    d['raw_money_flow'] = d['typical_price']
    mf = d.raw_money_flow.diff(1) 
    p = mf.copy()
    n = mf.copy()
    p[p<=0] = 0
    n[n>0] = 0
    pmf = p.rolling(window=14).mean()
    nmf = abs(n.rolling(window=14).mean())
    mfr = pmf / nmf
    d['mfi'] = 100 - (100 / (mfr +1))
    d['mfi'].dropna(inplace=True)

    #Rules
    #trends
    d['up_trend'] = np.where(d['20_sma'] > d['50_sma'], 1, 0)
    d['down_trend'] = np.where(d['20_sma'] < d['50_sma'], 1, 0)

    #mfi location
    d['mfi_70_overbought'] = np.where(d['mfi'] > 70, 1, 0)
    d['mfi_30_oversold'] = np.where(d['mfi'] < 30, 1, 0)

    #strength of volume
    d['high_volume'] = np.where(d['Volume']>=d['20_va']*1, 1, 0)

    buy_period_col = np.logical_and(d['up_trend']==1, d['mfi_30_oversold']==1) 

    buy_period = np.where(buy_period_col, 1, 0)

    buy = np.logical_and(buy_period==1, d['high_volume']==1)
    d['buy'] = np.where(buy, 1, 0)


    sell_period_col = np.logical_and(d['down_trend']==1, d['mfi_70_overbought']==1) 
    sell_period = np.where(sell_period_col, -1, 0)

    d['sell'] = np.where(sell_period==-1, -1, 0)

    d['trade'] = d['buy'] + d['sell']

    pos=0

    num=0
    percentchange = []
    prices = []
    #find values

    for i in d['buy']:
    if i == 1: 
        x = d.loc[i, ['Adj Close']]

代码运行良好,直到最后出现find values代码块。我想做的是索引出algo购买时的Adj收盘价。虽然我得到了错误:

    ---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-7-d19f86abf5d9> in <module>
     70 for i in d['buy']:
     71     if i == 1:
---> 72         x = d.loc[close]
     73         prices.append(x)
     74 #         if pos==0:

~\Anaconda3\lib\site-packages\pandas\core\indexing.py in __getitem__(self, key)
   1765 
   1766             maybe_callable = com.apply_if_callable(key, self.obj)
-> 1767             return self._getitem_axis(maybe_callable, axis=axis)
   1768 
   1769     def _is_scalar_access(self, key: Tuple):

~\Anaconda3\lib\site-packages\pandas\core\indexing.py in _getitem_axis(self, key, axis)
   1961 
   1962         # fall thru to straight lookup
-> 1963         self._validate_key(key, axis)
   1964         return self._get_label(key, axis=axis)
   1965 

~\Anaconda3\lib\site-packages\pandas\core\indexing.py in _validate_key(self, key, axis)
   1828 
   1829         if not is_list_like_indexer(key):
-> 1830             self._convert_scalar_indexer(key, axis)
   1831 
   1832     def _is_scalar_access(self, key: Tuple) -> bool:

~\Anaconda3\lib\site-packages\pandas\core\indexing.py in _convert_scalar_indexer(self, key, axis)
    738         ax = self.obj._get_axis(min(axis, self.ndim - 1))
    739         # a scalar
--> 740         return ax._convert_scalar_indexer(key, kind=self.name)
    741 
    742     def _convert_slice_indexer(self, key: slice, axis: int):

~\Anaconda3\lib\site-packages\pandas\core\indexes\datetimelike.py in _convert_scalar_indexer(self, key, kind)
    384             is_flt = is_float(key)
    385             if kind in ["loc"] and (is_int or is_flt):
--> 386                 self._invalid_indexer("index", key)
    387             elif kind in ["ix", "getitem"] and is_flt:
    388                 self._invalid_indexer("index", key)

~\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in _invalid_indexer(self, form, key)
   3075         """
   3076         raise TypeError(
-> 3077             f"cannot do {form} indexing on {type(self)} with these "
   3078             f"indexers [{key}] of {type(key)}"
   3079         )

TypeError: cannot do index indexing on <class 'pandas.core.indexes.datetimes.DatetimeIndex'> with these indexers [45.86000061035156] of <class 'float'>

为什么我会出现这个错误?我如何修复它?多谢各位


Tags: keyincoreimportselfpandasisnp
2条回答

上面的答案是正确的,而且效率更高,但如果您仍然希望它在一个循环中进行一些后处理,您可以这样做:

for i in d['buy'].index:
    if d.loc[i, 'buy'] == 1:
        x = d.loc[i, ['Adj Close']]

可以使用更简单的表达式:

X = d['Adj Close'][d['buy']==1]

d.loc[d.index[d['buy']==1], ['Adj Close']]

在您的示例中,您试图通过int值1调用位置,但不是datetime64类型

相关问题 更多 >

    热门问题