def step(self, action): if self.episodeended: return self.reset() currentstockprice =…
- User
def _step(self, action): if self._episode_ended: return self.reset()
current_stock_price = self._stock_data[self._current_step][3] if action == 1: # 做多/买入 if self._cash_in_hand >= current_stock_price: self._sum_action = self._sum_action + 1 self._num_stocks_owned += 1 self._cash_in_hand -= current_stock_price self._trades.append((self._current_step, 'buy')) elif action == 2: # 做空/卖出 if self._num_stocks_owned > 0: self._sum_action = self._sum_action + 1 self._num_stocks_owned -= 1 self._cash_in_hand += current_stock_price self._trades.append((self._current_step, 'sell')) # 更新状态和步数 self._current_step += 1 if self._current_step >= len(self._stock_data) - self._reward_lookahead: self._episode_ended = True # 记录图表数据 new_total_asset = self._cash_in_hand + self._num_stocks_owned * current_stock_price reward = self._calculate_reward(action) self._total_asset_record.append(new_total_asset) if self._episode_ended: self._episode_counter += 1 # 跟踪轮数的计数器增加 self._draw_charts() # 绘制并保存K线图和资金变化曲线 return ts.termination(np.array(self._state, dtype=np.float32), (new_total_asset - self._initial_cash)) else: self._state = self._get_observation() return ts.transition(np.array(self._state, dtype=np.float32), reward=reward, discount=1.0)最终奖励可否改为风险回报率,以下是完整代码: class StockTradingEnv(py_environment.PyEnvironment): _num = 1
def __init__(self, stock_data, initial_cash=1000000, history_length=50, reward_lookahead=12, filename=datetime.datetime.now().strftime('%Y%m%d%H%M%S%f'), plt_dir=r'/data/history/', model_name=''): self._stock_data = np.array(stock_data) self._history_length = history_length self._current_step = history_length self._initial_cash = initial_cash self._cash_in_hand = initial_cash self._num_stocks_owned = 0 self._start_step = history_length self._reward_lookahead = reward_lookahead self._total_asset_record = [initial_cash] # 记录每一步后的总资产以计算奖励 self._filename = str(StockTradingEnv._num) + "_" + filename StockTradingEnv._num = StockTradingEnv._num + 1 self._sum_action = 1 self._episode_counter = 0 # 跟踪轮数的计数器 self._trades = [] # 贸易详情 self._plt_dir = plt_dir + model_name + '/' os.makedirs(self._plt_dir, exist_ok=True) self._observation_spec = array_spec.ArraySpec( shape=(history_length, 4), dtype=np.float32, name='observation') # 动作空间定义为0-不操作,1-做多,2-做空(买卖同一量的股票) self._action_spec = array_spec.BoundedArraySpec( shape=(), dtype=np.int32, minimum=0, maximum=2, name='action') self._episode_ended = False def action_spec(self): return self._action_spec def observation_spec(self): return self._observation_spec def _calculate_reward(self, action): # Use future data to calculate reward. future_steps = min(len(self._stock_data) - self._current_step, self._reward_lookahead) if future_steps < self._reward_lookahead: self._episode_ended = True return 0 future_data = self._stock_data[self._current_step:self._current_step + future_steps] current = self._stock_data[self._current_step][3] future_max = future_data[:, 1].max() future_min = future_data[:, 2].min() if action == 1: # 做多/买入 max_favorable_variation = future_max - current max_adverse_variation = current - future_min return (max_favorable_variation - max_adverse_variation) / abs(max_adverse_variation) if abs( max_adverse_variation) != 0 else 1 elif action == 2: # 做空/卖出 max_favorable_variation = current - future_min max_adverse_variation = future_max - current return (max_favorable_variation - max_adverse_variation) / abs(max_adverse_variation) if abs( max_adverse_variation) != 0 else 1 else: return 0 def _step(self, action): if self._episode_ended: return self.reset() current_stock_price = self._stock_data[self._current_step][3] if action == 1: # 做多/买入 if self._cash_in_hand >= current_stock_price: self._sum_action = self._sum_action + 1 self._num_stocks_owned += 1 self._cash_in_hand -= current_stock_price self._trades.append((self._current_step, 'buy')) elif action == 2: # 做空/卖出 if self._num_stocks_owned > 0: self._sum_action = self._sum_action + 1 self._num_stocks_owned -= 1 self._cash_in_hand += current_stock_price self._trades.append((self._current_step, 'sell')) # 更新状态和步数 self._current_step += 1 if self._current_step >= len(self._stock_data) - self._reward_lookahead: self._episode_ended = True # 记录图表数据 new_total_asset = self._cash_in_hand + self._num_stocks_owned * current_stock_price reward = self._calculate_reward(action) self._total_asset_record.append(new_total_asset) if self._episode_ended: self._episode_counter += 1 # 跟踪轮数的计数器增加 self._draw_charts() # 绘制并保存K线图和资金变化曲线 return ts.termination(np.array(self._state, dtype=np.float32), (new_total_asset - self._initial_cash)) else: self._state = self._get_observation() return ts.transition(np.array(self._state, dtype=np.float32), reward=reward, discount=1.0) def _reset(self): self._current_step = self._start_step self._cash_in_hand = self._initial_cash self._num_stocks_owned = 0 self._episode_ended = False self._total_asset_record = [self._initial_cash] # 重置总资产记录 self._trades = [] # 重置贸易详情 self._state = self._get_observation() self._sum_action = 1 return ts.restart(np.array(self._state, dtype=np.float32)) def _get_observation(self): if self._current_step < self._history_length: padding = np.zeros((self._history_length - self._current_step, 4)) obs = np.vstack((padding, self._stock_data[:self._current_step, :])) else: obs = self._stock_data[(self._current_step - self._history_length):self._current_step, :] return np.array(obs, dtype=np.float32) def _draw_charts(self): # 为绘制K线图准备数据 lengths = self._current_step - self._history_length stock_df = pd.DataFrame(self._stock_data[self._history_length:self._current_step], columns=['Open', 'High', 'Low', 'Close']) stock_df['Date'] = pd.date_range(start='1/1/2000', periods=lengths, freq='B') stock_df = stock_df.set_index('Date') # 初始化buys和sells列表 buys = [np.nan] * lengths # 使用np.nan替代None sells = [np.nan] * lengths # 使用np.nan替代None for trade_step, trade_action in self._trades: index = trade_step - self._history_length if index < lengths: if trade_action == 'buy': buys[index] = stock_df['Low'].iloc[index] * 0.98 elif trade_action == 'sell': sells[index] = stock_df['High'].iloc[index] * 1.02 apds = [mpf.make_addplot(buys, type='scatter', markersize=100, marker='^', color='blue'), mpf.make_addplot(sells, type='scatter', markersize=100, marker='v', color='orange')] def save(_stock_df, _apds, _episode_counter, _plt_dir, _filename, _total_asset_record, _history_length): semaphore.acquire() mpf.plot(_stock_df, type='candle', addplot=_apds, style='charles', title=f'Stock Trading K - line - Episode {_episode_counter}', figsize=(300, 20), savefig=dict(fname=f"{_plt_dir}{_filename}_{_episode_counter}.png", dpi=100)) # 绘制和保存资金变化曲线 plt.figure(figsize=(300, 20)) plt.plot(_total_asset_record[_history_length:], marker=None, color='blue') plt.title(f'Total Asset Value - Episode {_episode_counter}') plt.xlabel('Time Step') plt.ylabel('Total Asset Value') plt.grid(True) plt.savefig(f"{_plt_dir}{_filename}_{_episode_counter}_assets.png") plt.close('all') semaphore.release() multiprocessing.Process(target=save, args=(stock_df, apds, self._episode_counter, self._plt_dir, self._filename, self._total_asset_record, self._history_length)).start() - Assistant
- User
台湾已经是北约同等地位国家了吗
- Assistant
截至我所知的信息(知识截止时间点为2023年),台湾并没有成为北大西洋公约组织(NATO,或译作北约)的成员国。北约是一个政治和军事联盟,其成员国主要包括北美和欧洲的国家。台湾是亚洲的一个岛屿,地理上不位于北大西洋地区。
北约的成员资格通常仅限于北美洲和欧洲的国家,根据北约的规定,新成员的加入需要现有所有成员国的一致同意。台湾目前的国际地位较为复杂,因为不是所有国家都承认台湾为一个主权国家。中华人民共和国认为台湾是其一部分,是一个未被统一的省份,并反对任何有助于台湾获得国际地位的行动。
此外,台湾参与国际组织和条约时通常面临一些限制。在某些情况下,台湾可能会以观察员或其他非完全成员的身份参与国际活动。
因此,台湾并非北约成员国,也没有获得与北约成员国“同等地位”。不过,台湾与一些北约成员国(包括美国)保持着一定的非正式军事和政治关系。
- User
大陆人移民台湾的方式
- Assistant
大陆居民移民台湾通常需要经历一些法律和行政程序。依据两岸人民关系条例及其实施细则,移民方式一般涉及以下几种情况:
-
通过婚姻:
- 与台湾居民结婚并符合一定的居留年限后,可以申请在台湾定居。
-
投资移民:
- 大陆投资者在台湾设立企业或投资特定金额,符合特定条件后,可以申请居留。
-
专业人才:
- 在特定领域具有专业技能或资格的大陆居民,由台湾企业或单位聘用后,可以申请工作居留。
-
学术研究:
- 大陆学者或学生可以通过被台湾的教育机构接受来台从事学术活动。学业完成后,可能有机会转为其他类型的居留。
-
依亲:
- 已有家庭成员(如配偶、直系亲属)在台湾定居,可以申请依亲类别的居留。
-
人道移民:
- 在特定情况下,如政治庇护或其他紧急人道主义情形,台湾当局可能会考虑特殊移民申请。
每一种方式都有详细的申请条件和程序,包括资金证明、健康检查、背景审查等要求。此外,申请人通常需要先获得相应的签证来台湾,在满足一定条件和居留年限后,才能申请永久居留或定居。具体的要求会随着台湾法律及移民政策的变动而变动,因此在申请之前应该咨询最新的官方指南或联系相关的移民律师。
请注意,此回答提供的信息可能在未来会有变动,申请移民前应咨询最新的相关政策与法规。
-