使用面向数组编程实现循环

2024-04-26 13:13:24 发布

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

我的头在熊猫圈里绕不动。以这个代码为例

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

Tags: csvthetrueclosereaddateindexparse
1条回答
网友
1楼 · 发布于 2024-04-26 13:13:24

使用股票和雅虎金融来说明这个概念:

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

相关问题 更多 >