在Python函数中,将熊猫结果写入CSV

时间:2020-10-26 16:29:03

标签: python pandas csv if-statement

enter image description here您好,我正在尝试编写一个脚本,在其中查看一些历史数据(股票价格)并计算滚动的线性回归斜率。

我有一个CSV文件,其价格为2010年1月1日至2020年10月23日的AAPL美国股票的收盘价。

如下面的代码所示,我已经阅读了CSV,创建了一些新变量,Moving Linear Slope等,并将该数据作为新列写入了CSV。 PS:ROC是MLR斜率的变化率。

我现在正在尝试创建一个函数,该函数针对每个日期/股价返回1,0,-1(1 =长,0 =无头寸,-1 =空)。我创建了以下函数“ scorer”,但无法弄清楚如何查看每个日期并将相应的值写入CSV中的新列。

任何帮助将不胜感激。预先感谢。

import pandas as pd
import talib as ta
import matplotlib.pyplot as plt

data = pd.read_csv("Copper.csv")
score = 0

mlrs = ta.LINEARREG_SLOPE(data["Close"].values,14)*-1
sma = data.MlrSlope.rolling(14).mean()
roc = data.MlrSlope.rolling(5).mean()

#Create new columns for Roc and SMA. We then Write the new Column data to the CSV file. This should add both the ROCC and SMA Columns. 
data["Rocc"] = roc
data["SMA"] = sma
data.to_csv("copper.csv",index=True)

# The below function looks to check for the SMA & MLR Slope being Positive... ***JOSHUA BEFORE FINISHING*** add another parameter that looks at the ROC of the MLR Slope... This would be my "roc" variable. If the change is very negative very quick it could resemble an exit opportunity on the Long Side, while a sharp Up Turn could indicate a Buy Opportunity.  
def scorer(data):
    if(data["sma"] > 0 and data["MlrSlope"] >0 ):
            return 1
        elif (data["sma"] >0 and data["MlrSlope"] <0):
            return 0
        elif(data["sma"] <0 and data["MlrSlope"] >0):
            return 0
        elif (data["sma"] <0 and data["MlrSlope"] <0):
            return -1

1 个答案:

答案 0 :(得分:0)

您创建的函数将检查数据框的整个列,而不是给定日期的值。另外,ifelif语句被错误地缩进。

def scorer(data, i):
    if(data.loc[i,"sma"] > 0 and data.loc[i,"MlrSlope"] >0 ):
        return 1
    elif (data.loc[i,"sma"] >0 and data.loc[i,"MlrSlope"] <0):
        return 0
    elif(data.loc[i,"sma"] <0 and data.loc[i,"MlrSlope"] >0):
        return 0
    elif (data.loc[i,"sma"] <0 and data.loc[i,"MlrSlope"] <0):
        return -1

上面的函数需要2个输入:您正在使用的数据框和给定的索引值。我想下一步是使用每个日期的策略值创建一个新列,因此下面的代码应该可以完成工作:

for i in data.index:
    data.loc[i, 'strategy'] = scorer(data,i)

请让我知道它是否有效,因为我无法在真实的数据帧中对其进行测试