gpt4 book ai didi

python - 商品 future 分层数据结构

转载 作者:行者123 更新时间:2023-11-28 16:42:58 27 4
gpt4 key购买 nike

我这辈子似乎无法获得我想要的结构并使其正常运行,所以我一怒之下来找你们。

设置:我有一个名为 Futures_Contracts 的目录,里面有大约 30 个文件夹,全部以标的 Assets 命名,最后在 6 个最近的 csv 格式的到期合约中。每个 csv 格式相同,包含日期、O、H、L、C、V、OI、到期月份。

注意:O H L C V OI 是开盘价、最高价、最低价、收盘价、成交量、持仓量(对于那些不熟悉的人)也假设收盘价是下面结算的同义词

Folder Structure

任务:从这里开始,目标是将 future 数据加载到多指数 pandas 数据框中,顶级指数是基础商品符号,中级指数是到期月-年,最后是 OHLC 数据。最终目标是让我可以开始破解 zipline 模块,让它在 futures 上运行。所以在视觉上: enter image description here

我的微弱尝试:

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from pandas import DataFrame, Series
import datetime
plt.figsize(16,8)

deliveries = {}
commoidities = {}
columns = 'open', 'high', 'low', 'settle', 'volume', 'interest', 'delivery' #Contract fields
path = os.getcwdu()+'/Futures_Contracts/' #Futures Path
for sym in os.listdir(path):
if sym[0] != '.': #Weed out hidden files
deliveries[sym] = []
i = 0
for contract in os.listdir(path + sym):
temp = pd.io.parsers.read_csv(path + sym + '/' + contract, index_col=0, parse_dates = True, names = columns)#pull in the csv
deliveries[sym].append(str(contract[:-4][-1] + contract[:-4][:-1][-2:])) #add contract to dict in form of MonthCode-YY
commodities[sym] = deliveries[sym]
commodities[sym][i] = temp
i += 1

这有点管用,但是这实际上是一个嵌套的字典,最后包含一个数据框。因此切片非常笨重:

commodities['SB2'][0]['settle'].plot()
commodities['SB2'][3]['settle'].plot()
commodities['SB2'][4]['settle'].plot()
commodities['SB2'][3]['settle'].plot()
commodities['SB2'][4]['settle'].plot()
commodities['SB2'][5]['settle'].plot()

并产生 enter image description here

最理想的情况是,我将能够对每个索引进行切片,以便我可以跨 Assets 、到期日、日期和值(value)来比较数据。此外标记我正在查看的内容,正如您在 matplotlib 图表中看到的那样,所有内容都被简单地命名为“settle”

肯定有办法做到这一点,但我不够聪明,无法弄清楚。

最佳答案

我认为将其放入一个 DataFrame 会更好,因此请考虑使用 MultiIndex。这是一个玩具示例,我认为它可以很好地转化为您的代码:

In [11]: dfN13 = pd.DataFrame([[1, 2]], columns=[['N13', 'N13'], ['a', 'b']])

In [12]: dfM13 = pd.DataFrame([[3, 4]], columns=[['M13', 'M13'], ['a', 'b']])

这些是您示例中的 DataFrame,但列的第一级只是 Assets 名称。

In [13]: df = pd.concat([dfN13, dfM13], axis=1)

In [14]: df
Out[14]:
N13 M13
a b a b
0 1 2 3 4

为方便起见,我们可以标记列级别和索引。

In [15]: df.columns.names = ['asset', 'chart']

In [16]: df.index.names = ['date'] # well, not in this toy example

In [17]: df
Out[17]:
asset N13 M13
chart a b a b
date
0 1 2 3 4

注意:这看起来很像您的电子表格。

我们可以使用 xs 抓取特定图表(例如 ohlc):

In [18]: df.xs('a', level='chart', axis=1)
Out[18]:
asset N13 M13
date
0 1 3

In [19]: df.xs('a', level='chart', axis=1).plot() # win

关于python - 商品 future 分层数据结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17178263/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com