Ruby或Python中的财务图表

12 投票
8 回答
19978 浏览
提问于 2025-04-15 12:43

我想知道在像Ruby或Python这样的高级编程语言中,制作一个金融的开盘-最高-最低-收盘(OHLC)图表的最佳选择是什么?虽然有很多图表绘制的选项,但我还没看到有什么库可以直接用来做这种图表。

http://en.wikipedia.org/wiki/Open-high-low-close_chart(不过我不需要移动平均线或布林带)

JFreeChart可以在Java中做到这一点,但我希望我的代码尽可能小而简单。

谢谢!

8 个回答

4

你有没有考虑过使用R语言和quantmod这个工具包?它可能正好能满足你的需求。

8

你可以在Python中使用Pylab(matplotlib.finance)。这里有一些例子:http://matplotlib.sourceforge.net/examples/pylab_examples/plotfile_demo.html。关于这个问题,有一些很好的资料可以参考,特别是在《开始Python可视化》这本书里。

更新:我觉得你可以使用matplotlib.finance.candlestick来实现日本蜡烛图效果。

18

你可以使用matplotlib这个库,配合它的一个可选参数bottom,来绘制图表。然后,你可以用plot这条线来表示开盘价和收盘价:

举个例子:

#!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import lines

import random


deltas = [4, 6, 13, 18, 15, 14, 10, 13, 9, 6, 15, 9, 6, 1, 1, 2, 4, 4, 4, 4, 10, 11, 16, 17, 12, 10, 12, 15, 17, 16, 11, 10, 9, 9, 7, 10, 7, 16, 8, 12, 10, 14, 10, 15, 15, 16, 12, 8, 15, 16]
bases = [46, 49, 45, 45, 44, 49, 51, 52, 56, 58, 53, 57, 62, 63, 68, 66, 65, 66, 63, 63, 62, 61, 61, 57, 61, 64, 63, 58, 56, 56, 56, 60, 59, 54, 57, 54, 54, 50, 53, 51, 48, 43, 42, 38, 37, 39, 44, 49, 47, 43]


def rand_pt(bases, deltas):
    return [random.randint(base, base + delta) for base, delta in zip(bases, deltas)]

# randomly assign opening and closing prices 
openings = rand_pt(bases, deltas)
closings = rand_pt(bases, deltas)

# First we draw the bars which show the high and low prices
# bottom holds the low price while deltas holds the difference 
# between high and low.
width = 0
ax = plt.axes()
rects1 = ax.bar(np.arange(50), deltas, width, color='r', bottom=bases)

# Now draw the ticks indicating the opening and closing price
for opening, closing, bar in zip(openings, closings, rects1):
    x, w = bar.get_x(), 0.2

    args = {
    }

    ax.plot((x - w, x), (opening, opening), **args)
    ax.plot((x, x + w), (closing, closing), **args)


plt.show()

这样就能生成一个像这样的图:

enter image description here

显然,你会想把这个过程封装成一个函数,用来绘制图表,输入的参数可以是(open, close, min, max)这样的元组(而且你可能不想随便给开盘价和收盘价赋值)。

撰写回答