class_docstr: A portfolio allocation environment for OpenAI gym.
  
  This environment simulates the interactions between an agent and the financial market
  based on data provided by a dataframe. The dataframe contains the time series of
  features defined by the user (such as closing, high and low prices) and must have
  a time and a tic column with a list of datetimes and ticker symbols respectively.
  An example of dataframe is shown below::
  
          date        high            low             close           tic
      0   2020-12-23  0.157414        0.127420        0.136394        ADA-USD
      1   2020-12-23  34.381519       30.074295       31.097898       BNB-USD
      2   2020-12-23  24024.490234    22802.646484    23241.345703    BTC-USD
      3   2020-12-23  0.004735        0.003640        0.003768        DOGE-USD
      4   2020-12-23  637.122803      560.364258      583.714600      ETH-USD
      ... ...         ...             ...             ...             ...
  
  Based on this dataframe, the environment will create an observation space that can
  be a Dict or a Box. The Box observation space is a three-dimensional array of shape
  (f, n, t), where f is the number of features, n is the number of stocks in the
  portfolio and t is the user-defined time window. If the environment is created with
  the parameter return_last_action set to True, the observation space is a Dict with
  the following keys::
  
      {
      "state": three-dimensional Box (f, n, t) representing the time series,
      "last_action": one-dimensional Box (n+1,) representing the portfolio weights
      }
  
  Note that the action space of this environment is an one-dimensional Box with size
  n + 1 because the portfolio weights must contains the weights related to all the
  stocks in the portfolio and to the remaining cash.
  
  Attributes:
      action_space: Action space.
      observation_space: Observation space.
      episode_length: Number of timesteps of an episode.
      portfolio_size: Number of stocks in the portfolio.
class_docstr_tok: ["A","portfolio","allocation","environment","for","OpenAI","gym",".","This","environment","simulates","the","interactions","between","an","agent","and","the","financial","market","based","on","data","provided","by","a","dataframe",".","The","dataframe","contains","the","time","series","of","features","defined","by","the","user","(","such","as","closing",",","high","and","low","prices",")","and","must","have","a","time","and","a","tic","column","with","a","list","of","datetimes","and","ticker","symbols","respectively",".","An","example","of","dataframe","is","shown","below",":",":","date","high","low","close","tic","0","2020-12-23","0.157414","0.127420","0.136394","ADA-USD","1","2020-12-23","34.381519","30.074295","31.097898","BNB-USD","2","2020-12-23","24024.490234","22802.646484","23241.345703","BTC-USD","3","2020-12-23","0.004735","0.003640","0.003768","DOGE-USD","4","2020-12-23","637.122803","560.364258","583.714600","ETH-USD","...","...","...","...","...","...","Based","on","this","dataframe",",","the","environment","will","create","an","observation","space","that","can","be","a","Dict","or","a","Box",".","The","Box","observation","space","is","a","three-dimensional","array","of","shape","(","f",",","n",",","t",")",",","where","f","is","the","number","of","features",",","n","is","the","number","of","stocks","in","the","portfolio","and","t","is","the","user-defined","time","window",".","If","the","environment","is","created","with","the","parameter","return_last_action","set","to","True",",","the","observation","space","is","a","Dict","with","the","following","keys",":",":","{","``","state","''",":","three-dimensional","Box","(","f",",","n",",","t",")","representing","the","time","series",",","``","last_action","''",":","one-dimensional","Box","(","n+1",",",")","representing","the","portfolio","weights","}","Note","that","the","action","space","of","this","environment","is","an","one-dimensional","Box","with","size","n","+","1","because","the","portfolio","weights","must","contains","the","weights","related","to","all","the","stocks","in","the","portfolio","and","to","the","remaining","cash",".","Attributes",":","action_space",":","Action","space",".","observation_space",":","Observation","space",".","episode_length",":","Number","of","timesteps","of","an","episode",".","portfolio_size",":","Number","of","stocks","in","the","portfolio","."]
docstr: Gets state and information given a time index. It also updates "data"
  attribute with information about the current simulation step.
  
  Args:
      time_index: An integer that represents the index of a specific datetime.
          The initial datetime of the dataframe is given by 0.
  
  Note:
      If the environment was created with "return_last_action" set to
      True, the returned state will be a Dict. If it's set to False,
      the returned state will be a Box. You can check the observation
      state through the attribute "observation_space".
  
  Returns:
      A tuple with the following form: (state, info).
  
      state: The state of the current time index. It can be a Box or a Dict.
      info: A dictionary with some informations about the current simulation
          step. The dict has the following keys::
  
          {
          "tics": List of ticker symbols,
          "start_time": Start time of current time window,
          "start_time_index": Index of start time of current time window,
          "end_time": End time of current time window,
          "end_time_index": Index of end time of current time window,
          "data": Data related to the current time window,
          "price_variation": Price variation of current time step
          }
docstr_tok: ["Gets","state","and","information","given","a","time","index",".","It","also","updates","``","data","''","attribute","with","information","about","the","current","simulation","step",".","Args",":","time_index",":","An","integer","that","represents","the","index","of","a","specific","datetime",".","The","initial","datetime","of","the","dataframe","is","given","by","0",".","Note",":","If","the","environment","was","created","with","``","return_last_action","''","set","to","True",",","the","returned","state","will","be","a","Dict",".","If","it","'s","set","to","False",",","the","returned","state","will","be","a","Box",".","You","can","check","the","observation","state","through","the","attribute","``","observation_space","''",".","Returns",":","A","tuple","with","the","following","form",":","(","state",",","info",")",".","state",":","The","state","of","the","current","time","index",".","It","can","be","a","Box","or","a","Dict",".","info",":","A","dictionary","with","some","informations","about","the","current","simulation","step",".","The","dict","has","the","following","keys",":",":","{","``","tics","''",":","List","of","ticker","symbols",",","``","start_time","''",":","Start","time","of","current","time","window",",","``","start_time_index","''",":","Index","of","start","time","of","current","time","window",",","``","end_time","''",":","End","time","of","current","time","window",",","``","end_time_index","''",":","Index","of","end","time","of","current","time","window",",","``","data","''",":","Data","related","to","the","current","time","window",",","``","price_variation","''",":","Price","variation","of","current","time","step","}"]
code: def _get_state_and_info_from_time_index(self, time_index):
      """Gets state and information given a time index. It also updates "data"
      attribute with information about the current simulation step.
  
      Args:
          time_index: An integer that represents the index of a specific datetime.
              The initial datetime of the dataframe is given by 0.
  
      Note:
          If the environment was created with "return_last_action" set to
          True, the returned state will be a Dict. If it's set to False,
          the returned state will be a Box. You can check the observation
          state through the attribute "observation_space".
  
      Returns:
          A tuple with the following form: (state, info).
  
          state: The state of the current time index. It can be a Box or a Dict.
          info: A dictionary with some informations about the current simulation
              step. The dict has the following keys::
  
              {
              "tics": List of ticker symbols,
              "start_time": Start time of current time window,
              "start_time_index": Index of start time of current time window,
              "end_time": End time of current time window,
              "end_time_index": Index of end time of current time window,
              "data": Data related to the current time window,
              "price_variation": Price variation of current time step
              }
      """
      # returns state in form (channels, tics, timesteps)
      end_time = self._sorted_times[time_index]
      start_time = self._sorted_times[
          time_index - (self._time_window - 1)
      ]
  
      # define data to be used in this time step
      self._data = self._df[
          (self._df[self._time_column] >= start_time)
          & (self._df[self._time_column] <= end_time)
      ][[self._time_column, self._tic_column] + self._features]
  
      # define price variation of this time_step
      self._price_variation = self._df_price_variation[
          self._df_price_variation[self._time_column] == end_time
      ][self._valuation_feature].to_numpy()
      self._price_variation = np.insert(self._price_variation, 0, 1)
  
      # define state to be returned
      state = None
      for tic in self._tic_list:
          tic_data = self._data[self._data[self._tic_column] == tic]
          tic_data = tic_data[self._features].to_numpy().T
          tic_data = tic_data[..., np.newaxis]
          state = (
              tic_data
              if state is None
              else np.append(state, tic_data, axis=2)
          )
      state = state.transpose((0, 2, 1))
      info = {
          "tics": self._tic_list,
          "start_time": start_time,
          "start_time_index": time_index - (self._time_window - 1),
          "end_time": end_time,
          "end_time_index": time_index,
          "data": self._data,
          "price_variation": self._price_variation,
      }
      return self._standardize_state(state), info
  
imports: from __future__ import annotations
  import math
  import gym
  import matplotlib
  import numpy
  import pandas
  from gym import spaces
  from gym.utils import seeding
  import matplotlib.pyplot
  from stable_baselines3.common.vec_env import DummyVecEnv
  from pathlib import Path
label_desc: Use image node_id 4 for calling the PortfolioOptimizationEnv obj's underlying member method code with example usage: obj._get_state_and_info_from_time_index(time_index) and returns: self,  info