I'm trying to iterate over positions in Zipline results, but the positions are in string format so there is no index to iterate over.
Here's my code to get the Zipline results setup:
#import zipline backtest
from quantrocket.zipline import backtest
from quantrocket.zipline import ZiplineBacktestResult
import pandas as pd
backtest(
'third_zipline_example',
start_date = "2003-01-01",
end_date = "2020-06-30",
capital_base = 10000,
data_frequency = 'daily',
bundle = 'dow30-1d-bundle',
filepath_or_buffer="example_3_results.csv"
)
zipline_result = ZiplineBacktestResult.from_csv("example_3_results.csv")
# Select day to view
day = '2009-03-17'
# Get portfolio value and positions for this day
port_value = zipline_result.perf.loc[day,'portfolio_value']
day_positions = zipline_result.perf.loc[day,'positions']
And here's the code to setup a dataframe and iterate to get the position data:
# Empty DataFrame to store values
df = pd.DataFrame(columns = ['value', 'pnl'])
# Populate DataFrame with position info
for pos in day_positions:
ticker = pos['sid'].symbol
df.loc[ticker,'value'] = pos['amount'] * pos['last_sale_price']
df.loc[ticker,'pnl'] = df.loc[ticker,'value'] - (pos['amount'] * pos['cost_basis'])
Here's the error I'm getting when trying to iterate with the for loop:
TypeError: string indices must be integers
When I view type(day_posiitons), it comes back as a string.
Is there any way to get the positions data as a list that I can iterate over and execute math functions on the integers?
Please advise.
David