To integrate the functionality from test.py into your project while adhering to your requirements, we'll need to update and create several files within the src directory. Below is a comprehensive plan that outlines the modifications, along with the required code snippets and instructions for running the updated functionality.
1. Modifications Overview
Modified Files
src/services/data_fetcher.py
Reason for Modification: Add methods to fetch concept board names and their historical data.
src/services/data_saver.py
Reason for Modification: Implement a method to save the concept board historical data to the database.
src/services/concept_data_handler.py (New File)
Reason for Creation: Create a dedicated module to handle fetching and saving concept board data, separating concerns from stock and index data.
src/core/config.py (if needed)
Reason for Modification: Ensure configuration values like CSV file paths are available.
2. Modified and New Files
Modified src/services/data_fetcher.py
Add the following methods for fetching concept board data:
python
# src/services/data_fetcher.py
# ... existing imports
import pandas as pd
from src.core.logger import logger
class DataFetcher:
# ... existing methods
@[Redacted Person]
def fetch_concept_board_names():
"""获取概念板块名称和代码"""
try:
logger.info("Fetching concept board names...")
concept_df = ak.stock_board_concept_name_em()
return concept_df
except Exception as e:
logger.error(f"Failed to fetch concept board names: {e}")
raise DataFetchError(f"Failed to fetch concept board names: {e}")
def fetch_concept_board_data(self, board_name):
"""获取概念板块历史数据"""
try:
logger.info(f"Fetching historical data for concept board: {board_name}...")
hist_df = ak.stock_board_concept_hist_em(symbol=board_name)
return hist_df
except Exception as e:
logger.error(f"Failed to fetch historical data for {board_name}: {e}")
raise DataFetchError(f"Failed to fetch historical data for {board_name}: {e}")
Modified src/services/data_saver.py
Add the following method to save concept board data:
python
# src/services/data_saver.py
# ... existing imports
from sqlalchemy.orm import Session
from ..database.models.concept_board import ConceptBoard # Assume the model exists
class DataSaver:
# ... existing methods
def save_concept_board_data_to_db(self, concept_data):
"""保存概念板块历史数据到数据库"""
try:
logger.info("Saving concept board data to database...")
db: Session = next(get_db())
for _, row in concept_data.iterrows():
db.add(ConceptBoard(
concept_name=row['板块名称'],
concept_code=row['板块代码'],
date=row['日期'],
open=row['开盘'],
close=row['收盘'],
high=row['最高'],
low=row['最低'],
change_rate=row['涨跌幅'],
change_amount=row['涨跌额'],
volume=row['成交量'],
amount=row['成交额'],
amplitude=row['振幅'],
turnover_rate=row['换手率'],
total_market_value=None, # Placeholder for future implementation
turnover=None, # Placeholder for future implementation
up_count=None, # Placeholder for future implementation
down_count=None # Placeholder for future implementation
))
db.commit()
logger.info("Concept board data saved successfully.")
except Exception as e:
db.rollback()
logger.error(f"Failed to save concept board data to database: {e}")
raise DataSaveError(f"Failed to save concept board data to database: {e}")
New File src/services/concept_data_handler.py
Create a new file for managing concept data:
python
# src/services/concept_data_handler.py
import pandas as pd
from src.services.data_fetcher import DataFetcher
from src.services.data_saver import DataSaver
from src.core.logger import logger
class ConceptDataHandler:
def __init__(self):
self.fetcher = DataFetcher()
self.saver = DataSaver()
def handle_concept_data(self):
"""处理概念板块数据的获取和保存"""
logger.info("开始处理概念板块数据...")
concept_names = self.fetcher.fetch_concept_board_names()
concept_data = []
for _, row in concept_names.iterrows():
board_name = row['板块名称']
board_code = row['板块代码']
hist_data = self.fetcher.fetch_concept_board_data(board_name)
if hist_data is not None and not hist_data.empty:
hist_data['板块名称'] = board_name
hist_data['板块代码'] = board_code
concept_data.append(hist_data)
if concept_data:
final_df = pd.concat(concept_data)
self.saver.save_concept_board_data_to_db(final_df)
else:
logger.warning("No concept data to save.")
3. How to Run the Implementation
Ensure Database and Model Setup: Make sure the ConceptBoard model exists in your src/database/models/concept_board.py file with the appropriate fields corresponding to the data you are saving.
Run the Concept Data Handler: You can create a script or modify your main application file to run the ConceptDataHandler.
Here’s a sample script (run_concept_data.py) to execute this:
python
# run_concept_data.py
from src.services.concept_data_handler import ConceptDataHandler
if __name__ == "__main__":
handler = ConceptDataHandler()
handler.handle_concept_data()
Execute the Script: Run the script using Python:
bash
python run_concept_data.py
Summary
With the above modifications and new implementations, you can effectively integrate the functionality of fetching and saving concept board data into your existing project structure. This approach ensures that the project is modular and maintainable while allowing for easy updates in the future.