This question already has answers here:
How to select rows from a DataFrame based on column values?
(10个答案)
去年关门了。
我试图用一个振荡器(相对强度指数)来知道什么时候买卖股票。我为RSI和收盘价创建了一个数据框。我可以同时绘制两个图,但我也希望在RSI达到买卖信号时添加到我的图中。因此,为了做到这一点,我需要在RSI低于25时创建RSI列的比较,如果RSI超过85,这将触发我的买入信号和卖出信号。我的问题是,在我的RSI列降到25以下的那一天,直到我的RSI列升到85以上的那一天,我都无法计算出我的收盘价列。我在新的dataframe列中只得到了Nan。
#rsi
import pandas
import warnings
import pandas_datareader.data as web
import datetime
import matplotlib.pyplot as plt
warnings.filterwarnings('ignore')
# Window length for moving average
window_length = 14

# Dates
start = datetime.datetime(2016, 1, 5)
end = datetime.datetime(2016, 12, 31)

# Get data
data = web.DataReader('FB', 'morningstar', start, end)
df= pd.DataFrame(data)

# Get just the close
close = data['Close']
# Get the difference in price from previous step
delta = close.diff()
# Get rid of the first row, which is NaN since it did not have a previous
# row to calculate the differences
delta = delta[1:]

# Make the positive gains (up) and negative gains (down) Series
up, down = delta.copy(), delta.copy()
up[up < 0] = 0
down[down > 0] = 0

# Calculate the EWMA
roll_up1 = pandas.stats.moments.ewma(up, window_length)
roll_down1 = pandas.stats.moments.ewma(down.abs(), window_length)

# Calculate the RSI based on EWMA
RS1 = roll_up1 / roll_down1
RSI1 = 100.0 - (100.0 / (1.0 + RS1))

# Calculate the SMA
roll_up2 = pandas.rolling_mean(up, window_length)
roll_down2 = pandas.rolling_mean(down.abs(), window_length)

# Calculate the RSI based on SMA
RS2 = roll_up2 / roll_down2
RSI2 = 100.0 - (100.0 / (1.0 + RS2))
df['RSI2']=RSI2

df=df.dropna(axis=0)

df['RSI2']=df['RSI2'].astype(float)




df['BUY']=df['Close'][df['RSI2'] < 25]
print (df['BUY'])




# Compare graphically
plt.figure()
df['BUY'].plot(title='FB',figsize = (20, 5))
plt.show()
RSI1.plot(title='Relative Strength Index',figsize = (20, 5))
RSI2.plot(figsize = (20, 5))
plt.legend(['RSI via EWMA', 'RSI via SMA'])
plt.show()

最佳答案

如果我正确地回答了您的问题,那么您要查找的是pandas(pd.query()中的内容,就像SQL中的一样,例如

df['rsi_query'] = np.zeros(df.shape[0])
myquery = df.query('RSI>.25 & RSI<.85').index
df.iloc[myquery, -1] = 1(replace it with what you want)

Further reference

10-08 00:29