This is my current code,
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import requests
plt.style.use("fivethirtyeight")
df = pd.read_csv("TSLA.csv")
df = df.set_index(pd.DatetimeIndex(df["Date"].values))
ShortEMA = df.Close.ewm(span=5, adjust = False).mean()
MiddleEMA = df.Close.ewm(span = 21, adjust = False).mean()
LongEMA = df.Close.ewm(span = 53, adjust = False).mean()
df['Short'] = ShortEMA
df['Middle'] = MiddleEMA
df['Long'] = LongEMA
def MyStrat(data):
bought_list = []
sold_list = []
current_pos = "None"
for i in range(0, len(data)):
if data["Close"][i] > data["Short"][i] and current_pos == "None":
bought_list.append(data["Close"][i])
sold_list.append(np.nan)
current_pos = "Bought"
else:
data["Close"][i] < data["Short"][i] and current_pos == "Bought"
sold_list.append(data["Close"][i])
bought_list.append(np.nan)
current_pos = "None"
print(MyStrat(df)["Close"])
df["Bought"] = MyStrat(df)
df["Sold"] = MyStrat(df)
I get the error
File "c:\Users\zackz\Desktop\AlgoTrading.py", line 100, in <module>
print(MyStrat(df)["Close"])
TypeError: 'NoneType' object is not subscriptable
The data looks something like this,
Date Open High Low Close Adj Close Volume Short Middle Long
2021-04-01 2021-04-01 688.369995 692.419983 659.419983 661.750000 661.750000 35298400 661.750000 661.750000 661.750000
2021-04-05 2021-04-05 707.710022 708.159973 684.700012 691.049988 691.049988 41842800 671.516663 664.413635 662.835185
2021-04-06 2021-04-06 690.299988 696.549988 681.369995 691.619995 691.619995 28271800 678.217773 666.886941 663.901289
2021-04-07 2021-04-07 687.000000 691.380005 667.840027 670.969971 670.969971 26309400 675.801839 667.258125 664.163092
2021-04-08 2021-04-08 677.380005 689.549988 671.650024 683.799988 683.799988 23924300 678.467889 668.761931 664.890384
I just want to add the data from the code, when bought, when sold, into the last 2 columns in the data, then i will plot the data.
Thanks In Advance
CodePudding user response:
Your MyStrat
function does not return anything, so you're basically trying to get the "Close" key from a None value. Try returning whatever you need from the MyStrat
function at the end of the body.