I am trying to apply q-learning to my custom reinforcement learning environment that is representing energy storage arbitrage (electricity trading with a battery,charge when prices are low and discharge when prices increase). The environment works but I am not able to apply q-learning to it. Below the environment is a script that is able to run the environment but I am unsure what I should make the state variable. Any ideas on how to apply q-learning to optimize the charge/discharge cycles? the reset function starts the next day from a dataset with hourly prices for electricity. picture of the dataframe is below.
class BatteryEnv(gym.Env):
def __init__(self, df):
self.dict_actions = {0:'discharge',1:'charge',2:'wait'}
self.df = df
self.action_space = spaces.Discrete(3)
self.observation_space = spaces.Box(low=0, high=100, shape=(1,1))
self.reward_list = []
self.actual_load_list = []#observations
self.SOE_list=[] #State of energy
self.state_idx = 0 #iteration (hour of the day)
self.SOE = 0 #SOE
self.MAX_charge = 20 #C-rate kinda
self.Capacity =100
def step(self, action):
#mapping integer to action for actual load calculation
str_action = self.dict_actions[action]
#increase state idx within episode (1= 1 hour)
self.state_idx+=1
#calculating our actual load
if str_action == 'charge' and self.SOE < self.Capacity:
SOE_charge = np.clip(self.Capacity - self.SOE, 0, self.MAX_charge)
self.SOE += SOE_charge
obs = SOE_charge * self.df['prices'][self.state_idx]
elif str_action == 'discharge' and self.SOE > 0:
SOE_discharge = np.clip(self.SOE, 0, self.MAX_charge)
self.SOE -= SOE_discharge
obs = -SOE_discharge * self.df['prices'][self.state_idx]
else:
self.SOE += 0
obs = 0 * self.df['prices'][self.state_idx]
# appending actual load to list for monitoring and comparison purposes
self.actual_load_list.append(obs)
self.SOE_list.append(self.SOE)
#reward system
if obs<0: #if observation is positive we spending money. if negative we earning
reward =1
else:
reward =-1
# appending curr reward to list for monitoring and comparison purposes
self.reward_list.append(reward)
#checking whether our episode (day interval) ends
if self.df.iloc[self.state_idx,:].Daynum != self.df.iloc[self.state_idx-1].Daynum:
done = True
else:
done = False
return obs, reward, done
def reset(self):
return df.iloc[self.state_idx,:]
def render():
pass
The below codes are able to to show that the environment is working.
for episode in range(7):
observation = env.reset()
for t in range(24): #can't be smaller than 24 as 24 time points equal to 1 episode (1 day)
#print(observation)
action = env.action_space.sample() #random actions
observation, reward, done = env.step(action)
if done:
print("Episode finished after {} timesteps".format(t+1)), print (observation), print(reward)
break