簡體   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