Python 再入门

Python 再入门

经过一晚上的随意学习,我终于确认,我把之前学的 Python 全忘完了。明天开始再从零入门吧!

月度收益图

首先从这幅月度平均收益图开始再入门:

最早我在这篇文章里介绍了这幅图:如何一劳永逸地解决 Python 的 matplotlib 模块绘图时无法显示中文的问题

同样按照那篇文章介绍的那样修改源码,然后使用 tushare 导入上证指数的数据进行绘图:

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
import pandas as pd
import tushare as ts
import monthly_returns_heatmap as mrh
ts.set_token('你从tushare官网申请的密钥')
pro = ts.pro_api()
df = pro.index_daily(ts_code='399330.SZ',
start_date = '20100101',
end_date = '20190316')
ret = df['pct_chg'] / 100
df['trade_date'] = pd.to_datetime(df['trade_date'])
ret.index = df['trade_date']
mrh.plot(ret, figname = "399330.svg",
cmap = 'Set1')

用 R 绘制类似的图

R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
library(tidyquant)
library(lubridate)
df <- tq_get('000001.SS',
get = "stock.prices",
from = "2010-01-01")
df %>% arrange(date) %>%
mutate(
ret = (adjusted - dplyr::lag(adjusted)) / dplyr::lag(adjusted),
year = year(date),
month = month(date)
) %>%
select(date, year, month, adjusted, ret) %>%
group_by(year, month) %>%
mutate(
month_ret = mean(ret, na.rm = T) * 100
) %>%
ungroup() %>%
ggplot(aes(x = factor(month), y = year)) +
geom_tile(aes(fill = month_ret), color = "white") +
geom_text(aes(label = month_ret %>% round(2)),
family = "RobotoSlab-Regular") +
viridis::scale_fill_viridis() +
scale_y_reverse() +
scale_x_discrete(breaks = 1:12, labels = 1:12) +
theme(legend.title = element_blank()) +
labs(title = "月度平均收益率(%)",
x = "月份", y = "年份")

ggsave("上证指数月度平均收益率.svg")

比特币走势图

这是前几天看一篇推文的时候跟着画的:

Python
1
2
3
4
5
6
7
8
9
10
11
12
# 绘制比特币价格的走势图
import quandl as qdl
btc_usd_bitfinex = qdl.get('BITFINEX/BTCUSD')
import matplotlib.pyplot as plt
plt.style.available
plt.style.use('dark_background')
plt.figure(figsize = (20, 7))
plt.grid(linewidth = 0.2)
plt.title('BTC x USD (Bitfinex)')
plt.plot(btc_usd_bitfinex.index, btc_usd_bitfinex.Last)
plt.savefig('btc.svg')
plt.show()

# Python

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×