I was trying to troubleshoot why the returns for NG doesn’t tally, until I printed out the entire continuous series in an excel, and realised that it’s not adjusting the data. It’s just stitching together raw data.
Code and screenshot below.
Any idea why? Appreciate any help
import pandas as pd
import zipline
from zipline.api import (
schedule_function, date_rules, time_rules, continuous_future, set_commission, set_slippage,
get_datetime, order_target, record, symbol
)
def initialize(context):
# Create a continuous future for the asset you're interested in
context.cf = continuous_future('NG', offset=0, roll='volume', adjustment='mul')
# Schedule the function to run at the end of each day
schedule_function(collect_data, date_rules.every_day(), time_rules.market_close())
# Initialize an empty list to store daily data
context.data_list = []
def collect_data(context, data):
# Collect data for the continuous future
current_date = get_datetime().date()
price = data.current(context.cf, 'price')
volume = data.current(context.cf, 'volume')
contract = data.current(context.cf, 'contract')
# Append the data to our list
context.data_list.append({
'date': current_date,
'price': price,
'volume': volume,
'contract': contract
})
def analyze(context, perf):
# Convert the list of dictionaries to a DataFrame
df = pd.DataFrame(context.data_list)
# Print the entire DataFrame
print(df)
# Optionally, save to CSV
df.to_csv('continuous_future_data.csv', index=False)
if __name__ == '__main__':
start = pd.Timestamp('2023-01')
end = pd.Timestamp('2024-01-01')
results = zipline.run_algorithm(
start=start,
end=end,
initialize=initialize,
capital_base=10000000,
data_frequency='daily',
bundle='csi_futures_data',
analyze=analyze
)