我正在尝试添加显示值为1的列,其中显示交易信号。我已经把以下测试数据放在一起,以显示我想要做的事情。
创建测试数据框:
import pandas as pd
import datetime
index = pd.date_range('2013-1-1',periods=100,freq='30Min')
data = pd.DataFrame(data=list(range(100)), columns=['value'], index=index)
在2013-01-01,我们可以看到在09:30 - 10:30之间,最大值为20,最低值为19。
data.ix['2013-01-01 09:30:00':'2013-01-01 10:30:00']
value
2013-01-01 09:30:00 19
2013-01-01 10:00:00 20
2013-01-01 10:30:00 21
我想创建一个名为“enter_long”和“enter_short”的新列,每天会在hour_1_session
(见下文)的最大值或最小值第一次传递时添加1。每天只有一次,因此在同一天的enter_long和enter_short中的1不能为1。
这是所需的输出,并且在当天它在10:30显示的值列是> hour_1_session
的最大值(最长时间为09:30 - 10:30)。为了填充enter_short列'value',需要< 19.
value enter_long enter_short
2013-01-01 09:30:00 19 0 0
2013-01-01 10:00:00 20 0 0
2013-01-01 10:30:00 21 1 0
2013-01-01 11:00:00 22 0 0
2013-01-01 11:30:00 23 0 0
我可以使用以下内容获取此数据,但我不知道如何根据上述问题添加新的dataframe列:
daystart = '9:30'
hour_1_end = '10:29:59'
dayend = '16:14:59'
hour_1_session = data.between_time(daystart,hour_1_end, include_start=True, include_end=True)
day_session = data.between_time(daystart,dayend, include_start=True, include_end=True)
hour_1_high = hour_1_session['value'].rolling(window=1,freq='D').max()
hour_1_low = hour_1_session['value'].rolling(window=1,freq='D').min()
hour_1_high
2013-01-01 20.0
2013-01-02 68.0
Freq: D, Name: value, dtype: float64
答案 0 :(得分:1)
希望这会有所帮助。我在数据生成代码中改变了一点。
import pandas as pd
import random
periods = 48*7
index = pd.date_range('2013-1-1',periods=periods,freq='30Min')
data = pd.DataFrame({'value':[random.randint(0,100)+i/10 for i in range(periods)], 'enter_long':[False]*periods, 'enter_short':[False]*periods}, index=index)
daystart = '9:30'
dayend = '16:14:59'
day_session = data.between_time(daystart,dayend, include_start=True, include_end=True)
day_high = day_session['value'].rolling(window=1,freq='D').max()
day_low = day_session['value'].rolling(window=1,freq='D').min()
print(day_high)
七天的高点
2013-01-01 97.1
2013-01-02 104.9
2013-01-03 109.7
2013-01-04 113.5
2013-01-05 104.3
2013-01-06 121.7
2013-01-07 113.6
同一7天的低点
2013-01-01 9.0
2013-01-02 7.3
2013-01-03 13.5
2013-01-04 18.9
2013-01-05 24.5
2013-01-06 46.6
2013-01-07 42.
查找信号
for i, date in enumerate(day_high.index):
df_sub=data[data.index.day==date.day]
d = df_sub[(df_sub.value>day_high[i]) | (df_sub.value<day_low[i])].iloc[0:1]
try:
if d.value[0]>day_high[i]:
data.loc[d.index,'enter_long']=True
else:
data.loc[d.index,'enter_short']=True
except IndexError:
print("No signals")
print(data[(data['enter_long']==True) | (data['enter_short']==True)])
返回
enter_long enter_short value
2013-01-01 01:30:00 False True 3.3
2013-01-02 07:30:00 True False 105.3
2013-01-03 07:30:00 False True 13.1
2013-01-04 01:00:00 False True 17.6
2013-01-05 00:00:00 False True 24.2
2013-01-06 02:00:00 True False 123.4
2013-01-07 02:00:00 True False 129.2