【问题标题】:How to make the below code run for entire data set in python?如何使以下代码在 python 中为整个数据集运行?
【发布时间】:2022-01-12 06:04:06
【问题描述】:

我有股票市场数据,我想让代码购买股票(买入)并等到它被卖出(卖出)并在卖出后再次购买股票。以下代码仅针对初始买卖运行。如果我想对整个数据集执行此操作,而不是在第一次买入和第一次卖出时中断。

i=0
j=0
while (i<1) and (j <len(data)):
    if data['RSI'][j]>=70:
        print(j,data['RSI'][j])
        print("BUY")
        k=j
        i+=1
    j+=1
    while (i==1) and ((j>k) and (j<len(data))):
        if data['RSI'][j]<=30:
            print(j,data['RSI'][j])
            print("Sell")
            i+=1
        j+=1

以上代码以表格形式输出(便于理解):

index RSI tag
0 100.0 BUY
7 25.38 SELL

预期输出:

index RSI tag
0 100.0 BUY
7 25.38 SELL
10 80.24 BUY
20 40.20 SELL
25 81.24 BUY
30 41.20 SELL

整个数据集都是这样的

【问题讨论】:

    标签: python python-3.x pandas while-loop finance


    【解决方案1】:

    您的第一个 for 循环在一次迭代后存在,因为您将 i 增加到 1(并且可能增加到更高的值)。由于您的 while 循环仅在 i&lt;1 and some other stuff 时不断迭代,因此当它发现 i1 时,它就存在。

    我不能就如何解决这个问题给你建议,因为我不能完全看到你想用ji 实现什么,但你一定会弄清楚的 :)

    【讨论】:

      【解决方案2】:

      我在完成工作的第二个 while 中申请了循环和 (k!='NA')。

      i=0
      j=0
      for row in range(0,len(data)):
          while (i<row+1) and (j<len(data)):
              if data['RSI'][j]>=70:
                  print(j,data['RSI'][j])
                  print("BUY")
                  k=j
                  i+=1
              j+=1
              while (k!='NA') and ((j>k) and (j<len(data))):
                  if data['RSI'][j]<=30:
                      print(j,data['RSI'][j])
                      print("Sell")
                      k='NA'
                  j+=1
      

      【讨论】:

      • 您还需要在开头定义k。如果不是,则在第一个 if 语句为 False 的开始时,第二个 while 循环使用不存在的变量 k
      猜你喜欢
      • 1970-01-01
      • 2022-11-18
      • 1970-01-01
      • 2018-11-17
      • 2021-07-19
      • 2012-12-29
      • 2021-09-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多