我在 pandas/numpy 的循环中遇到了麻烦。以这段代码为例
import pandas as pd
eurusd = pd.read_csv('EURUSD.csv',index_col='Date',parse_dates=True,usecols=['Date','High','Low','Open','Close'])
gbpusd = pd.read_csv('GBPUSD.csv',index_col='Date',parse_dates=True,usecols=['Date','High','Low','Open','Close'])
audusd = pd.read_csv('AUDUSD.csv',index_col='Date',parse_dates=True,usecols=['Date','High','Low','Open','Close'])
eurusd['MovingAvg'] = pd.rolling_mean(eurusd.Close,100)
gbpusd['MovingAvg'] = pd.rolling_mean(gbpusd.Close,100)
audusd['MovingAvg'] = pd.rolling_mean(audusd.Close,100)
我将如何实现这样的逻辑
if the eurusd.Close is less than the eurusd.MovingAvg
AND if gbpusd.Close is less than the gbpusd.MovingAvg
AND if audusd.Close is GREATER than the audusd.MovingAvg
then set some condition to TRUE
最佳答案
使用股票和雅虎财经来说明这一概念:
import pandas.io.data as web
df = web.DataReader(['F', 'AAPL', 'IBM'], 'yahoo', '2015-01-02', '2016-01-01')['Adj Close']
df = pd.concat([df,
pd.rolling_mean(df, window=100).rename(
columns={col: col + "_100" for col in df})],
axis=1)
df['condition'] = False
df.loc[(df.F < df.F_100) &
(df.AAPL < df.AAPL_100) &
(df.IBM > df.IBM_100), 'condition'] = True
>>> df.tail()
AAPL F IBM AAPL_100 F_100 IBM_100 condition
Date
2015-12-24 106.796739 13.692101 135.544053 112.421986 13.616413 140.126056 False
2015-12-28 105.600553 13.567714 134.916580 112.347147 13.611907 139.954141 False
2015-12-29 107.498633 13.615554 137.044105 112.288827 13.607596 139.806220 False
2015-12-30 106.094845 13.558146 136.612715 112.212631 13.602994 139.665642 False
2015-12-31 104.058365 13.481600 134.926379 112.074727 13.595828 139.492368 False
>>> df.condition.sum()
8
关于python - 努力使用面向数组的编程来实现循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37127354/