问题:当时处理股票数据,获取到以dataframe数据结构的股票,由于Redis 是一个内存中的数据结构存储系统,但是不接受dataframe数据结构的数据,选择将其先转化为JSON格式,但发现再将JSON格式转化为原数据时,数据发生篡改。
如 002855是股票'捷荣技术'的股票代码,会被篡改为2855,001301是'尚太科技'的股票代码,会被篡改为1301,造成这样的原因是JSON数据转换时将原字符串类型的数据自动转为了数字
解决方法:我使用了pickle模块,将dataframe对象转换为字节流进行存储,下面是示例代码:
# get_stock_historical_data 函数用于从Redis中获取股票的历史数据(近六个月到最近一个交易日),如果没有缓存数据则从数据源获取,并存储到Redis中的哈希表中。 def get_stock_six_months_historical_data(stock_code): cached_stock_six_months_historical_df_bytes = r.hget('stock_six_months_historical_df_bytes', stock_code) if cached_stock_six_months_historical_df_bytes: stock_six_months_historical_df = pickle.loads(cached_stock_six_months_historical_df_bytes) else: stock_six_months_historical_df = ak.stock_zh_a_hist(symbol=stock_code, period="daily", start_date=six_months_ago.strftime("%Y%m%d"), end_date=latest_trade_date.strftime("%Y%m%d"), adjust="") stock_six_months_historical_df_bytes = pickle.dumps(stock_six_months_historical_df) r.hset('stock_six_months_historical_df_bytes', stock_code, stock_six_months_historical_df_bytes) r.expire('stock_six_months_historical_df_bytes', 60 * 60 * 2) return stock_six_months_historical_df