An Example Method of class Class Obtaining Financial Data in python

  • 2021-08-17 00:34:25
  • OfStack

When we collect financial data, we usually want to use crawler methods. In fact, the class we learned recently can not only make class calls, but also be feasible in obtaining data. Many small partners pay more attention to financial management and need more financial data. The following is an explanation of how class class obtains financial data in python.

Use tushare to obtain daily trading data of all A shares, save them to the local database, and update the database every day; Visual and simple strategy analysis and back test according to market data. Due to the limited space, this paper focuses on the object-oriented programming application examples of stock data management (downloading and data updating).


# Import required modules 
import numpy as np
import pandas as pd
from dateutil.parser import parse
from datetime import datetime,timedelta
# Operate the first of the database 3 Square package, install before use pip install sqlalchemy
from sqlalchemy import create_engine
#tushare Package settings 
import tushare as ts
token=' Enter your tushare Obtained on token'
pro=ts.pro_api(token)
# Use python3 Bring your own sqlite Database 
# The database address I created is c:\zjy\db_stock\
file='sqlite:///c:\\zjy\\db_stock\\'
# Database name 
db_name='stock_data.db'
engine = create_engine(file+db_name)
class Data(object):
  def __init__(self,
         start='20050101',
         end='20191115',
         table_name='daily_data'):
    self.start=start
    self.end=end
    self.table_name=table_name
    self.codes=self.get_code()
    self.cals=self.get_cals()    
  # Get a list of stock codes   
  def get_code(self):
    codes = pro.stock_basic(list_status='L').ts_code.values
    return codes
  # Get the stock trading calendar 
  def get_cals(self):
    # Get the transaction calendar 
    cals=pro.trade_cal(exchange='')
    cals=cals[cals.is_open==1].cal_date.values
    return cals
  # Daily market data 
  def daily_data(self,code):
    try:
      df0=pro.daily(ts_code=code,start_date=self.start,
        end_date=self.end)      
      df1=pro.adj_factor(ts_code=code,trade_date='') 
      # Complex weight factor 
      df=pd.merge(df0,df1) # Merge data 
    except Exception as e:
      print(code)
      print(e)
    return df
  # Save data to database 
  def save_sql(self):
    for code in self.codes:
      data=self.daily_data(code)
      data.to_sql(self.table_name,engine,
         index=False,if_exists='append')
  # Get the latest transaction date 
  def get_trade_date(self):
    # Get the date and time of the day 
    pass
  # Update database data 
  def update_sql(self):
    pass # Code omission 
  # Query database information       
  def info_sql(self):

Code running


# Suppose you encapsulate the above code into class Data
# Save in 'C:\zjy\db_stock' Directory down_data.py Medium 
import sys
# Add to current work path 
sys.path.append(r'C:\zjy\db_stock')
# Import py In the file Data Class 
from download_data import Data
# Instance class 
data=Data()
#data.save_sql() # Just run 1 You can do it once 
data.update_sql()   
data.info_sql()

Instance extension:

Under Python, pandas_datareader module can be used to obtain research data. Examples are as follows:


>>> from pandas_datareader.data import DataReader
>>>
>>> datas = DataReader(name='AAPL', data_source='yahoo', start='2018-01-01')
>>>
>>> type(datas)
<class 'pandas.core.frame.DataFrame'>
>>> datas
         Open    High     Low    Close  Adj Close \
Date
2018-01-02 170.160004 172.300003 169.259995 172.259995 172.259995
2018-01-03 172.529999 174.550003 171.960007 172.229996 172.229996
2018-01-04 172.539993 173.470001 172.080002 173.029999 173.029999
2018-01-05 173.440002 175.369995 173.050003 175.000000 175.000000
2018-01-08 174.350006 175.610001 173.929993 174.350006 174.350006
2018-01-09 174.550003 175.059998 173.410004 174.330002 174.330002
2018-01-10 173.160004 174.300003 173.000000 174.289993 174.289993
2018-01-11 174.589996 175.490005 174.490005 175.279999 175.279999
2018-01-12 176.179993 177.360001 175.649994 177.089996 177.089996

       Volume
Date
2018-01-02 25555900
2018-01-03 29517900
2018-01-04 22434600
2018-01-05 23660000
2018-01-08 20567800
2018-01-09 21584000
2018-01-10 23959900
2018-01-11 18667700
2018-01-12 25226000
>>>
>>> print(datas.to_csv())
Date,Open,High,Low,Close,Adj Close,Volume
2018-01-02,170.160004,172.300003,169.259995,172.259995,172.259995,25555900
2018-01-03,172.529999,174.550003,171.960007,172.229996,172.229996,29517900
2018-01-04,172.539993,173.470001,172.080002,173.029999,173.029999,22434600
2018-01-05,173.440002,175.369995,173.050003,175.0,175.0,23660000
2018-01-08,174.350006,175.610001,173.929993,174.350006,174.350006,20567800
2018-01-09,174.550003,175.059998,173.410004,174.330002,174.330002,21584000
2018-01-10,173.160004,174.300003,173.0,174.289993,174.289993,23959900
2018-01-11,174.589996,175.490005,174.490005,175.279999,175.279999,18667700
2018-01-12,176.179993,177.360001,175.649994,177.089996,177.089996,25226000

>>>

Related articles: