### Initialize and Use CChan Core Analysis Class in Python Source: https://context7.com/vespa314/chan.py/llms.txt Demonstrates how to initialize the `CChan` class for Chanlun analysis. It shows setting up configuration, specifying stock code, date range, data source, K-line levels, and adjustment type. The example also illustrates accessing computed stroke, segment, pivot, and buy/sell point data. ```python from Chan import CChan from ChanConfig import CChanConfig from Common.CEnum import AUTYPE, DATA_SRC, KL_TYPE # Initialize configuration config = CChanConfig({ "bi_strict": True, # Use strict stroke definition "divergence_rate": 0.9, # Divergence threshold for type-1 buy/sell points "min_zs_cnt": 1, # Minimum pivot count for type-1 points "max_bs2_rate": 0.618, # Max retracement for type-2 points "zs_combine": True, # Enable pivot merging }) # Create analysis instance chan = CChan( code="sz.000001", # Stock code (format depends on data source) begin_time="2023-01-01", # Start date end_time="2024-01-01", # End date (None for latest) data_src=DATA_SRC.BAO_STOCK, # Data source lv_list=[KL_TYPE.K_DAY], # K-line levels (high to low) config=config, autype=AUTYPE.QFQ, # Adjustment type (forward/backward/none) ) # Access calculated elements for the first (and only) level kl_data = chan[0] # CKLine_List object # Get stroke list for bi in kl_data.bi_list: print(f"Stroke {bi.idx}: {bi.dir} from {bi.begin_klc[0].time} to {bi.end_klc[-1].time}") # Get segment list for seg in kl_data.seg_list: print(f"Segment {seg.idx}: {seg.dir}, is_sure={seg.is_sure}") # Get pivot/center list for zs in kl_data.zs_list: print(f"Pivot: low={zs.low:.2f}, high={zs.high:.2f}") # Get buy/sell points bsp_list = chan.get_latest_bsp() for bsp in bsp_list: print(f"BSP: {'Buy' if bsp.is_buy else 'Sell'}, types={bsp.type}, at {bsp.klu.time}") ``` -------------------------------- ### Implement Custom Data Source in Python Source: https://context7.com/vespa314/chan.py/llms.txt This snippet illustrates how to create a custom data source by inheriting from CCommonStockApi and implementing the `get_kl_data` method as a generator. The example shows reading data from a list of dictionaries and yielding CKLine_Unit objects, demonstrating how to map data fields and handle optional fields like volume and turnover. It also includes placeholders for initialization and cleanup methods (`do_init`, `do_close`). Dependencies include typing, CEnum, CTime, CKLine_Unit, and CCommonStockApi. ```python from typing import Iterable from Common.CEnum import AUTYPE, DATA_FIELD, KL_TYPE from Common.CTime import CTime from KLine.KLine_Unit import CKLine_Unit from DataAPI.CommonStockAPI import CCommonStockApi class CCustomDataSource(CCommonStockApi): def __init__(self, code, k_type=KL_TYPE.K_DAY, begin_date=None, end_date=None, autype=AUTYPE.QFQ): super(CCustomDataSource, self).__init__(code, k_type, begin_date, end_date, autype) def get_kl_data(self) -> Iterable[CKLine_Unit]: # Example: read from your data source data = [ {"date": "2024-01-02", "open": 100.0, "high": 105.0, "low": 99.0, "close": 104.0, "volume": 1000000}, {"date": "2024-01-03", "open": 104.0, "high": 108.0, "low": 103.0, "close": 107.0, "volume": 1200000}, # ... more data ] for row in data: year, month, day = map(int, row["date"].split("-")) item_dict = { DATA_FIELD.FIELD_TIME: CTime(year, month, day, 0, 0), DATA_FIELD.FIELD_OPEN: float(row["open"]), DATA_FIELD.FIELD_HIGH: float(row["high"]), DATA_FIELD.FIELD_LOW: float(row["low"]), DATA_FIELD.FIELD_CLOSE: float(row["close"]), DATA_FIELD.FIELD_VOLUME: float(row.get("volume", 0)), # Optional DATA_FIELD.FIELD_TURNOVER: float(row.get("amount", 0)), # Optional DATA_FIELD.FIELD_TURNRATE: float(row.get("turnrate", 0)), # Optional } yield CKLine_Unit(item_dict) @classmethod def do_init(cls): # Initialize connection/resources if needed pass @classmethod def do_close(cls): # Cleanup connection/resources if needed pass # Usage with CChan # data_src="custom:YourModule.CCustomDataSource" ``` -------------------------------- ### Serialization and Persistence of CChan State in Python Source: https://context7.com/vespa314/chan.py/llms.txt This example shows how to save the state of a CChan object to a file using pickle serialization and then load it back. This is useful for caching analysis results or resuming interrupted tasks. It also includes increasing the recursion limit for deep copy operations. ```python from Chan import CChan from ChanConfig import CChanConfig from Common.CEnum import DATA_SRC, KL_TYPE import sys # Increase recursion limit for deep copy operations sys.setrecursionlimit(0x100000) config = CChanConfig({}) chan = CChan( code="sz.000001", begin_time="2023-01-01", end_time="2024-01-01", data_src=DATA_SRC.BAO_STOCK, lv_list=[KL_TYPE.K_DAY], config=config, ) # Save to file chan.chan_dump_pickle("chan_state.pkl") # Load from file chan_restored = CChan.chan_load_pickle("chan_state.pkl") # Verify restoration print(f"Original strokes: {len(list(chan[0].bi_list))}") print(f"Restored strokes: {len(list(chan_restored[0].bi_list))}") ``` -------------------------------- ### Implement Trading Strategy with Step-by-Step Backtesting Source: https://context7.com/vespa314/chan.py/llms.txt Enables incremental processing by setting `trigger_step=True` in CChanConfig. This allows iterating through each K-line, analyzing the state, and implementing trading strategies based on buy/sell points and fractal confirmations. ```python from Chan import CChan from ChanConfig import CChanConfig from Common.CEnum import AUTYPE, BSP_TYPE, DATA_SRC, FX_TYPE, KL_TYPE config = CChanConfig({ "trigger_step": True, # Enable step mode "divergence_rate": 0.8, "min_zs_cnt": 1, }) chan = CChan( code="sz.000001", begin_time="2021-01-01", end_time=None, data_src=DATA_SRC.BAO_STOCK, lv_list=[KL_TYPE.K_DAY], config=config, autype=AUTYPE.QFQ, ) # Simple strategy: trade type-1 buy/sell points is_hold = False last_buy_price = None for chan_snapshot in chan.step_load(): bsp_list = chan_snapshot.get_latest_bsp() if not bsp_list: continue last_bsp = bsp_list[0] # Only trade type-1 or type-1p points if BSP_TYPE.T1 not in last_bsp.type and BSP_TYPE.T1P not in last_bsp.type: continue cur_lv = chan_snapshot[0] # Check if the buy/sell point is at the second-to-last combined K-line if last_bsp.klu.klc.idx != cur_lv[-2].idx: continue # Buy on bottom fractal confirmation if cur_lv[-2].fx == FX_TYPE.BOTTOM and last_bsp.is_buy and not is_hold: last_buy_price = cur_lv[-1][-1].close print(f'{cur_lv[-1][-1].time}: BUY @ {last_buy_price}') is_hold = True # Sell on top fractal confirmation elif cur_lv[-2].fx == FX_TYPE.TOP and not last_bsp.is_buy and is_hold: sell_price = cur_lv[-1][-1].close profit = (sell_price - last_buy_price) / last_buy_price * 100 print(f'{cur_lv[-1][-1].time}: SELL @ {sell_price}, profit: {profit:.2f}%') is_hold = False ``` -------------------------------- ### Configure CChanConfig for Financial Analysis Source: https://context7.com/vespa314/chan.py/llms.txt Demonstrates how to initialize CChanConfig with various parameters to control stroke, segment, pivot, and buy/sell point calculations. This includes settings for technical indicators and backtesting modes. ```python from ChanConfig import CChanConfig config = CChanConfig({ # Stroke (Bi) configuration "bi_algo": "normal", # "normal" or "fx" (fractal-based) "bi_strict": True, # Require 5+ K-lines between fractals "bi_fx_check": "strict", # Fractal validation: strict/loss/half/totally "bi_end_is_peak": True, # Stroke end must be highest/lowest point "gap_as_kl": False, # Treat gaps as K-lines # Segment (Seg) configuration "seg_algo": "chan", # "chan" (characteristic sequence), "1+1", "break" "left_seg_method": "peak", # Handle incomplete segments: "all" or "peak" # Pivot (Zhongshu) configuration "zs_combine": True, # Merge overlapping pivots "zs_combine_mode": "zs", # Merge mode: "zs" or "peak" "one_bi_zs": False, # Calculate single-stroke pivots "zs_algo": "normal", # "normal" (within segment), "over_seg" (cross-segment) # Buy/Sell Point configuration "divergence_rate": 0.9, # MACD divergence threshold for type-1 "min_zs_cnt": 1, # Minimum pivot count for type-1 "max_bs2_rate": 0.9999, # Max retracement ratio for type-2 "bs1_peak": True, # Type-1 must be at pivot extreme "bs_type": "1,1p,2,2s,3a,3b", # Types to calculate "macd_algo": "peak", # Divergence algo: peak/area/full_area/slope/amp # Technical indicators "mean_metrics": [5, 20, 60], # Moving average periods "trend_metrics": [20], # Channel periods (high/low) "boll_n": 20, # Bollinger Bands period "cal_demark": False, # Calculate DeMark indicator "cal_rsi": False, # Calculate RSI "cal_kdj": False, # Calculate KDJ # Step-by-step mode (for backtesting) "trigger_step": False, # Enable incremental mode "skip_step": 0, # Skip first N K-lines }) ``` -------------------------------- ### Iterate Combined K-lines and Strokes in Python Source: https://context7.com/vespa314/chan.py/llms.txt Demonstrates iterating through combined K-lines (CKLine) and individual K-lines (KLU) within them. It also shows how to iterate through strokes (CBi), segments (CSeg), pivots (CZS), and buy/sell points (BSP) from the kl_data object. ```python # Iterate combined K-lines (CKLine) for klc in kl_data.lst: print(f"Combined K-line {klc.idx}: fx={klc.fx}, high={klc.high}, low={klc.low}") # Access individual K-lines within combined K-line for klu in klc.lst: print(f" K-line: time={klu.time}, O={klu.open}, H={klu.high}, L={klu.low}, C={klu.close}") # Iterate strokes (CBi) for bi in kl_data.bi_list: print(f"Stroke {bi.idx}:") print(f" Direction: {'UP' if bi.dir == BI_DIR.UP else 'DOWN'}") print(f" Start: {bi.get_begin_klu().time} @ {bi.get_begin_val()}") print(f" End: {bi.get_end_klu().time} @ {bi.get_end_val()}") print(f" Confirmed: {bi.is_sure}") # Iterate segments (CSeg) for seg in kl_data.seg_list: print(f"Segment {seg.idx}:") print(f" Direction: {seg.dir}") print(f" Strokes: {seg.start_bi.idx} to {seg.end_bi.idx}") print(f" Pivot count: {len(seg.zs_lst)}") for zs in seg.zs_lst: print(f" Pivot: [{zs.low:.2f}, {zs.high:.2f}]") # Iterate pivots/centers (CZS) for zs in kl_data.zs_list: print(f"Pivot: low={zs.low:.2f}, high={zs.high:.2f}, mid={zs.mid:.2f}") print(f" Peak range: [{zs.peak_low:.2f}, {zs.peak_high:.2f}]") print(f" Entry stroke: {zs.bi_in.idx if zs.bi_in else None}") print(f" Exit stroke: {zs.bi_out.idx if zs.bi_out else None}") # Get buy/sell points for bsp in kl_data.bs_point_lst: type_str = ",".join([t.value for t in bsp.type]) print(f"BSP: {'BUY' if bsp.is_buy else 'SELL'} type={type_str} at {bsp.klu.time}") ``` -------------------------------- ### Multi-Level Analysis with CChan in Python Source: https://context7.com/vespa314/chan.py/llms.txt This snippet demonstrates how to perform multi-level analysis using the CChan class, allowing simultaneous analysis of different timeframes (e.g., daily and 60-minute). It shows initialization, accessing data for specific levels, and navigating relationships between K-lines across levels. ```python from Chan import CChan from ChanConfig import CChanConfig from Common.CEnum import DATA_SRC, KL_TYPE config = CChanConfig({ "kl_data_check": True, # Validate level alignment "max_kl_misalgin_cnt": 5, # Max allowed misaligned K-lines }) # Multi-level: Daily + 60-minute chan = CChan( code="sz.000001", begin_time="2023-01-01", end_time="2024-01-01", data_src=DATA_SRC.BAO_STOCK, lv_list=[KL_TYPE.K_DAY, KL_TYPE.K_60M], # High to low config=config, ) # Access daily level daily_data = chan[KL_TYPE.K_DAY] # or chan[0] print(f"Daily strokes: {len(list(daily_data.bi_list))}") # Access 60-minute level m60_data = chan[KL_TYPE.K_60M] # or chan[1] print(f"60M strokes: {len(list(m60_data.bi_list))}") # Navigate between levels via K-line relationships for klu in daily_data.lst[0].lst: # First daily combined K-line # Get sub-level K-lines within this daily K-line print(f"Daily K-line {klu.time} contains {len(klu.sub_kl_list)} 60M K-lines") for sub_klu in klu.sub_kl_list: print(f" 60M: {sub_klu.time}") ``` -------------------------------- ### Feed External K-line Data with trigger_load Source: https://context7.com/vespa314/chan.py/llms.txt Utilizes `trigger_load()` to bypass built-in data sources and feed K-lines from external sources, suitable for real-time trading applications. Requires separate initialization of the data source. ```python from Chan import CChan from ChanConfig import CChanConfig from Common.CEnum import AUTYPE, DATA_SRC, KL_TYPE from DataAPI.BaoStockAPI import CBaoStock config = CChanConfig({ "trigger_step": True, "divergence_rate": 0.8, }) # Initialize CChan (data_src params are ignored when using trigger_load) chan = CChan( code="sz.000001", begin_time="2021-01-01", end_time=None, data_src=DATA_SRC.BAO_STOCK, lv_list=[KL_TYPE.K_DAY], config=config, autype=AUTYPE.QFQ, ) # Initialize data source separately CBaoStock.do_init() data_src = CBaoStock( code="sz.000001", k_type=KL_TYPE.K_DAY, begin_date="2021-01-01", end_date=None, autype=AUTYPE.QFQ ) ``` -------------------------------- ### Feed K-lines and Access Analysis State in Python Source: https://context7.com/vespa314/chan.py/llms.txt This snippet demonstrates how to feed K-line data one by one to a CChan object and then access the latest analysis state, specifically the Buy/Sell Points (BSP). It iterates through data, triggers loading, retrieves BSP, and prints the current state if available. Dependencies include data_src and KL_TYPE. ```python # Feed K-lines one by one for klu in data_src.get_kl_data(): # Feed single K-line to CChan chan.trigger_load({KL_TYPE.K_DAY: [klu]}) # Access current analysis state bsp_list = chan.get_latest_bsp() if bsp_list: print(f"Current BSP at {bsp_list[0].klu.time}: {bsp_list[0].type}") CBaoStock.do_close() ``` -------------------------------- ### Enumerations Reference for Chan Framework in Python Source: https://context7.com/vespa314/chan.py/llms.txt This section lists and briefly describes key enumerations used within the Chan framework. These enumerations are crucial for configuring analysis parameters and interpreting results, covering K-line types, data sources, adjustment types, stroke directions, fractal types, buy/sell point types, and MACD algorithms. ```python from Common.CEnum import ( KL_TYPE, # K-line timeframes DATA_SRC, # Data sources AUTYPE, # Adjustment types BI_DIR, # Stroke directions FX_TYPE, # Fractal types BSP_TYPE, # Buy/sell point types MACD_ALGO, # MACD algorithms ) # K-line types (timeframes) # KL_TYPE.K_1M, K_3M, K_5M, K_15M, K_30M, K_60M # KL_TYPE.K_DAY, K_WEEK, K_MON, K_QUARTER, K_YEAR # Data sources # DATA_SRC.BAO_STOCK - BaoStock API (China A-shares) # DATA_SRC.AKSHARE - AkShare API # DATA_SRC.CCXT - Cryptocurrency exchanges # DATA_SRC.CSV - CSV files # Adjustment types # AUTYPE.QFQ - Forward adjustment (前复权) # AUTYPE.HFQ - Backward adjustment (后复权) # AUTYPE.NONE - No adjustment # Stroke directions # BI_DIR.UP - Upward stroke # BI_DIR.DOWN - Downward stroke # Fractal types # FX_TYPE.TOP - Top fractal # FX_TYPE.BOTTOM - Bottom fractal # FX_TYPE.UNKNOWN - Not determined # Buy/sell point types # BSP_TYPE.T1 - Type 1 (trend reversal) # BSP_TYPE.T1P - Type 1P (consolidation divergence) # BSP_TYPE.T2 - Type 2 (retracement) # BSP_TYPE.T2S - Type 2S (secondary retracement) # BSP_TYPE.T3A - Type 3A (breakout after T1) # BSP_TYPE.T3B - Type 3B (breakout before T1) ``` -------------------------------- ### Visualize Analysis Results with CPlotDriver in Python Source: https://context7.com/vespa314/chan.py/llms.txt This snippet shows how to use CPlotDriver to visualize the analysis results computed by CChan. It involves configuring which elements to plot (K-lines, strokes, MACD, etc.) and defining their appearance through plot_config and plot_para dictionaries. The final visualization is saved to an image file. Dependencies include CChan, CChanConfig, CEnum, and PlotDriver. ```python from Chan import CChan from ChanConfig import CChanConfig from Common.CEnum import AUTYPE, DATA_SRC, KL_TYPE from Plot.PlotDriver import CPlotDriver config = CChanConfig({}) chan = CChan( code="sz.000001", begin_time="2023-01-01", end_time="2024-01-01", data_src=DATA_SRC.BAO_STOCK, lv_list=[KL_TYPE.K_DAY], config=config, autype=AUTYPE.QFQ, ) # Define what to plot plot_config = { "plot_kline": True, # K-line candles "plot_kline_combine": True, # Combined K-lines "plot_bi": True, # Strokes "plot_seg": True, # Segments "plot_zs": True, # Pivots/Centers "plot_bsp": True, # Buy/sell points "plot_macd": True, # MACD indicator "plot_eigen": False, # Characteristic sequence (debug) "plot_boll": False, # Bollinger Bands "plot_mean": False, # Moving averages } # Configure plot appearance plot_para = { "figure": { "w": 24, # Figure width "h": 10, # Figure height "macd_h": 0.3, # MACD subplot height ratio "x_range": 100, # Show last N K-lines (0=all) }, "bi": { "color": "black", "show_num": True, # Show stroke numbers "disp_end": True, # Show end prices }, "seg": { "color": "g", "width": 5, "plot_trendline": True, # Draw trend lines }, "zs": { "color": "orange", "linewidth": 2, "show_text": True, # Show high/low values }, } # Create plot plot_driver = CPlotDriver(chan, plot_config=plot_config, plot_para=plot_para) # Save to file plot_driver.save2img("analysis.png") ``` -------------------------------- ### Access Computed Elements from CChan in Python Source: https://context7.com/vespa314/chan.py/llms.txt This snippet demonstrates how to access computed analysis elements such as strokes, segments, pivots, and buy/sell points after they have been calculated by the CChan object. It shows that these elements can be retrieved from the `CKLine_List` object obtained by indexing the CChan instance with the desired level (e.g., `chan[0]` for the first level). Dependencies include CChan, CChanConfig, CEnum, and BSP_TYPE, BI_DIR. ```python from Chan import CChan from ChanConfig import CChanConfig from Common.CEnum import DATA_SRC, KL_TYPE, BSP_TYPE, BI_DIR chan = CChan( code="sz.000001", begin_time="2023-01-01", end_time="2024-01-01", data_src=DATA_SRC.BAO_STOCK, lv_list=[KL_TYPE.K_DAY], ) kl_data = chan[0] ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.