我有3个脚本:MA_ExecFast MA_BacktestFast和MA_OptimizationFast 最初我在同一个原型脚本中有MA_ExecFast MA_BacktestFast的功能。
我有:
def MA_Exec(start_date= default_date, MA_length = default_length):
global SignalTable
global PositionTable
PositionData = PositionTable[-1:]
Signal = Ticker.loc[Ticker.Date < start_date][-(MA_length + 1):]
def backTest():
global PositionTable
OldPosition = PositionTable[-1:]
NewSig = SignalTable[-1:] #Last row of SignalTable
Backtest = pd.concat([OldPosition,NewSig], ignore_index=True)
if __name__ == "__main__":
start = time.time()
col1 = [...]
col2 = [...]
SignalTable = pd.DataFrame(columns = col1)
PositionTable = pd.DataFrame(columns = col1 + col2)
start_date = date(2016, 8, 15)
end_date = date(2017, 8, 15)
for single_date in daterange(start_date, end_date):
MA_Exec(start_date=single_date, MA_length = 20)
backTest()
但现在我需要将这些功能放到不同的脚本中。我想调用MA_OptimizationFast中的前两个脚本:
import MA_BacktestFast
import MA_ExecFas
def Opt(start_date = default_start_date, end_date = default_end_date, start_MA_length = default_start_Var1, end_MA_length = default_end_Var1):
col1 = [...]
col3 = [...]
for length in range(start_MA_length, end_MA_length + 1): # Loop through different MA_length
SignalTable = pd.DataFrame(columns = col1)
PositionTable = pd.DataFrame(columns = col3)
for single_date in MA_BacktestFast.daterange(start_date, end_date): # Loop through different dates with the same MA_length
MA_ExecFast.MA_Exec(start_date=single_date, MA_length = length)
MA_BacktestFast.backTest()
# After each MA_length is finished, we read the final return of this MA_length
ReturnTable = PositionTable
现在当我运行Opt()时,我会得到NameError: name 'PositionTable' is not defined.
我知道原因是,PositionTable和SignalTable现在处于Opt()函数中,因此它们不再是全局变量,但是如果我只是删除函数MA_Exec()和backTest()中的global关键字。它仍然无法运作。我想这是因为这使得这两个函数的SignalTable和PositionTable局部变量。
我想要SignalTable和PositionTable变量的位置,因为我想清除每个外部for循环中的Dataframe。如何将外部for循环层设为旧的“全局”图层?