繁体   English   中英

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

[英]In a Python Function, write the pandas result to a CSV

在此处输入图像描述您好,我正在尝试编写一个脚本,在其中查看一些历史数据(股票价格)并计算滚动线性回归斜率。

我有一个 CSV 文件,其中包含 01-01-2010 - 10-23-2020 的 AAPL 美国股票收盘价。

正如您在下面的代码中所看到的,我已经阅读了 CSV,创建了一些新变量、移动线性斜率等......并将这些数据作为新列写入 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

您创建的函数检查数据框的完整列,而不是给定日期的值。 另外, 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)

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM