[英]How do i print 2 consecutive red or green candles using the def function and conditional statements in python
I want the python conditional statements to only execute / print "PLEASE SELL" IF there are 2 consecutive RED CANDLES in a row, followed by 2 consecutive GREEN CANDLES in a row我希望 python 条件语句只执行/打印“请出售”,如果连续有 2 个连续的红色蜡烛,然后是连续的 2 个连续的绿色蜡烛
and for ELIF, IF there are 2 consecutive GREEN CANDLES in a row, followed by 2 consecutive RED CANDLES in a row.对于 ELIF,如果连续有 2 个连续的 GREEN CANDLES,然后是连续的 2 个连续的 RED CANDLES。
The below code of mine prints and executes on only 1 RED candle and 1 GREEN candle.我的以下代码仅在 1 根红色蜡烛和 1 根绿色蜡烛上打印和执行。 Kindly let me know how to improve the code to give my anticipated result
请让我知道如何改进代码以给出我预期的结果
def data_color(open,close):
color = []
if open > close:
color.append("RED")
elif open < close:
color.append("GREEN")
else:
color.append("DOJI")
return color
while True:
time_iq = API.get_server_timestamp()
if int(dt.fromtimestamp(time_iq).second) == 59 or 1 > 0:
data_candle = API.get_candles(pair,timeframe,10,time_iq)
colors = data_color(data_candle[-2]["open"], data_candle[-2]["close"])
if colors[0] == "RED":
print(" PLEASE SELL")
elif colors[0] == "GREEN":
print("PLEASE BUY")
for i in range (1,len(colors)):
if colors[i-1] and colors[i] == "RED":
print(" PLEASE SELL")
elif colors[i-1] and colors[i] == "GREEN":
print("PLEASE BUY")
else:
pass
You should try this
你应该试试这个
There are a number of ways to approach this, but here are two that might do what you need:有很多方法可以解决这个问题,但这里有两种方法可以满足您的需求:
It depends on how you want to evaluate and find the patterns you're looking for.这取决于您想如何评估和找到您正在寻找的模式。 From your question, it is unclear whether the data you have comes in pre-formatted "packets" of 4 entries, within which you're looking for the recognized pattern of "2 green 2 red" or "2 red 2 green", so I'm going to assume this is not the case for the first example.
从您的问题来看,目前尚不清楚您拥有的数据是否来自 4 个条目的预格式化“数据包”,您在其中寻找“2 绿 2 红”或“2 红 2 绿”的识别模式,因此我将假设第一个示例不是这种情况。 In the second example, I will illustrate how to approach things if that assumption is true.
在第二个例子中,我将说明如何处理事情,如果这个假设是真实的。
Example 1: iterate over the list of colors and find the pattern you're looking for in the last 4 entries, including the current iteration.示例 1:迭代颜色列表并在最后 4 个条目中找到您要查找的图案,包括当前迭代。
def evaluate_by_iteration(_colors):
# -- skip the first three entries
for i in range(4, len(_colors)):
# -- get the preceding three elements and the current one.
# -- note the "i+1" here, this is how list slicing works
first, second, third, fourth = _colors[i-3: i+1]
if (first == second == 'GREEN') and (third == fourth == 'RED'):
print('[iterator] PLEASE SELL')
elif (first == second == 'RED') and (third == fourth == 'GREEN'):
print('[iterator] PLEASE BUY')
Example 2: chunk the list into packets of size 4, and check on each packet if they conform to the pattern.示例 2:将列表分成大小为 4 的数据包,并检查每个数据包是否符合模式。 Do this only if the data is expected to be chunked this way!
仅当数据预计以这种方式分块时才这样做! (again, not clear from your question)
(同样,从你的问题中不清楚)
from itertools import izip_longest
def evaluate_by_chunks(_colors):
chunked_colors = izip_longest(*[iter(_colors)] * 4, fillvalue=None)
for chunk in list(chunked_colors):
first, second, third, fourth = chunk
if (first == second == 'GREEN') and (third == fourth == 'RED'):
print('[chunker] PLEASE SELL')
if (first == second == 'RED') and (third == fourth == 'GREEN'):
print('[chunker] PLEASE BUY')
Why would you use the second approach over the first one?为什么要使用第二种方法而不是第一种方法?
It depends on how you want to evaluate your data.这取决于您想如何评估数据。 Take the following data set:
取以下数据集:
colors = ['RED', 'GREEN', 'RED', 'RED', 'GREEN', 'GREEN', 'RED', 'RED']
print('-------------')
print('EVALUATE BY ITERATION')
evaluate_by_iteration(colors)
print(' ')
print('-------------')
print('EVALUATE BY CHUNKS')
evaluate_by_chunks(colors)
print(' ')
This will print:这将打印:
-------------
EVALUATE BY ITERATION
[iterator] PLEASE BUY
[iterator] PLEASE SELL
-------------
EVALUATE BY CHUNKS
[chunker] PLEASE SELL
Note how "evaluate by iteration" has two matches, as we only increment the search index by one each time.请注意“通过迭代评估”如何有两个匹配项,因为我们每次只将搜索索引增加一个。
Now, depending on your needs, either one of these may be correct;现在,根据您的需要,其中之一可能是正确的; with the iterator-based approach, you will find every instance of the pattern you look for, including patterns that overlap, where you have a "GREEN GREEN RED RED GREEN GREEN" pattern for example.
使用基于迭代器的方法,您将找到您要查找的模式的每个实例,包括重叠的模式,例如,您有一个“GREEN GREEN RED RED GREEN GREEN”模式。
With the chunk-based approach, you ensure that you will never evaluate patterns that overlap, but that comes with the assumption that your data is nicely organized in packets of size 4.使用基于块的方法,您可以确保永远不会评估重叠的模式,但前提是假设您的数据很好地组织在大小为 4 的数据包中。
There is one final approach that takes the iterator approach, but ensures no item is evaluated twice;有一种最终方法采用迭代器方法,但确保不会对任何项进行两次评估; in this example, we rewrite the iteration-based evaluator method, but instead of looking back, we look forward.
在这个例子中,我们重写了基于迭代的评估器方法,但不是回顾,而是向前看。 This allows us, when we find a pattern match, to manually increment the "index" variable, ensuring we skip over the pattern when it matches.
这允许我们在找到模式匹配时手动增加“索引”变量,确保我们在匹配时跳过模式。
This allows for the data to be relatively unstructured, while ensuring you do not evaluate overlapping patterns.这允许数据相对非结构化,同时确保您不会评估重叠模式。
def evaluate_by_iteration_looking_forward(_colors):
# -- skip the first three entries
counter = 0
for i in range(0, len(_colors) - 3):
if counter > len(_colors) - 3:
break
first, second, third, fourth = _colors[counter: counter + 4]
if (first == second == 'GREEN') and (third == fourth == 'RED'):
print('[iterator] PLEASE SELL')
counter += 4
continue
elif (first == second == 'RED') and (third == fourth == 'GREEN'):
print('[iterator] PLEASE BUY')
counter += 4
continue
counter += 1
To test this, we run this code:为了测试这一点,我们运行以下代码:
print('-------------')
print('EVALUATE BY ITERATION')
evaluate_by_iteration(colors)
print(' ')
print('-------------')
print('EVALUATE BY CHUNKS')
evaluate_by_chunks(colors)
print(' ')
print('-------------')
print('EVALUATE BY ITERATION LOOKING FORWARD')
evaluate_by_iteration_looking_forward(colors)
Which prints:哪个打印:
-------------
EVALUATE BY ITERATION
[iterator] PLEASE BUY
[iterator] PLEASE SELL
-------------
EVALUATE BY CHUNKS
[chunker] PLEASE SELL
-------------
EVALUATE BY ITERATION LOOKING FORWARD
[iterator] PLEASE BUY
As you can see, our forward-looking evaluator only matches the first pattern, and then skips head, ensuring it does not match a second time with elements that were previously already evaluated.如您所见,我们的前瞻性评估器只匹配第一个模式,然后跳过 head,确保它不会与之前已经评估过的元素第二次匹配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.