Files
etf/visualization/charts/kline.py
aszerW 988c2335fb chore(config): 添加环境变量示例及.gitignore更新
- 新增 .env.example,包含 Tushare API、钉钉机器人和PostgreSQL数据库配置模板
- 更新.gitignore,忽略本地配置文件如 .env.local 和 config_local.py
- 添加对报表文件命名规则的支持,保留示例文件不忽略
- 删除废弃的 chart.py 及相关图表模块代码
- 新增 config/settings.py,实现从环境变量读取配置的统一接口
- 设置数据目录及缓存目录,确保目录存在,提高配置管理规范性
2026-03-18 23:33:40 +08:00

98 lines
2.6 KiB
Python

"""
K线图表组件
基于lightweight-charts的K线图表
"""
import pandas as pd
from lightweight_charts import Chart
from datetime import datetime
class KlineChart:
"""K线图表类"""
def __init__(self, title: str = "K线图", toolbox: bool = True):
self.title = title
self.toolbox = toolbox
self.chart = None
self.subcharts = {}
def create(self, maximize: bool = True) -> Chart:
"""创建图表实例"""
self.chart = Chart(toolbox=self.toolbox, inner_height=0.8, maximize=maximize)
self.chart.layout(font_family="Times New Roman")
self.chart.legend(visible=True, font_size=14, color="#FFFFFF")
return self.chart
def set_data(self, df: pd.DataFrame, time_col: str = "time"):
"""设置K线数据"""
if self.chart is None:
self.create()
# 验证数据
required_cols = ["open", "high", "low", "close", "volume"]
missing = [c for c in required_cols if c not in df.columns]
if missing:
raise ValueError(f"缺少必要列: {missing}")
# 确保时间列格式正确
df = df.copy()
if time_col in df.columns:
df[time_col] = pd.to_datetime(df[time_col])
self.chart.set(df)
def set_visible_range(self, start_time: datetime, end_time: datetime):
"""设置可见范围"""
if self.chart:
self.chart.set_visible_range(start_time, end_time)
def add_topbar_text(self, key: str, text: str):
"""添加顶部栏文本"""
if self.chart:
self.chart.topbar.textbox(key, text)
def show(self, block: bool = True):
"""显示图表"""
if self.chart:
self.chart.show(block=block)
def create_kline_chart(
df: pd.DataFrame,
symbol: str,
name: str,
timeframe: str,
init_visible_bars: int = 90,
) -> Chart:
"""
快速创建K线图表
Args:
df: DataFrame with OHLCV data
symbol: 标的代码
name: 标的名称
timeframe: 时间周期
init_visible_bars: 初始可见K线数量
Returns:
Chart实例
"""
chart = KlineChart()
chart.create(maximize=True)
chart.add_topbar_text("symbol", symbol)
chart.add_topbar_text("name", name)
chart.add_topbar_text("timeframe", timeframe)
chart.set_data(df)
# 设置初始可见范围
if len(df) > init_visible_bars:
end_time = df["time"].iloc[-1]
start_time = df["time"].iloc[-init_visible_bars]
chart.set_visible_range(start_time, end_time)
return chart.chart