microsoft / qlib

Qlib is an AI-oriented quantitative investment platform that aims to realize the potential, empower research, and create value using AI technologies in quantitative investment, from exploring ideas to implementing productions. Qlib supports diverse machine learning modeling paradigms. including supervised learning, market dynamics modeling, and RL.
https://qlib.readthedocs.io/en/latest/
MIT License
15.18k stars 2.6k forks source link

how to visualize positions data? #1478

Closed CharlieChi closed 1 year ago

CharlieChi commented 1 year ago

❓ Questions and Help

positions = recorder.load_object("portfolio_analysis/positions_normal_1day.pkl")

the historical positions in backtest is a nested dict. how to transfer it into a dataframe or some sorts to give a better view?

We sincerely suggest you to carefully read the documentation of our library as well as the official paper. After that, if you still feel puzzled, please describe the question clearly under this issue.

Fivele-Li commented 1 year ago

Hi, you can try the following code to see if it can solve your problem.

positions_df = pd.DataFrame(columns=['symbol', 'amount', 'price'])

for date, position in positions.items():
    for symbol, _position in position.position.items():
        if symbol == 'yourSymbol':
            positions_df = positions_df.append({
                'price': _position['price'],
                'symbol': symbol,
                'amount': _position['amount']
            }, ignore_index=True)
CharlieChi commented 1 year ago

Hi, you can try the following code to see if it can solve your problem.

positions_df = pd.DataFrame(columns=['symbol', 'amount', 'price'])

for date, position in positions.items():
    for symbol, _position in position.position.items():
        if symbol == 'yourSymbol':
            positions_df = positions_df.append({
                'price': _position['price'],
                'symbol': symbol,
                'amount': _position['amount']
            }, ignore_index=True)

thanks with a little customization it works perfectly

positions_list = []
for date, position in positions.items():
    for symbol, _position in position.position.items():
        if symbol.startswith(("SH.", "SZ.")):
            positions_list.append({
                'date': date,
                'price': _position['price'],
                'symbol': symbol,
                'amount': _position['amount']
            })
positions_df = pd.DataFrame(positions_list)