通过tushare获取股票价格

# Author llll

# coding=utf-8


# ---
描述
#
完成股票 价格查询和展示
#
不直接根据网页进行爬虫获取股票价格,而是通过已有组件查询股票价格,并保存到csv文件或者excel文件
# Tushare
是一个免费、开源的python财经数据接口包。主要实现对股票等金融数据从数据采集、清洗加工 数据存储的过程,能够为金融分析人员提供快速、整洁、和多样的便于分析的数据。
#
安装命令 pip install tushare

#
正文
import tushare as ts


#
获取历史价格
def get_gp_ls(gp_code, gp_name):
'''
获取股票历史价格
:param gp_code:
标识股票代码
:param gp_name:
股票名称

:return:
'''
path="D:\\python\\excel_export\\"
df_gp =ts.get_hist_data(gp_code)
print("
获取", gp_name, "历史价格")
print(type(df_gp))
print(df_gp)
df_gp.to_excel(path+gp_name+".xls")
# xls_save(gp_name+".xls",df_gp)

if __name__ == "__main__":
get_gp_ls("600050", "
中国联通")
get_gp_ls("300267", "
尔康制药")
#
尔康制药300267
#
联通股票600050


转载于:https://www.cnblogs.com/programer-xinmu78/p/10706321.html

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的示例代码,使用tushare获取股票数据,然后使用gym和keras进行强化学习: ```python import tushare as ts import gym from gym import spaces import numpy as np from keras.models import Sequential from keras.layers import Dense, Activation, Flatten from keras.optimizers import Adam class StockTradingEnv(gym.Env): def __init__(self): super(StockTradingEnv, self).__init__() # 加载股票数据 self.df = ts.get_k_data('000001', start='2010-01-01', end='2019-01-01') self.df = self.df.sort_values('date') # 定义可用的操作 self.action_space = spaces.Discrete(2) # 定义观察空间 self.observation_space = spaces.Box(low=0, high=1, shape=(6,)) # 保存当前的股票价格、持仓数量、现金余额等信息 self.current_step = 0 self.stock_price = 0 self.stock_owned = 0 self.cash_in_hand = 10000 def _next_observation(self): obs = np.array([ self.df.loc[self.current_step, 'open'] / self.stock_price, self.df.loc[self.current_step, 'high'] / self.stock_price, self.df.loc[self.current_step, 'low'] / self.stock_price, self.df.loc[self.current_step, 'close'] / self.stock_price, self.df.loc[self.current_step, 'volume'] / 1000, self.cash_in_hand / self.stock_price ]) return obs def _take_action(self, action): self.stock_price = self.df.loc[self.current_step, 'close'] action_type = action - 1 # 0为买入,1为卖出 if action_type == 0: # 买入股票 self.stock_owned += (self.cash_in_hand / self.stock_price) self.cash_in_hand -= (self.stock_owned * self.stock_price) elif action_type == 1: # 卖出股票 self.cash_in_hand += (self.stock_owned * self.stock_price) self.stock_owned = 0 def step(self, action): # 执行操作 self._take_action(action) # 更新状态 self.current_step += 1 if self.current_step > len(self.df) - 1: self.current_step = 0 obs = self._next_observation() # 计算奖励 reward = self.cash_in_hand + self.stock_owned * self.stock_price - 10000 # 判断是否游戏结束 done = False if self.cash_in_hand <= 0 or self.stock_owned < 0: done = True # 返回结果 return obs, reward, done, {} def reset(self): self.current_step = 0 self.stock_price = self.df.loc[self.current_step, 'close'] self.stock_owned = 0 self.cash_in_hand = 10000 return self._next_observation() env = StockTradingEnv() state_size = env.observation_space.shape[0] action_size = env.action_space.n # 定义神经网络模型 model = Sequential() model.add(Dense(32, input_dim=state_size, activation='relu')) model.add(Dense(16, activation='relu')) model.add(Dense(action_size, activation='linear')) model.compile(loss='mse', optimizer=Adam()) # 训练模型 batch_size = 32 num_episodes = 1000 for e in range(num_episodes): state = env.reset() state = np.reshape(state, [1, state_size]) for time in range(500): action = np.argmax(model.predict(state)[0]) next_state, reward, done, _ = env.step(action) next_state = np.reshape(next_state, [1, state_size]) model.fit(state, reward, epochs=1, verbose=0) state = next_state if done: print("episode: {}/{}, score: {}".format(e, num_episodes, time)) break ``` 该示例仅用于演示目的,实际上股票交易的环境和策略可能比这个更加复杂。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值