with one click
write-strategy
guide user to write a strategy for msd backtest
Install with Codex or Claude Copy this prompt, paste it into Codex, Claude, or another assistant, and let it review the skill page and install it for you.
Menu
guide user to write a strategy for msd backtest
Install with Codex or Claude Copy this prompt, paste it into Codex, Claude, or another assistant, and let it review the skill page and install it for you.
Based on SOC occupation classification
| name | write_strategy |
| description | guide user to write a strategy for msd backtest |
| tags | ["msd","strategy","backtest"] |
| version | 1 |
| author | elsejj |
This guide will help you to write a strategy for msd backtest.
Programming language: Python 3.11+
msd-backtest[cli] be installed use project package manager.MSD_HOST environment variable be set, can be find in .env file or test by shell command env | grep MSD_HOST. If not set, you can ask the user to set it first.You should create a subclass named Strategy of mbt.Strategy and implement the execute method. The skeleton of the code is shown below:
import mbt
import numpy as np
import alpha as al
# Other libraries can be imported as needed
class Strategy(mbt.Strategy):
def __init__(self):
super().__init__()
# TODO: add your custom parameters to __init__ method if needed.
def execute(self, ctx: mbt.Context):
"""
execute the strategy, this method will be called for each bar.
Args:
ctx: context of the strategy
"""
# TODO: implement strategy, building buy/sell signals then call ctx.buy/ctx.sell
pass
After writing a strategy, you can run it to verify it works as expected.
[uv run] python -m mbt.run.cli <STRATEGY_PATH> -s SH600000 -b 2025-01-01 -e 2025-12-31
uv run can be omitted current workspace not using uv as package manager.
ctx.data(name: str, /, symbol: str | None = None) -> np.ndarray
the primary method to get data, name is the data name, symbol is used only when comparison, keep None for no explicit requirements. name can be:
open, high, low, close, volume, amount, vwap on bar levelror for rate of return since first barror_hold for rate of return of holding since last buy after clearance.limited used to check whether the bar had reached the daily limit. 0 for no limit, 1 for limit up, -1 for limit downtotal_shares: total shares, total stock shares, use to calculate total market capitalization etc.tradable_shares: tradable shares, tradable stock shares, use to calculate tradable market capitalization, turnover etc.Balance Sheet
f008: Cash and Cash Equivalentsf009: Trading Financial Assetsf010: Notes Receivablef011: Accounts Receivablef015: Other Receivablesf016: Contract Liabilitiesf017: Inventoriesf021: Total Current Assetsf025: Long-term Equity Investmentsf026: Investment Propertiesf027: Property, Plant and Equipment (PP&E)f028: Construction in Progress (CIP)f033: Intangible Assetsf034: Development Expendituresf035: Goodwillf039: Total Non-current Assetsf040: Total Assetsf041: Short-term Borrowingsf043: Notes Payablef044: Accounts Payablef045: Advances from Customersf051: Amounts Due to Related Partiesf052: Non-current Liabilities Due Within One Yearf054: Total Current Liabilitiesf055: Long-term Borrowingsf056: Bonds Payablef059: Provisionsf062: Total Non-current Liabilitiesf063: Total Liabilitiesf066: Treasury Stockf068: Retained Earningsf071: Total Shareholders' Equity (Excluding Non-controlling Interests)f073: Total Shareholders' Equity (Including Non-controlling Interests)f074: Total Liabilities and Shareholders' EquityIncome Statement
f075: Revenuef076: Cost of Salesf078: Selling Expensesf079: Administrative Expensesf080: Research and Development (R&D) Expensesf081: Financial Expensesf082: Asset Impairment Lossesf084: Investment Incomef085: Including: Share of Profits of Associates and Joint Venturesf087: Operating Profitf088: Non-GAAP Operating Profitf092: Total Revenuef093: Profit Before Tax (PBT)f095: Total Operating Costsf096: Net Profit (Including Non-controlling Interests)f097: Net Profit Attributable to Shareholders of the ParentCash Flow Statement
f099: Cash Received from Sales of Goods and Rendering of Servicesf102: Cash Inflows from Operating Activities Subtotalf103: Cash Paid for Goods and Servicesf104: Cash Paid to and for Employeesf107: Cash Outflows from Operating Activities Subtotalf108: Net Cash Flows from Operating Activitiesf114: Cash Inflows from Investing Activities Subtotalf115: Cash Paid for Acquisition of Fixed Assets, Intangible Assets and Other Long-term Assetsf116: Cash Paid for Investmentsf117: Net Cash Paid for Acquisition of Subsidiaries and Other Business Unitsf119: Cash Outflows from Investing Activities Subtotalf120: Net Cash Flows from Investing Activitiesf121: Cash Received from Capital Contributionsf123: Cash Received from Borrowingsf125: Cash Inflows from Financing Activities Subtotalf126: Cash Paid for Debt Repaymentsf127: Cash Paid for Dividends, Profits Distribution or Interest Paymentsf130: Cash Outflows from Financing Activities Subtotalf131: Net Cash Flows from Financing Activitiesf134: Net Increase in Cash and Cash Equivalentsf136: Ending Balance of Cash and Cash Equivalentsf137: Net Profitf138: Provision for Asset Impairmentf139: Depreciation of Fixed Assets, Depletion of Oil and Gas Assets, and Depreciation of Productive Biological Assetsf140: Amortization of Intangible Assetsf149: Decrease in Inventoriesf150: Decrease in Operating Receivablesf151: Increase in Operating Payablesf156: Ending Balance of Cashf158: Ending Balance of Cash EquivalentsPer Share Indicators
f000: Diluted Earnings Per Share (Diluted EPS)f001: Book Value per Share-based Returnf002: Operating Cash Flow Per Sharef003: Net Assets Per Share (BVPS)f005: Retained Earnings Per Sharef006: Revenue Per Sharef007: Non-GAAP EPSProfitability Analysis
f205:Annualized Return on Equity (Annualized ROE)f206:Net Return on Total Assetsf207:Return on Invested Capital (ROIC)f208:Cost and Expense Profit Marginf209:Operating Profit Marginf210:COGS-to-Revenue Ratiof211:Net Profit Marginf212:Return on Total Assets (ROA)f213:Gross Profit Marginf214:SG&A and Finance Expenses to Revenue Ratiof215:Selling Expense Ratiof216:Administrative Expense Ratiof217:Financial Expense Ratiof218:Non-operating Income to Total Profit Ratiof219:Operating Profit to Total Profit Ratiof220:EBITDA Per Sharef221:EBIT Per Sharef222:EBITDA MarginSolvency Analysis
f160: Current Ratiof161: Quick Ratiof162: Cash Ratiof163: Debt-to-Equity Ratio (D/E)f164: Equity-to-Assets Ratiof165: Equity-to-Debt Ratiof166: Equity Multiplierf167: Long-term Debt to Working Capital Ratiof168: Long-term Debt Ratiof169: Times Interest Earned (TIE)f172: Debt to Tangible Net Worth Ratiof174: Debt Service Coverage Ratio (DSCR)f175: Operating Cash Flow to Current Liabilities Ratiof177: Working Capital Per Sharef178: Total Debt-to-EBITDA RatioOperating Efficiency Analysis
f179: Operating Cyclef180: Days Inventory Outstanding (再生 DIO)f181: Days Sales Outstanding (再生 DSO)f182: Current Asset Turnover Daysf183: Total Asset Turnover Daysf184: Inventory Turnover Ratiof185: Accounts Receivable Turnover Ratiof186: Current Asset Turnover Ratiof187: Fixed Asset Turnover Ratiof188: Total Asset Turnover Ratiof189: Net Asset Turnover Ratiof190: Equity Turnover Ratiof191: Working Capital Turnover Ratiof192: Inventory Year-on-Year (YoY) Growth Ratef193: Accounts Receivable Year-on-Year (YoY) Growth RateGrowth Ability Analysis
f194: Revenue Growth Ratef195: Operating Profit Growth Ratef196: Total Profit Growth Ratef199: Current Assets Growth Ratef200: Fixed Assets Growth Ratef201: Total Assets Growth Ratef202: Diluted EPS Growth Ratef203: Net Assets Per Share Growth Ratef204: Operating Cash Flow Per Share Growth RateCapital Structure Analysis
f223: Asset-to-Liability Ratiof224: Equity-to-Assets Ratiof225: Long-term Debt Ratiof226: Equity-to-Fixed Assets Ratiof227: Debt-to-Equity Ratiof228: Non-current Assets to Long-term Capital Ratiof229: Capitalization Ratiof231: Fixed Assets to Total Assets RatioCash Flow Analysis
f232: Operating Cash Flow to Sales Ratiof233: Cash Return on Assetsf234: Operating Cash Flow to Net Profit Ratiof235: Operating Cash Flow to Total Debt Ratiof236: Operating Cash Flow Per Sharef237: Net Operating Cash Flow Per Sharef238: Net Investing Cash Flow Per Sharef239: Net Financing Cash Flow Per Sharef240: Net Increase in Cash and Cash Equivalents Per Sharef241: Cash Flow Adequacy Ratiof242: Cash Operating Indexctx.buy(signals: np.ndarray, percent: float = 1.0)
ctx.sell(signals: np.ndarray, percent: float = 1.0)
buy/sell a position, signals is a boolean array of signals, True means buy/sell, percent is the percent of cash/position to buy/sell.List of available functions with python type hints:
the np.ndarray is ndarray type in numpy package
periods windowperiods elements.bins equal-width buckets within the window's [min, max] range, then computes -sum(p * ln(p)) where p is the frequency of each occupied bin. Uses natural log (base e). Requires at least 2 valid values. Single-value windows return 0.is_calc[t+delay] is 0, returns NaN.category value, then computes rank percentage within each group. Same value gets averaged rank. NaN in category or input produces NaN output.category value, then computes (x - group_mean) / group_std within each group. NaN in category or input produces NaN output. Groups with fewer than 2 valid values produce NaN.periods windowperiods period highperiods windowperiods window If periods is 0, it calculates the cumulative product from the first valid value.periods Uses min-rank method for ties (same as pandas rankdata method='min'). NaN values are treated as larger than all non-NaN values.periods, r[i] = input[i - periods]periods window If periods is 0, it calculates the cumulative sum from the first valid value.amountperiods window where condition is trueperiods. Uses sample stddev (ddof=1) to match pandas.