美文网首页
【StudyQuant| Python量化投资课堂系列2】如何使

【StudyQuant| Python量化投资课堂系列2】如何使

作者: StudyQuant量化投资 | 来源:发表于2019-03-14 23:25 被阅读0次

前言

如果你想入门量化,了解更多量化投资知识,欢迎点击加入关注我们的「量化投资博客」,欢迎大家加入。
也欢迎大神交流投资,互相学习。个人VX: 82789754

StudyQuant量化投资学院 计划在未来逐步公开以下内容:

前置条件

开始之前,安装PyMongo和Mongo。确保在python交互界面执行import不报错:

通过MongoClient建立一个连接。

开始使用PyMongo的第一步是创建一个MongoClient,对应于MongoDB实例。操作起来so easy:

# 数据库连接
import pymongo
from pymongo import MongoClient
client = MongoClient()

上面代码将会连接默认的host和port。当然也可指定:

client = MongoClient('localhost', 27017)

或者用 MongoDB URI 格式:

client = MongoClient('mongodb://localhost:27017/')

获取数据库

MongoDB的单个实例可以支持多个独立的 数据库。使用PyMongo时,您可以使用MongoClient实例上的属性样式访问来访问数据库:

db  =  client [ 'test-database' ]

使用JSON样式的文档表示(并存储)MongoDB中的数据。在PyMongo中,我们使用字典来表示文档。例如,以下字典可能用于表示博客帖子:

import datetime
post = {"author": "Mike",
         "text": "My first blog post!",
         "tags": ["mongodb", "python", "pymongo"],
         "date": datetime.datetime.utcnow()}

post
{'author': 'Mike',
 'date': datetime.datetime(2018, 11, 23, 13, 27, 14, 313779),
 'tags': ['mongodb', 'python', 'pymongo'],
 'text': 'My first blog post!'}

插入文档

要将文档插入集合,我们可以使用以下 insert_one()方法:

posts = db.posts
post_id = posts.insert_one(post).inserted_id
post_id
ObjectId('5bf8007810599866ec48c317')

插入文档时"_id",如果文档尚未包含"_id"密钥,则会自动添加特殊键。"_id"整个集合中的值必须是唯一的。insert_one()返回一个实例InsertOneResult。有关更多信息"_id",请参阅_id上的文档。

插入第一个文档后,实际上已在服务器上创建了posts集合。我们可以通过在数据库中列出所有集合来验证这一点:

db.collection_names(include_system_collections = False)
C:\Anaconda3.4.3\lib\site-packages\ipykernel\__main__.py:1: DeprecationWarning: collection_names is deprecated. Use list_collection_names instead.
  if __name__ == '__main__':
['posts']

用获取单个文档find_one()

可以在MongoDB中执行的最基本类型的查询是 find_one()。此方法返回与查询匹配的单个文档(或者None如果没有匹配项)。当您知道只有一个匹配的文档,或者只对第一个匹配感兴趣时,它很有用。这里我们用来 find_one()从posts集合中获取第一个文档:

import pprint
pprint.pprint(posts.find_one())
{'_id': ObjectId('5bf8007810599866ec48c317'),
 'author': 'Mike',
 'date': datetime.datetime(2018, 11, 23, 13, 27, 14, 313000),
 'tags': ['mongodb', 'python', 'pymongo'],
 'text': 'My first blog post!'}

If we try with a different author, like “Eliot”, we’ll get no result:

posts.find_one({"author": "Mike"})
{'_id': ObjectId('5bf8007810599866ec48c317'),
 'author': 'Mike',
 'date': datetime.datetime(2018, 11, 23, 13, 27, 14, 313000),
 'tags': ['mongodb', 'python', 'pymongo'],
 'text': 'My first blog post!'}

通过ObjectId查询

 pprint.pprint(posts.find_one({"_id": post_id}))

{'_id': ObjectId('5bf8007810599866ec48c317'),
 'author': 'Mike',
 'date': datetime.datetime(2018, 11, 23, 13, 27, 14, 313000),
 'tags': ['mongodb', 'python', 'pymongo'],
 'text': 'My first blog post!'}

批量插入¶

为了使查询更有趣,让我们再插入一些文档。除了插入单个文档之外,我们还可以通过将列表作为第一个参数传递来执行批量插入操作insert_many()。这将在列表中插入每个文档,只向服务器发送一个命令:

new_posts = [{"author": "Mike",
              "text": "Another post!",
               "tags": ["bulk", "insert"],
               "date": datetime.datetime(2009, 11, 12, 11, 14)},
              {"author": "Eliot",
               "title": "MongoDB is fun",
               "text": "and pretty easy too!",
               "date": datetime.datetime(2009, 11, 10, 10, 45)}]
result = posts.insert_many(new_posts)
result.inserted_ids

[ObjectId('5bf8023910599866ec48c318'), ObjectId('5bf8023910599866ec48c319')]

查询多个文档

要获取查询结果以外的多个文档,我们使用该 find() 方法。find()返回一个 Cursor实例,它允许我们迭代所有匹配的文档。例如,我们可以迭代posts集合中的每个文档:

for post in posts.find():
    pprint.pprint(post)
{'_id': ObjectId('5bf8007810599866ec48c317'),
 'author': 'Mike',
 'date': datetime.datetime(2018, 11, 23, 13, 27, 14, 313000),
 'tags': ['mongodb', 'python', 'pymongo'],
 'text': 'My first blog post!'}
{'_id': ObjectId('5bf8023910599866ec48c318'),
 'author': 'Mike',
 'date': datetime.datetime(2009, 11, 12, 11, 14),
 'tags': ['bulk', 'insert'],
 'text': 'Another post!'}
{'_id': ObjectId('5bf8023910599866ec48c319'),
 'author': 'Eliot',
 'date': datetime.datetime(2009, 11, 10, 10, 45),
 'text': 'and pretty easy too!',
 'title': 'MongoDB is fun'}

计数

 posts.count_documents({})
3

索引¶

添加索引可以帮助加速某些查询,还可以添加其他功能来查询和存储文档。在此示例中,我们将演示如何在键上创建唯一索引,该索引拒绝索引中已存在该键值的文档。

首先,我们需要创建索引:

result = db.profiles.create_index([('user_id', pymongo.ASCENDING)],
                                   unique=True)
sorted(list(db.profiles.index_information()))
[u'_id_', u'user_id_1']
['_id_', 'user_id_1']
user_profiles = [
     {'user_id': 211, 'name': 'Luke'},
     {'user_id': 212, 'name': 'kevin'}]
result = db.profiles.insert_many(user_profiles)

new_profile = {'user_id': 213, 'name': 'Drew'}

result = db.profiles.insert_one(new_profile)  # This is fine.

duplicate_profile = {'user_id': 212, 'name': 'Tommy'}
result = db.profiles.insert_one(duplicate_profile)
---------------------------------------------------------------------------

DuplicateKeyError                         Traceback (most recent call last)

<ipython-input-60-533650ecd4e1> in <module>()
----> 1 result = db.profiles.insert_one(duplicate_profile)

C:\Anaconda3.4.3\lib\site-packages\pymongo\collection.py in insert_one(self, document, bypass_document_validation, session)
    691                          write_concern=write_concern,
    692                          bypass_doc_val=bypass_document_validation,
--> 693                          session=session),
    694             write_concern.acknowledged)
    695 

C:\Anaconda3.4.3\lib\site-packages\pymongo\collection.py in _insert(self, docs, ordered, check_keys, manipulate, write_concern, op_id, bypass_doc_val, session)
    605             return self._insert_one(
    606                 docs, ordered, check_keys, manipulate, write_concern, op_id,
--> 607                 bypass_doc_val, session)
    608 
    609         ids = []

C:\Anaconda3.4.3\lib\site-packages\pymongo\collection.py in _insert_one(self, doc, ordered, check_keys, manipulate, write_concern, op_id, bypass_doc_val, session)
    593 
    594         self.__database.client._retryable_write(
--> 595             acknowledged, _insert_command, session)
    596 
    597         if not isinstance(doc, RawBSONDocument):

C:\Anaconda3.4.3\lib\site-packages\pymongo\mongo_client.py in _retryable_write(self, retryable, func, session)
   1246         """Internal retryable write helper."""
   1247         with self._tmp_session(session) as s:
-> 1248             return self._retry_with_session(retryable, func, s, None)
   1249 
   1250     def __reset_server(self, address):

C:\Anaconda3.4.3\lib\site-packages\pymongo\mongo_client.py in _retry_with_session(self, retryable, func, session, bulk)
   1199                             raise last_error
   1200                         retryable = False
-> 1201                     return func(session, sock_info, retryable)
   1202             except ServerSelectionTimeoutError:
   1203                 if is_retrying():

C:\Anaconda3.4.3\lib\site-packages\pymongo\collection.py in _insert_command(session, sock_info, retryable_write)
    590                 retryable_write=retryable_write)
    591 
--> 592             _check_write_command_response(result)
    593 
    594         self.__database.client._retryable_write(

C:\Anaconda3.4.3\lib\site-packages\pymongo\helpers.py in _check_write_command_response(result)
    215     write_errors = result.get("writeErrors")
    216     if write_errors:
--> 217         _raise_last_write_error(write_errors)
    218 
    219     error = result.get("writeConcernError")

C:\Anaconda3.4.3\lib\site-packages\pymongo\helpers.py in _raise_last_write_error(write_errors)
    196     error = write_errors[-1]
    197     if error.get("code") == 11000:
--> 198         raise DuplicateKeyError(error.get("errmsg"), 11000, error)
    199     raise WriteError(error.get("errmsg"), error.get("code"), error)
    200 

DuplicateKeyError: E11000 duplicate key error collection: test-database.profiles index: user_id_1 dup key: { : 212 }

前言

如果你想入门量化,了解更多量化投资知识,欢迎点击加入关注我们的「量化投资博客」,欢迎大家加入。
也欢迎大神交流投资,互相学习。个人VX: 82789754

更多量化学习资源

扫上方二维码,关注公众账号 量化投资学院 ,获取下列免费资源

  • 回复“热点研报”,获取近年热点券商金融工程研究报告

  • 回复“Python3”,获取Python免费学习教程

  • 回复“Python”,获取免费Python量化投资入门课程

相关文章

网友评论

      本文标题:【StudyQuant| Python量化投资课堂系列2】如何使

      本文链接:https://www.haomeiwen.com/subject/zyxkmqtx.html