关于一个价值为真,然后变成假的问题。

问题描述 投票:0回答:1

好吧,我是个学生,也是Python的新手,请耐心等待。我正在处理时间序列数据和移动平均数。

我想写一个条件动作,当一个数据点从True到False的时候,这个动作会做一些事情。

例如,当序列高于移动平均线时,等到它低于移动平均线时,dosomething()

然而,我只想在它从高于移动平均线到低于移动平均线的情况下让它dosomething()。如果只是移动平均线的时间序列,我不想让它dosomething()。

所以... 我有。

 if self.series > moving_average:
            while True:
                if position < moving_average: #Need something if series then becomes less than the 
                                              #moving_average
                    self.dosomething('action', self.something)
                    break
                time.sleep(0.1)

我知道这很难看,我也知道... ... while True:if position < moving_average 是在最好的不完整。我需要知道,如果我在正确的轨道上,或者如果我必须做一些完全不同的事情。

先谢谢你

previous_series = df['series'].shift(1)   
previous_MA_35 = df['MA_35'].shift(1)

long_crossing = ((df['series'] < df[MA_35]) & (previos_series >= 
                                               previous_MA_35))

while True:
    if long_crossing = True:
        dosomething()
        break
    time.sleep(0.1)

好吧,也许这样更好一些。但还是不知道我的方向是否正确。

python time-series conditional-statements moving-average
1个回答
0
投票

我想你需要的是一个变量,作为你的程序的状态。

state = False # False represents pos >= moving_avg, True represents pos < moving_avg

while True:
    new_state = False
    if pos < moving_avg:
        new_state = True

    move = (new_state and (not state) )
    # move is True only when new_state is True and state is False

    if move:
        do_something()

    state = new_state
© www.soinside.com 2019 - 2024. All rights reserved.