制作交易收盘价走势图:JSON格式

2023-10-28 11:30

本文主要是介绍制作交易收盘价走势图:JSON格式,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

JSON格式

JSON格式的文件使用json模块来处理。
下面看一个JSON文件里面的内容是什么样子的:
在这里插入图片描述
就是一个很长的Python列表,其中每个元素都是一个包含五个键的字典:统计日期,月份,周数,周几以及收盘价。

下载收盘数据

from __future__ import (absolute_import, division, print_function,unicode_literals)
try:# Python 2.x 版本from urllib2 import urlopen
except ImportError:# Python 3.x 版本from urllib.request import urlopen  # 1
import json
import requests
import pygal
import math
from itertools import groupbyjson_url = 'https://raw.githubusercontent.com/muxuezi/btc/master/btc_close_2017.json'
response = urlopen(json_url)  # 2
# 读取数据
req = response.read()
# 将数据写入文件
with open('btc_close_2017_urllib.json', 'wb') as f:  # 3f.write(req)
# 加载json格式
file_urllib = json.loads(req.decode('utf8'))  # 4
print(file_urllib)json_url = 'https://raw.githubusercontent.com/muxuezi/btc/master/btc_close_2017.json'
req = requests.get(json_url)  # 1
# 将数据写入文件
with open('btc_close_2017_request.json', 'w') as f:f.write(req.text)  # 2
file_requests = req.json()  # 3print(file_urllib == file_requests)

提取相关的数据

下面编写一个小程序来提取btc_close_2017.json文件中的相关信息:

import json#将数据加载到一个列表中
filename='btc_close_2017.json'
with open(filename) as f:btc_data=json.load(f)#打印每一天的信息
for btc_dict in btc_data:date=btc_dict['date']month=btc_dict['month']week=btc_dict['week']weekday=btc_dict['weekday']close=btc_dict['close']print("{} is month{}week{},{},the close price is {}RMB".format(date,month,week,weekday,close))

在这里插入图片描述

import json#将数据加载到一个列表中
filename='btc_close_2017.json'
with open(filename) as f:btc_data=json.load(f)#打印每一天的信息
for btc_dict in btc_data:date=btc_dict['date']month=int(btc_dict['month'])week=int(btc_dict['week'])weekday=btc_dict['weekday']close=int(btc_dict['close'])print("{} is month{}week{},{},the close price is {}RMB".format(date,month,week,weekday,close))

我们运行来试试,看看结果如何
在这里插入图片描述
没想到出现了异常错误,在实际工作中,原始数据的格式经常不是统一的,此类数值类型转换造成的ValueError异常十分普遍,这里的原因在于,Python不能直接将包含小数点的字符串‘6928.6492’转换为整数。为了消除这种错误,需要先将字符串转换为浮点数(float),再将浮点数转换为整数(int):

import json#将数据加载到一个列表中
filename='btc_close_2017.json'
with open(filename) as f:btc_data=json.load(f)#打印每一天的信息
for btc_dict in btc_data:date=btc_dict['date']month=int(btc_dict['month'])week=int(btc_dict['week'])weekday=btc_dict['weekday']close=int(float(btc_dict['close']))print("{} is month{}week{},{},the close price is {}RMB".format(date,month,week,weekday,close))

在这里插入图片描述
好了,解决了。

绘制收盘价折线图

之前了解过了pygal绘制条形图(bar chart)和matplotlib绘制折线图(line chart),下面用Pygal来实现收盘价的折线图

import json
import pygal#将数据加载到一个列表中
filename='btc_close_2017.json'
with open(filename) as f:btc_data=json.load(f)#创建5个列表,分别存储日期和收盘价
dates=[]
months=[]
weeks=[]
weekdays=[]
close=[]#打印每一天的信息
for btc_dict in btc_data:dates.append(btc_dict['date'])months.append(int(btc_dict['month']))weeks.append(int(btc_dict['week']))weekdays.append(btc_dict['weekday'])close.append(int(float(btc_dict['close'])))#print("{} is month{}week{},{},the close price is {}RMB".format(date,month,week,weekday,close))line_chart=pygal.Line(x_label_rotation=20,show_minor_x_labels=False)
line_chart.title='收盘价(RMB)'
line_chart.x_labels=dates
N=20 #x轴坐标每隔20天显示一次
line_chart.add('收盘价',close)
line_chart.render_to_file('收盘价折线图.svg')

运行后,会在文件保存的目录下面生成一个.svg文件
在这里插入图片描述
然后用浏览器打开如下图:

在这里插入图片描述

时间序列特征初探

进行时间序列分析总是期望发现趋势(trend)、周期性(seasonality)和噪声(noise),从而能够描述事实、预测未来、做出决策。对数变换(log transformation)是可以将波动中非线性的趋势消除。Python标准库的数学模块math来解决,我i们用以10为底的对数函数math.log10计算收盘价,日期仍然保持不变,这种方式称为半对数变换(semi-logarithmic)。

import json
import pygal
import math#将数据加载到一个列表中
filename='btc_close_2017.json'
with open(filename) as f:btc_data=json.load(f)#创建5个列表,分别存储日期和收盘价
dates=[]
months=[]
weeks=[]
weekdays=[]
close=[]#打印每一天的信息
for btc_dict in btc_data:dates.append(btc_dict['date'])months.append(int(btc_dict['month']))weeks.append(int(btc_dict['week']))weekdays.append(btc_dict['weekday'])close.append(int(float(btc_dict['close'])))#print("{} is month{}week{},{},the close price is {}RMB".format(date,month,week,weekday,close))line_chart=pygal.Line(x_label_rotation=20,show_minor_x_labels=False)
line_chart.title='收盘价对数变换(RMB)'
line_chart.x_labels=dates
N=20 #x轴坐标每隔20天显示一次
line_chart.x_labels_major=dates[::N]
close_log=[math.log10(_)for _ in close]
line_chart.add('log收盘价',close_log)
line_chart.render_to_file('收盘价折线图.svg')

在这里插入图片描述
现在用对数变换剔除非线性趋势之后,整体上涨的趋势更接近线性增长,并且从图中可以看出每个季度末似乎有显著的周期性—3月、6月、9月都出现了波动,那么,按照这样的推算12月是不是也会出现这样的波动呢?下面看看收盘的月日均值和周日均值的表现。

收盘价均值

import json
import pygal
import math
from itertools import groupby#将数据加载到一个列表中
filename='btc_close_2017.json'
with open(filename) as f:btc_data=json.load(f)#创建5个列表,分别存储日期和收盘价
dates=[]
months=[]
weeks=[]
weekdays=[]
close=[]#打印每一天的信息
for btc_dict in btc_data:dates.append(btc_dict['date'])months.append(int(btc_dict['month']))weeks.append(int(btc_dict['week']))weekdays.append(btc_dict['weekday'])close.append(int(float(btc_dict['close'])))#print("{} is month{}week{},{},the close price is {}RMB".format(date,month,week,weekday,close))line_chart = pygal.Line(x_label_rotation=20, show_minor_x_labels=False)  # ①
line_chart.title = '收盘价(¥)'
line_chart.x_labels = dates
N = 20  # x轴坐标每隔20天显示一次
line_chart.x_labels_major = dates[::N]  # ②
line_chart.add('收盘价', close)
line_chart.render_to_file('收盘价折线图(¥).svg')line_chart = pygal.Line(x_label_rotation=20, show_minor_x_labels=False)
line_chart.title = '收盘价对数变换(¥)'
line_chart.x_labels = dates
N = 20  # x轴坐标每隔20天显示一次
line_chart.x_labels_major = dates[::N]
close_log = [math.log10(_) for _ in close]  # ①
line_chart.add('log收盘价', close_log)
line_chart.render_to_file('收盘价对数变换折线图(¥).svg')
line_chartdef draw_line(x_data, y_data, title, y_legend):xy_map = []for x, y in groupby(sorted(zip(x_data, y_data)), key=lambda _: _[0]):  # 2y_list = [v for _, v in y]xy_map.append([x, sum(y_list) / len(y_list)])  # 3x_unique, y_mean = [*zip(*xy_map)]  # 4line_chart = pygal.Line()line_chart.title = title#line_chart.x_labels = x_uniquex_unique_str=int_str(x_unique)line_chart.x_labels = x_unique_strline_chart.add(y_legend, y_mean)line_chart.render_to_file(title + '.svg')return line_chartdef int_str(list_0):list_1=[]for x in list_0:x_str=str(x)list_1.append(x_str)return list_1idx_month = dates.index('2017-12-01')
line_chart_month = draw_line(months[:idx_month], close[:idx_month], '收盘价月日均值(¥)', '月日均值')
line_chart_monthidx_week = dates.index('2017-12-11')
line_chart_week = draw_line(weeks[1:idx_week], close[1:idx_week], '收盘价周日均值(¥)', '周日均值')
line_chart_weekidx_week = dates.index('2017-12-11')
wd = ['Monday', 'Tuesday', 'Wednesday','Thursday', 'Friday', 'Saturday', 'Sunday']
weekdays_int = [wd.index(w) + 1 for w in weekdays[1:idx_week]]
line_chart_weekday = draw_line(weekdays_int, close[1:idx_week], '收盘价星期均值(¥)', '星期均值')
line_chart_weekday.x_labels = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
line_chart_weekday.render_to_file('收盘价星期均值(¥).svg')
line_chart_weekdaywith open('收盘价Dashboard.html', 'w', encoding='utf8') as html_file:html_file.write('<html><head><title>收盘价Dashboard</title><meta charset="utf-8"></head><body>\n')for svg in ['收盘价折线图(¥).svg', '收盘价对数变换折线图(¥).svg', '收盘价月日均值(¥).svg','收盘价周日均值(¥).svg', '收盘价星期均值(¥).svg']:html_file.write('    <object type="image/svg+xml" data="{0}" height=500></object>\n'.format(svg))  # 1html_file.write('</body></html>')

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

再写上面的代码时,出现了一个错误,如下,总是提示
在这里插入图片描述
是x轴的数据有问题,x轴应该修改为数值型str,修改方式如下:
在这里插入图片描述

这篇关于制作交易收盘价走势图:JSON格式的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/292912

相关文章

Python实现网格交易策略的过程

《Python实现网格交易策略的过程》本文讲解Python网格交易策略,利用ccxt获取加密货币数据及backtrader回测,通过设定网格节点,低买高卖获利,适合震荡行情,下面跟我一起看看我们的第一... 网格交易是一种经典的量化交易策略,其核心思想是在价格上下预设多个“网格”,当价格触发特定网格时执行买

Python进行JSON和Excel文件转换处理指南

《Python进行JSON和Excel文件转换处理指南》在数据交换与系统集成中,JSON与Excel是两种极为常见的数据格式,本文将介绍如何使用Python实现将JSON转换为格式化的Excel文件,... 目录将 jsON 导入为格式化 Excel将 Excel 导出为结构化 JSON处理嵌套 JSON:

SpringBoot 异常处理/自定义格式校验的问题实例详解

《SpringBoot异常处理/自定义格式校验的问题实例详解》文章探讨SpringBoot中自定义注解校验问题,区分参数级与类级约束触发的异常类型,建议通过@RestControllerAdvice... 目录1. 问题简要描述2. 异常触发1) 参数级别约束2) 类级别约束3. 异常处理1) 字段级别约束

详解MySQL中JSON数据类型用法及与传统JSON字符串对比

《详解MySQL中JSON数据类型用法及与传统JSON字符串对比》MySQL从5.7版本开始引入了JSON数据类型,专门用于存储JSON格式的数据,本文将为大家简单介绍一下MySQL中JSON数据类型... 目录前言基本用法jsON数据类型 vs 传统JSON字符串1. 存储方式2. 查询方式对比3. 索引

C#解析JSON数据全攻略指南

《C#解析JSON数据全攻略指南》这篇文章主要为大家详细介绍了使用C#解析JSON数据全攻略指南,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录一、为什么jsON是C#开发必修课?二、四步搞定网络JSON数据1. 获取数据 - HttpClient最佳实践2. 动态解析 - 快速

MySQL 8 中的一个强大功能 JSON_TABLE示例详解

《MySQL8中的一个强大功能JSON_TABLE示例详解》JSON_TABLE是MySQL8中引入的一个强大功能,它允许用户将JSON数据转换为关系表格式,从而可以更方便地在SQL查询中处理J... 目录基本语法示例示例查询解释应用场景不适用场景1. ‌jsON 数据结构过于复杂或动态变化‌2. ‌性能要

Spring的RedisTemplate的json反序列泛型丢失问题解决

《Spring的RedisTemplate的json反序列泛型丢失问题解决》本文主要介绍了SpringRedisTemplate中使用JSON序列化时泛型信息丢失的问题及其提出三种解决方案,可以根据性... 目录背景解决方案方案一方案二方案三总结背景在使用RedisTemplate操作redis时我们针对

MySQL查询JSON数组字段包含特定字符串的方法

《MySQL查询JSON数组字段包含特定字符串的方法》在MySQL数据库中,当某个字段存储的是JSON数组,需要查询数组中包含特定字符串的记录时传统的LIKE语句无法直接使用,下面小编就为大家介绍两种... 目录问题背景解决方案对比1. 精确匹配方案(推荐)2. 模糊匹配方案参数化查询示例使用场景建议性能优

Mysql常见的SQL语句格式及实用技巧

《Mysql常见的SQL语句格式及实用技巧》本文系统梳理MySQL常见SQL语句格式,涵盖数据库与表的创建、删除、修改、查询操作,以及记录增删改查和多表关联等高级查询,同时提供索引优化、事务处理、临时... 目录一、常用语法汇总二、示例1.数据库操作2.表操作3.记录操作 4.高级查询三、实用技巧一、常用语

springboot项目打jar制作成镜像并指定配置文件位置方式

《springboot项目打jar制作成镜像并指定配置文件位置方式》:本文主要介绍springboot项目打jar制作成镜像并指定配置文件位置方式,具有很好的参考价值,希望对大家有所帮助,如有错误... 目录一、上传jar到服务器二、编写dockerfile三、新建对应配置文件所存放的数据卷目录四、将配置文