30天学会量化交易模型 Day03
常用参数说明:
excel_writer: 文件路径或者ExcelWriter对象
sheet_name:sheet名称,默认为Sheet1
sep : 文件内容分隔符,默认为,逗号
na_rep: 在遇到NaN值时保存为某字符,默认为’‘空字符
float_format: float类型的格式
columns: 需要保存的列,默认为None
header: 是否保存columns名,默认为True
index: 是否保存index,默认为True
encoding: 文件编码格式
startrow: 在数据的头部留出startrow行空行
startcol :在数据的左边留出startcol列空列
tushare数据保存到SQL数据库文件
df.to_sql(表名,数据库的连接器)
引用官方的参数:
pandas.DataFrame.to_sql
DataFrame.to_sql(name, con, flavor=None, schema=None, if_exists='fail', index=True, index_label=None,chunksize=None, dtype=None)[source]
Write records stored in a DataFrame to a SQL database.
Parameters:
name : string
Name of SQL table
con : SQLAlchemy engine or DBAPI2 connection (legacy mode)
Using SQLAlchemy makes it possible to use any DB supported by that library. If a DBAPI2 object, only sqlite3 is supported.
flavor : ‘sqlite’, default None
DEPRECATED: this parameter will be removed in a future version, as ‘sqlite’ is the only supported option if SQLAlchemy is not installed.
schema : string, default None
Specify the schema (if database flavor supports this). If None, use default schema.
if_exists : {‘fail’, ‘replace’, ‘append’}, default ‘fail’
fail: If table exists, do nothing.
replace: If table exists, drop it, recreate it, and insert data.
append: If table exists, insert data. Create if does not exist.
index : boolean, default True
Write DataFrame index as a column.
index_label : string or sequence, default None
Column label for index column(s). If None is given (default) and index is True, then the index names are used. A sequence should be given if the DataFrame uses MultiIndex.
chunksize : int, default None
If not None, then rows will be written in batches of this size at a time. If None, all rows will be written at once.
dtype : dict of column name to SQL type, default None
Optional specifying the datatype for columns. The SQL type should be a SQLAlchemy type, or a string for sqlite3 fallback connection.
这里只支持sqlalchemy和sqlite。 所以如果是用的mysql,需要安装sqlalchemy的插件才行。
这里使用简单的sqlite3 作为例子:
import sqlite3这样,数据就保存到到名字为testdb.db的数据库中,表名为 newtable
db=sqlite3.connect("testdb.db")
df = ts.get_k_data('300333',start='2016-01-01',end='2016-12-28')
df.to_sql("newtable",db,flavor='sqlite')
上一篇:30天学会量化交易模型 Day02
http://30daydo.com/article/13
下一篇:30天学会量化交易模型 Day04 (tushare获取破新高的股票)
链接: http://www.30daydo.com/article/70
9 个评论
如果一定要保存为excel文件,需要手工写代码实现。 我之前折腾过一阵子,需要用到excel的一些库,可以实现。
import numpy as np
import pandas as pd
import tushare as ts
import openpyxl
import sqlite3
db = sqlite3.connect('testdb.db')
df = ts.get_k_data('300333', start = '2016-01-01', end = '2016-12-28')
df.to_sql('newtable', self.db, flavor = 'sqlite')