如何将 OHLCV 命名数据数组转换为 numpy 数据帧?
Posted
技术标签:
【中文标题】如何将 OHLCV 命名数据数组转换为 numpy 数据帧?【英文标题】:How to convert a OHLCV named data array into a numpy dataframe? 【发布时间】:2020-12-09 08:59:01 【问题描述】:我的数据由一个特定的 OHLCV 对象组成,有点奇怪,它只能通过名称访问,如下所示:
# rA = [<MtApi.MqlRates object at 0x000000A37A32B308>,...]
type(rA)
# <class 'list'>
ccnt = len(rA) # 100
for i in range(ccnt):
print(' '.format(i, rA[i].MtTime, rA[i].Open, rA[i].High, rA[i].Low, rA[i].Close, rA[i].TickVolume))
#0 1607507400 0.90654 0.90656 0.90654 0.90656 7
#1 1607507340 0.90654 0.9066 0.90653 0.90653 20
#2 1607507280 0.90665 0.90665 0.90643 0.90653 37
#3 1607507220 0.90679 0.90679 0.90666 0.90666 22
#4 1607507160 0.90699 0.90699 0.90678 0.90678 29
我有一些额外的格式:
Time Open High Low Close Volume
-----------------------------------------------------------------
1607507400 0.90654 0.90656 0.90654 0.90656 7
1607507340 0.90654 0.90660 0.90653 0.90653 20
1607507280 0.90665 0.90665 0.90643 0.90653 37
1607507220 0.90679 0.90679 0.90666 0.90666 22
我尝试过这样的事情:
df = pd.DataFrame(data = rA, index = range(100), columns = ['MtTime', 'Open', 'High','Low', 'Close', 'TickVolume'])
# Resulting in:
# TypeError: iteration over non-sequence
如何将此thing 转换为 Panda DataFrame, 这样我就可以使用原始名称进行绘制?
然后应该可以使用 matplotlib 进行绘图,如下所示:
import matplotlib.pyplot as plt
import pandas as pd
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()
...
df = pd.DataFrame(rA) # not working
df['time'] = pd.to_datetime(df['MtTime'], unit='s')
plt.plot(df['MtTime'], df['Open'], 'r-', label='Open')
plt.plot(df['MtTime'], df['Close'], 'b-', label='Close')
plt.legend(loc='upper left')
plt.title('EURAUD candles')
plt.show()
可能相关的问题(但对我没有帮助):
Numpy / Matplotlib - Transform tick data into OHLCV OHLC aggregator doesn't work with dataframe on pandas? How to convert a pandas dataframe into a numpy array with the column names Converting Numpy Structured Array to Pandas Dataframes Pandas OHLC aggregation on OHLC data Getting Open, High, Low, Close for 5 min stock data python Converting OHLC stock data into a different timeframe with python and pandas【问题讨论】:
【参考方案1】:一个想法是使用列表推导将值提取到元组列表:
L = [(rA[i].MtTime, rA[i].Open, rA[i].High, rA[i].Low, rA[i].Close, rA[i].TickVolume)
for i in range(len(rA))]
df = pd.DataFrame(L, columns = ['MtTime', 'Open', 'High','Low', 'Close', 'TickVolume']))
或者如果可能的话:
df = pd.DataFrame('MtTime':list(rA.MtTime), 'Open':list(rA.Open),
'High':list(rA.High),'Low':list(rA.Low),
'Close':list(rA.Close), 'TickVolume':list(rA.TickVolume))
【讨论】:
第一部作品!第二个给:AttributeError: 'list' object has no attribute 'MtTime'
.以上是关于如何将 OHLCV 命名数据数组转换为 numpy 数据帧?的主要内容,如果未能解决你的问题,请参考以下文章
如何将包装为字符串的向量转换为熊猫数据框中的numpy数组?
如何将稀疏的 pandas 数据帧转换为 2d numpy 数组