python+Sqlite+Dataframe打造金融股票数据结构
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python+Sqlite+Dataframe打造金融股票数据结构,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2566字,纯文字阅读大概需要4分钟。
内容图文
很简单的用本地Sqlite查找股票数据。
DataSource类,返回的是Dataframe物件。这个Dataframe物件,在之后的业务,如计算股票指标,还需要特别处理。
import os import sqlite3 as sqlite3 import numpy as np import pandas as pd # 数据源 class DataSource: def __init__(self): self.db = None # 数据库 self.cursor = None # 指针 self.stocks = {} # 股票池 self.indexs = {} # 指数池 self.name = ‘unit_test.db‘ # 数据源名称 def connect(self): self.db = sqlite3.connect(os.path.abspath(self.name)) self.cursor = self.db.cursor() def get_stocks(self, ucodes): # 股票池 try: self.stocks = {} self.connect() self.db.row_factory = lambda cursor, row: row[0] for ucode in ucodes: sql = """SELECT t.code, t.lot, t.nmll, t.stime, t.high, t.low, t.open, t.close, t.volume FROM (SELECT n.code, n.lot, n.nmll, c.stime, c.high, c.low, c.open, c.close, c.volume FROM s_{} AS c INNER JOIN name AS n ON c.code=n.code ORDER BY c.stime DESC LIMIT 365*20) AS t /*INNER JOIN financial AS f ON t.code=f.code AND substr(t.stime,1,4)=f.year*/ ORDER BY t.stime""".format(ucode) self.cursor.execute(sql) columns = [‘code‘, ‘lot‘, ‘nmll‘, ‘sdate‘, ‘high‘, ‘low‘, ‘open‘, ‘last‘, ‘vol‘] self.stocks[ucode] = pd.DataFrame(self.cursor.fetchall(), columns=columns) self.db.commit() self.cursor.close() self.db.close() return self.stocks except sqlite3.Error as e: print(e) def get_indexs(self, indexs): try: # 指数池 self.indexs = {} self.connect() self.db.row_factory = lambda cursor, row: row[0] for index in indexs: sql = """SELECT t.code, t.lot, t.nmll, t.stime, t.high, t.low, t.open, t.close, t.volume FROM (SELECT n.code, n.lot, n.nmll, c.stime, c.high, c.low, c.open, c.close, c.volume FROM s_{} AS c INNER JOIN name AS n ON c.code=n.code ORDER BY c.stime DESC LIMIT 365*20) AS t /*INNER JOIN financial AS f ON t.code=f.code AND substr(t.stime,1,4)=f.year*/ ORDER BY t.stime""".format(index.upper()) self.cursor.execute(sql) columns = [‘code‘, ‘lot‘, ‘nmll‘, ‘sdate‘, ‘high‘, ‘low‘, ‘open‘, ‘last‘, ‘vol‘] self.indexs[index] = pd.DataFrame(self.cursor.fetchall(), columns=columns) self.db.commit() self.cursor.close() self.db.close() return self.indexs except sqlite3.Error as e: print(e) data_source = DataSource() df1 = data_source.get_stocks([‘00700‘]) df2 = data_source.get_indexs([‘hsi‘])
python+Sqlite+Dataframe打造金融股票数据结构
标签:font commit 5* com import open print rom tor
本文系统来源:https://www.cnblogs.com/chenkuang/p/12236519.html
内容总结
以上是互联网集市为您收集整理的python+Sqlite+Dataframe打造金融股票数据结构全部内容,希望文章能够帮你解决python+Sqlite+Dataframe打造金融股票数据结构所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。