├── .gitattributes ├── .gitignore ├── Chapter01 ├── c1_01_assign_value.py ├── c1_02_import_math_module.py ├── c1_03_def_fv_funtion.py ├── c1_04_def_pv_funtion.py ├── c1_05_pv_f_with_help_comments.py ├── c1_06_if_else.py ├── c1_07_NPV_function.py ├── c1_08_NPV_Excel.py ├── c1_09_while_loop.py ├── c1_10_while_loop_2IRRs.py ├── c1_11_import_math_print_dir.py ├── c1_12_read_csv_file.py ├── c1_13_read_remote_data.py ├── c1_14_read_pickle_data.py ├── c1_15_if_condition.py ├── c1_16_logic_and_logic_or.py ├── c1_17_to_letter_grade.py ├── c1_18_many_useful_commands.py ├── c1_19_flatten_function.py ├── c1_20_matrix_dot_product.py ├── c1_21_read_ffMonthly_data.py ├── c1_22_data_output.py ├── c1_23_read_stock_data_and_save_it.py ├── c1_24_read_infile.py └── c1_25_string_replacement.py ├── Chapter02 ├── c2_01_time_value_of_money.py ├── c2_02_pandas_1.py ├── c2_03_pandas_02 ├── c2_04_interplate.py ├── c2_05_example_statsmodel_OLS.py ├── c2_06_generate_pickle.py ├── c2_07_statsmodels_OLS.py ├── c2_08_example_pandas.py ├── c2_09_bsCall.py └── c2_99_interplate_not_working.py ├── Chapter03 ├── c3_01_write_your_own_financial_calculator.py ├── c3_02_myPV_based_on_scipy.py ├── c3_03_IRRs_funciton.py └── c3_04_appendix_E_more.py ├── Chapter04 ├── c4_01_dir_pandas_data.py ├── c4_02_dir_pandas_data.py ├── c4_03_get_data_google.py ├── c4_04_dir_fin.py ├── c4_05_get_data.py ├── c4_06_read_local_csv_file.py ├── c4_07_first_one.py ├── c4_08_get_data_5lines.py ├── c4_09_get_return_only.py ├── c4_10_from_daily_ret_to_monthly_ret.py ├── c4_11_daily_ret_to_annual.py ├── c4_12_get_ffMonthly.py ├── c4_13_generate_ffMonthly_txt2.py ├── c4_14_download_one_jpg_image.py ├── c4_15_get_data_google_01.py ├── c4_16_ttest_2stocks.py ├── c4_17_print_png_image.py ├── c4_18_federal_fund_rate.py ├── c4_19_appendixA.py ├── c4_20_appendixB.py ├── c4_21_appendixC.py ├── c4_22_appendixD_intraday.py └── c4_23_read_csv_local_file.py ├── Chapter05 ├── p4f.cpython-35.pyc └── spreadBasedOnCreditRating.pkl ├── Chapter06 ├── c6_01_learn_OLS.py ├── c6_02_random_OLS.py ├── c6_03_04_read_pickle.py ├── c6_03_random_OLS.py ├── c6_05_read_excel.py ├── c6_06_input_excel_02.py ├── c6_07_read_csv_file.py ├── c6_08_dailyReturn_4_annual.py ├── c6_09_save_price_data_from_Google.py ├── c6_10_save_price_data_from_Yahoo.py ├── c6_11_save_csv_file.py ├── c6_12_save_a_binary_file.py ├── c6_13_save_Excel_file.py ├── c6_14_save_Excel_file_index_false.py ├── c6_15_string_manipulation.py ├── c6_16_string_manipulation2.py ├── c6_17_yanMonthly.py ├── c6_18_lag_and_forward.py ├── c6_19_lag_once.py ├── c6_20_save_simple_pickle.py ├── c6_21_yanMonthly_unique_securities.py ├── c6_22_sp500_return_lag_lead.py ├── c6_23_lag.py ├── c6_24_bible.py ├── c6_25_mention_canopy.py ├── c6_26_beta_good.py ├── c6_27_get_beta_good.py ├── c6_28_ols_example.py ├── c6_29_save_text_file.py ├── c6_30_suggested_read_pickle_not_working.py └── c6_31_read_from_a_binary_file.py ├── Chapter07 ├── c7_01_3factor_model.py ├── c7_02_critical_F_value.py ├── c7_03_random_OLS.py ├── c7_04_3factors_model.py ├── c7_06_3factors_IBMno_meaning.py ├── c7_07_generate_ffMonthly.py ├── c7_100_generate_ffMonthly_txt.py ├── c7_101_generate_ffcMonthly.py ├── c7_102_generate_ffMonthly5.py ├── c7_11_dot_diff_and_dot_shift_functions.py ├── c7_12_Dimson1979_sp500_lag_lead.py ├── c7_14_sharpe_ratio_using_yanMonthly.py ├── c7_16_def_sharpe_ratio.py ├── c7_16_sharpe_ratio_YahooData.py ├── c7_22_daily2monthly_ff3factor.py ├── c7_23_ffMonthly5.py ├── c7_23_generate_ffMonthly5.py ├── c7_24_generate_ffmonMonthly.py ├── c7_24_read_ffcMonthly.py ├── c7_25_generate_ffcMonthly_pkl.py ├── c7_26_read_ffMonthly5.py ├── c7_30_merge_not_good.py ├── c7_31_merge_01.py ├── c7_32_merge_02_different_names.py ├── c7_32_merge_02_stock.py ├── c7_33_merge_03_left_index.py ├── c7_34_merge_by_two_variables.py ├── c7_39_LPSD.py ├── c7_40_generate_usCPImonthly.py ├── c7_41_generate_ibmMonthly_pkl.py ├── c7_41_generate_usGDPquarterly.py ├── c7_55_merge_how_4types.py ├── c7_56_merge_ffMonthly_GDPquarterly.py ├── c7_88_generate_ffMonthly.py ├── c7_print_ff3factor.py └── c7_simple_ff3_IBM.py ├── Chapter08 ├── c8_01_first_one.py ├── c8_02_get_date_varible_using_pandasDataFrame.py ├── c8_03_daily_to_monthly.py ├── c8_04_retrieve_daily_from_Yahoo.py ├── c8_05_print_GDPquarterly_ffMonthly.py ├── c8_05_print_obs_from_Google.py ├── c8_05_print_obs_from_Google2.py ├── c8_05_yahoo_stock_splits_dividends_data_notWorking.py ├── c8_06_get_daily_data_from_Google.py ├── c8_06_noLonger_working.py ├── c8_07_pandas_datareader_GDP.py ├── c8_07_pandas_read_csv_function.py ├── c8_08_gen_quote_yahoo_good.py ├── c8_08_generate_GDP_pickle_using_pandas_datareader_GDP.py ├── c8_09_foreigh_exchange_not_working.py ├── c8_09_pandas_interpolate.py ├── c8_10_normality_test_random_from_normal_distribution.py ├── c8_10_ochl_still_working.py ├── c8_11_normality_test_random_from_uniform.py ├── c8_12_normality_test_for_IBM.py ├── c8_13_get_current_quote.py ├── c8_14_mean_std_skew_kurt.py ├── c8_15_merge_ffMonthly_GDP.py ├── c8_16_4moments_forSP500.py ├── c8_17_ttest_mean_point5.py ├── c8_18_merge_ff_daily_return.py ├── c8_18_ttest_IBM_2013.py ├── c8_19_Roll_spread.py ├── c8_20_Durbin_Watson_test.py ├── c8_21_use_tempfile.py ├── c8_22_table2_get_year_month_day_from_a_date_var.py ├── c8_24_second_way_to_calculate_returns.py ├── c8_25_interplate.py ├── c8_26_test_daily_mean_is_zero.py ├── c8_27_test_equal_variances.py ├── c8_28_52_week_high.py ├── c8_30_test_january_effect.py ├── c8_31_get_high_frequency_data_google.py ├── c8_32_print_TORQct.py ├── c8_33_read_TORQcq.py ├── c8_34_Durbin_Watson_test_CAPM_IBM_residual.py ├── c8_35_pandas_OLS.py ├── c8_36_Fama_Mecbeth_regression.py ├── c8_44_Amihud_IBM_WMT.py ├── c8_44_generate_bysinessCyclePkl.py ├── c8_44_relative_spread_TORQcq.py ├── c8_45_read_crspInfo.py ├── c8_46_print_indexMonthly_CRSP.py ├── c8_55_high_frequency_from_Google.py ├── c8_55_merge_business_GDP.py ├── c8_55_rolling_max_decapitted_.py ├── c8_99_01_generate_ffDaily_txt.py ├── c8_99_03_generate_crspInfo_pickle.py ├── c8_99_04_generate_indexMonthly_pickle.py ├── c8_99_08_generate_tradingDays.py └── c8_generate_critical_F_values_Table.py ├── Chapter09 ├── c9_01_optimize.py ├── c9_02_graph_y_x.py ├── c9_02_matrix.py ├── c9_032_matrix_multiplication.py ├── c9_03_graph_another_pair_y_x.py ├── c9_03_optimization.py ├── c9_04_solution_x1_x2_for_quatradic_form.py ├── c9_06_find_weight_2stock_portfolio.p ├── c9_06_solution_2stock_negative_perfect_corr.py ├── c9_07_find_minimum_expentional_function.py ├── c9_08_generate_2setCorrelated_randomNumbers.py ├── c9_10_impact_of_correlation_2_stock.py ├── c9_12_get_ret_matrix_from_yanMonthly.py ├── c9_13_get_IBM_from_yanMonthly.py ├── c9_13_get_ret_matrix_from_yanMonthly.py ├── c9_14_10_stock_retrun_matrixget_from_yanMonthly.py ├── c9_14_get_IBM_ret_from_yanMonthly.py ├── c9_18_sharpe_ratio.py ├── c9_19_treynor_ratio.py ├── c9_21_optimal_portfolio_based_on_Sortino_ratio.py ├── c9_22_LPSD_f.py ├── c9_23_efficient_based_on_sortino_ratio.py ├── c9_30_utility_function_impact_Of_A.py ├── c9_32_mean_and_var.py ├── c9_44_equal_weighted_vs_value_weighted.py ├── c9_44_impact_of_correlation_2stock_portfolio.py ├── c9_46_print_ff49industries.py ├── c9_50_efficient_frontier.py ├── c9_52_impact_of_correlation_on_efficient_frontier_notWorking.py ├── c9_55_end_Of_chapter_problem_update_yanMonthly.py ├── c9_55_read_stockMonthly.py ├── c9_77_Modigliani_m2_performance_measure.py ├── c9_99_01_generate_stockMonthly_pkl.py ├── c9_99_03_generate_sp500add_pkl.py ├── c9_99_04_generate_sp500monthly_pkl.py └── c9_99_05_generate_ff49_industries.py ├── Chapter10 ├── c10_01.py ├── c10_02_foreign_exchange_futures.py ├── c10_03_exchange_futures.py ├── c10_04_payoff_call_graph.py ├── c10_05_payoff_function_call.py ├── c10_06_profit_loss_for_call.py ├── c10_07_profit_loss_for_put.py ├── c10_08_arbitrage_argument_exchange_futures.py ├── c10_09_standard_normal_dis_graph.py ├── c10_10_target_beta_portfolio_hedging.py ├── c10_11_area_under_normal_dist.py ├── c10_12_target_beta_portfolio_hedging02.py ├── c10_13_fig.py ├── c10_14_bsCall.py ├── c10_15_covered_call.py ├── c10_16_straddle.py ├── c10_17_calendarSpread.py ├── c10_18_butterFly.py ├── c10_19_graph_sigma_call.py ├── c10_20_6_figures.py ├── c10_21_CRR_01.py ├── c10_22_binomial_graph.py ├── c10_23_binomial_2steps.py ├── c10_24_binomial_2steps2.py ├── c10_25_binomialEuropeanCallFunction.py ├── c10_26_binomialAmericanCall.py ├── c10_27_end_of_chapter_question.py ├── c10_28_standard_normal_dist.py ├── c10_29_fig_good.py ├── c10_30_figure_end_of_chapter_problem.py ├── c10_31_plot_call_vs_one_input.py ├── c10_32_implied_vol_EuropeanCall.py ├── c10_33_implied_vol_EuropeanPut_min.py ├── c10_34_binary_search.py ├── c10_35_put_call_ratio.py ├── c10_36_put_call_ratio_add_trend.py ├── c10_37_volatility_smile.py ├── c10_38_greeks.py ├── c10_39_implied_vol_binary_search.py ├── c10_40_data_case.py ├── c10_41_number_of_stock_vs_vol_graph.py ├── c10_42_binomialCallEuropean.py └── c10_43_EW_port.py ├── Chapter11 ├── c11_01_normal_density_function.py ├── c11_02_normal_distribution.py ├── c11_03_standard_normal_dis.py ├── c11_04_show_z_negative.py ├── c11_05_VaR_left_1percentTail.py ├── c11_06_VaR_500shares_IBM_10days.py ├── c11_07_VaR_500shares_IBM_tomorrow.py ├── c11_08_second_way_to_calculate_10dayVaR.py ├── c11_09_normaility_test_msft.py ├── c11_10_normality_test.py ├── c11_11_normality_test_for_sp500.py ├── c11_12_normal_random.py ├── c11_13_sort_nparray.py ├── c11_14_VaR_500shares_WMT.py ├── c11_15_VaR_500shares_WMT_sort_daily.py ├── c11_16_VaR_sorting_10days.py ├── c11_17_ModifiedVaR_one_day.py ├── c11_18_sort_pandas.py ├── c11_19_portfolio_VaR.py ├── c11_20_VaR_for_5industry_portfolo_ff.py ├── c11_21_ES_z_value_normal_distribution.py ├── c11_22_back_testing_1000shares_IBM_tomorrow.py ├── c11_23_back_testing_IBM_one_day.py ├── c11_24_01_generate_ff5VWindustry_49.py └── c11_25_more_on_VaR.py ├── Chapter12 ├── c12_01_10random_numbers.py ├── c12_03_graph_standard_normal_dist.py ├── c12_04_histogram.py ├── c12_05_lognormal_graphs.py ├── c12_06_random_number_with_seed.py ├── c12_07_normal_dist.py ├── c12_08_uniform_dist.py ├── c12_09_roll_a_dice.py ├── c12_10_simulate_pi.py ├── c12_11_poison_dist.py ├── c12_12_radnomly_choose_m_from_n_stocks.py ├── c12_13_use_yanMonthly.py ├── c12_14_stock_price_movement.py ├── c12_15_simulate_Black_Scholes_call.py ├── c12_16_VaR_based_on_formula.py ├── c12_17_average_price_call.py ├── c12_18_VaR_based_on_simulation.py ├── c12_19_up_and_out_call.py ├── c12_20_boots_f_function.py ├── c12_21_use_permutation_function.py ├── c12_22_distribution_of_annual_returns.py ├── c12_23_capital_budget_01.py ├── c12_24_capital_bedget_02.py ├── c12_25_long_term_forecast.py ├── c12_26_simulation_link_2method_VaR.py ├── c12_27_random_numbers_from_three_distributions.py ├── c12_28_basic_income_best.py ├── c12_29_2stock_efficient_frontier_simulation.py ├── c12_30_n_stock_efficient_frontier.py ├── c12_31_scatter_random_numbers.py ├── c12_32_scatter_sobol.py ├── c12_33_generateSobol_pkl.py ├── c12_35_simpy_02.py ├── c12_36_terminal_stock_price_distribution.py ├── c12_40_capital_budget_01.py └── c12_88_simpy_02.py ├── Chapter13 ├── c13_01.py ├── c13_02_print1year_credit_migration.py ├── c13_03_print_moodyAAAyield.py ├── c13_04_print5year_credit_migrationMatrix.py ├── c13_05_print_bondSpread2014.py ├── c13_06_norm_ppf.py ├── c13_07_BIS_interest_simulation.py ├── c13_08_KMF_function.py ├── c13_09_get_PriceYahoo_not_working.py ├── c13_20_graph_term_structure.py ├── c13_99_02_1yearCreditRatingMigrationMarrix.py ├── c13_99_03_geneerate5year.py ├── c13_99_03_generateBondSpread2014.py ├── c13_99_04_generate_moodyAAAyield.py ├── c13_99_get_finStatement_not_working.py └── c13_99_get_finstatement_not_good.py ├── Chapter14 ├── c14_01_callandPut.py ├── c14_02_chooserOption.py ├── c14_03_binomialAmericanCall.py ├── c14_04_BermudanCallBinomial.py ├── c14_05_shoutCall.py ├── c14_06_binary_call.py ├── c14_07_mvn_multiVariateNormalGraph.py ├── c14_08_N2_f_bivariate_cumulative_normal_dist.py ├── c14_09_rainbowFormulaMinimum2.py ├── c14_10_correlated_random_numbers.py ├── c14_11_rainbow_callMaxOn2_viaSimulation.py ├── c14_12_Rainbow2.py ├── c14_13_average_price_call.py ├── c14_14_average_price_call.py ├── c14_15_exoticOptoin_averagePrice.py ├── c14_16_up_and_out_call.py ├── c14_17_up_call.py ├── c14_18_down_and_in_put.py ├── c14_19_fig_upAndIn_upAndOut_simulation.py ├── c14_20_lookback_min_price_as_strike.py ├── c14_21_Lookback_notWorking.py ├── c14_22_crudeOilPrice.py ├── c14_23_N_f_vs_N2_f.py ├── c14_24_cholesky.py ├── c14_25_up_and_out_call.py └── c14_26_up_and_out_call2.py ├── Chapter15 ├── c15_01_vol_IBM.py ├── c15_02_normalityTests.py ├── c15_03_4moments.py ├── c15_04_sp500_4moments.py ├── c15_05_generate_ffDaily_pkl.py ├── c15_06_LSPD.py ├── c15_07_equal_vol_2periods.py ├── c15_08.py ├── c15_09_volatility_smile_call.py ├── c15_10_volatility_smile_put.py ├── c15_11_sp500cluster.py ├── c15_12_ARCH_1.py ├── c15_13_GARCH.py ├── c15_14_GARCH_2_1.py ├── c15_15_jir_GARCH_function.py ├── c15_16_GJR_GARCH_function.py └── c15_17_GIR_GARCH_result.py ├── LICENSE └── README.md /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | 4 | # Custom for Visual Studio 5 | *.cs diff=csharp 6 | 7 | # Standard to msysgit 8 | *.doc diff=astextplain 9 | *.DOC diff=astextplain 10 | *.docx diff=astextplain 11 | *.DOCX diff=astextplain 12 | *.dot diff=astextplain 13 | *.DOT diff=astextplain 14 | *.pdf diff=astextplain 15 | *.PDF diff=astextplain 16 | *.rtf diff=astextplain 17 | *.RTF diff=astextplain 18 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Windows image file caches 2 | Thumbs.db 3 | ehthumbs.db 4 | 5 | # Folder config file 6 | Desktop.ini 7 | 8 | # Recycle Bin used on file shares 9 | $RECYCLE.BIN/ 10 | 11 | # Windows Installer files 12 | *.cab 13 | *.msi 14 | *.msm 15 | *.msp 16 | 17 | # Windows shortcuts 18 | *.lnk 19 | 20 | # ========================= 21 | # Operating System Files 22 | # ========================= 23 | 24 | # OSX 25 | # ========================= 26 | 27 | .DS_Store 28 | .AppleDouble 29 | .LSOverride 30 | 31 | # Thumbnails 32 | ._* 33 | 34 | # Files that might appear in the root of a volume 35 | .DocumentRevisions-V100 36 | .fseventsd 37 | .Spotlight-V100 38 | .TemporaryItems 39 | .Trashes 40 | .VolumeIcon.icns 41 | 42 | # Directories potentially created on remote AFP share 43 | .AppleDB 44 | .AppleDesktop 45 | Network Trash Folder 46 | Temporary Items 47 | .apdisk 48 | -------------------------------------------------------------------------------- /Chapter01/c1_01_assign_value.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c1_01_assign_value.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | pv=100 13 | fv=pv*(1+0.1)**20 14 | 15 | print(fv) -------------------------------------------------------------------------------- /Chapter01/c1_02_import_math_module.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c1_02_import_math_module.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | import math 13 | x=math.sqrt(3) 14 | print(x) -------------------------------------------------------------------------------- /Chapter01/c1_03_def_fv_funtion.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c1_03_def_fv_function.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | def fv_f(pv,r,n): 13 | return pv*(1+r)**n 14 | # 15 | fv=fv_f(100,0.1,2) 16 | print(fv) -------------------------------------------------------------------------------- /Chapter01/c1_04_def_pv_funtion.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c1_04_def_pv_function.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | def pv_f(pv,r,n): 13 | return pv/(1+r)**n 14 | # 15 | pv=pv_f(100,0.1,2) 16 | print(pv) -------------------------------------------------------------------------------- /Chapter01/c1_05_pv_f_with_help_comments.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c1_05_pv_f_with_help_comments.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | def pv_f(fv,r,n): 13 | """Objective: estimate present value 14 | fv: fture value 15 | r : discount period rate 16 | n : number of periods 17 | formula : fv/(1+r)**n 18 | e.g., 19 | >>>pv_f(100,0.1,1) 20 | 90.9090909090909 21 | >>>pv_f(r=0.1,fv=100,n=1) 22 | 90.9090909090909 23 | >>>pv_f(n=1,fv=100,r=0.1) 24 | 90.9090909090909 25 | """ 26 | return fv/(1+r)**n -------------------------------------------------------------------------------- /Chapter01/c1_06_if_else.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c1_06_if_else.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | import numpy as np 13 | cashFlows=np.array([-100,50,40,30]) 14 | for cash in cashFlows: 15 | print(cash) -------------------------------------------------------------------------------- /Chapter01/c1_07_NPV_function.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c1_07_NPV_function.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | def npv_f(rate, cashflows): 13 | total = 0.0 14 | for i in range(0,len(cashflows)): 15 | total += cashflows[i] / (1 + rate)**i 16 | return total -------------------------------------------------------------------------------- /Chapter01/c1_08_NPV_Excel.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c1_08_NPV_Excel.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | def npv_Excel(rate, cashflows): 13 | total = 0.0 14 | for i, cashflow in enumerate(cashflows): 15 | total += cashflow / (1 + rate)**(i+1) 16 | return total -------------------------------------------------------------------------------- /Chapter01/c1_09_while_loop.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c1_09_while_loop.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | i=1 13 | while(i<10): 14 | print(i) 15 | i+=1 -------------------------------------------------------------------------------- /Chapter01/c1_10_while_loop_2IRRs.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c1_09_while_loop_2IRRs.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | def npv_f(rate, cashflows): 12 | total = 0.0 13 | for i in range(0,len(cashflows)): 14 | total += cashflows[i] / (1 + rate)**i 15 | return total 16 | # 17 | cashFlows=(550,-500,-500,-500,1000) 18 | r=0 19 | while(r<1.0): 20 | r+=0.000001 21 | npv=npv_f(r,cashFlows) 22 | if(abs(npv)<=0.0001): 23 | print(r) -------------------------------------------------------------------------------- /Chapter01/c1_11_import_math_print_dir.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c1_11_import_math_print_dir.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | import math 12 | x=dir(math) 13 | print(x) -------------------------------------------------------------------------------- /Chapter01/c1_12_read_csv_file.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c1_12_read_csv_file.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | import pandas as pd 12 | x=pd.read_csv("c:/temp/ibm.csv") -------------------------------------------------------------------------------- /Chapter01/c1_13_read_remote_data.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c1_13_read_remote_data.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | import pandas as pd 13 | url='http://canisius.edu/~yany/data/ibm.csv' 14 | x=pd.read_csv(url) 15 | print(x.head()) -------------------------------------------------------------------------------- /Chapter01/c1_14_read_pickle_data.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c1_14_read_pickle_data.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | import pandas as pd 13 | x=pd.read_pickle("c:/temp/ffMonthly.pkl") 14 | print(x.head()) -------------------------------------------------------------------------------- /Chapter01/c1_15_if_condition.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c1_15_if_condition.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | r=-0.05 13 | 14 | if(r<0): 15 | print("interest rate is less than zero") -------------------------------------------------------------------------------- /Chapter01/c1_16_logic_and_logic_or.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c1_16_logic_and_logic_or.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | a=9 12 | b=-8 13 | 14 | if(a>0 and b>0): 15 | print("both positive") 16 | if(a>0 or b>0): 17 | print("at least one is positive") -------------------------------------------------------------------------------- /Chapter01/c1_17_to_letter_grade.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c1_17_to_letter_grade.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | grade=87 12 | 13 | if grade>=90: 14 | print('A') 15 | elif grade >=85: 16 | print('A-') 17 | elif grade >=80: 18 | print('B+') 19 | elif grade >=75: 20 | print('B') 21 | elif grade >=70: 22 | print('B-') 23 | elif grade>=65: 24 | print('C+') 25 | else: 26 | print('D') -------------------------------------------------------------------------------- /Chapter01/c1_18_many_useful_commands.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c1_18_many_useful_commands.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | import numpy as np 12 | a=np.zeros(10) # array with 10 zeros 13 | b=np.zeros((3,2),dtype=float) # 3 by 2 with zeros 14 | c=np.ones((4,3),float) # 4 by 3 with all ones 15 | d=np.array(range(10),float) # 0,1, 2,3 .. up to 9 16 | e1=np.identity(4) # identity 4 by 4 matrix 17 | e2=np.eye(4) # same as above 18 | e3=np.eye(4,k=1) # 1 start from k 19 | f=np.arange(1,20,3,float) # from 1 to 19 interval 3 20 | g=np.array([[2,2,2],[3,3,3]]) # 2 by 3 21 | h=np.zeros_like(g) # all zeros 22 | i=np.ones_like(g) # all ones 23 | -------------------------------------------------------------------------------- /Chapter01/c1_19_flatten_function.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c1_19_flatten_function.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | import numpy as np 12 | # 13 | x=np.array([[1,2],[5,6],[7,9]]) # a 3 by 2 array 14 | print(x) 15 | y=x.flatten() 16 | print(y) 17 | x2=np.reshape(y,[2,3]) 18 | print(x2) -------------------------------------------------------------------------------- /Chapter01/c1_20_matrix_dot_product.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c1_20_matrix_dot_product.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | import numpy as np 12 | a=np.array([[1,2,3],[4,5,6]],float) # 2 by 3 13 | b=np.array([[1,2],[3,3],[4,5]],float) # 3 by 2 14 | np.dot(a,b) # 2 by 2 15 | print(np.dot(a,b)) -------------------------------------------------------------------------------- /Chapter01/c1_21_read_ffMonthly_data.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c1_21_read_ffMonthly_data.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | import numpy as np 12 | import pandas as pd 13 | file=open("c:/temp/ffMonthly.txt","r") 14 | data=file.readlines() 15 | f=[] 16 | index=[] 17 | for i in range(1,np.size(data)): 18 | t=data[i].split() 19 | index.append(int(t[0])) 20 | for j in range(1,5): 21 | k=float(t[j]) 22 | f.append(k/100) -------------------------------------------------------------------------------- /Chapter01/c1_22_data_output.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c1_22_data_output.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | f=open("c:/temp/out.txt","w") 12 | x="This is great" 13 | f.write(x) 14 | f.close() -------------------------------------------------------------------------------- /Chapter01/c1_23_read_stock_data_and_save_it.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c1_23_read_stock_data_and_save_it.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | import re 12 | from matplotlib.finance import quotes_historical_yahoo_ochl 13 | ticker='dell' 14 | outfile=open("c:/temp/dell.txt","w") 15 | begdate=(2013,1,1) 16 | enddate=(2016,11,9) 17 | p=quotes_historical_yahoo_ochl(ticker,begdate,enddate,asobject=True,adjusted=True) 18 | outfile.write(str(p)) 19 | outfile.close() -------------------------------------------------------------------------------- /Chapter01/c1_24_read_infile.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c1_24_read_infile.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | infile=open("c:/temp/dell.txt","r") 12 | x=infile.read() 13 | -------------------------------------------------------------------------------- /Chapter01/c1_25_string_replacement.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c1_26_string_replacement.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | import re 12 | x="abc" 13 | print("x=",x) 14 | y=re.sub("a","9",x) 15 | print("y=",y) 16 | 17 | 18 | -------------------------------------------------------------------------------- /Chapter02/c2_02_pandas_1.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c2_02_pandas_1.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | import pandas as pd 13 | import numpy as np 14 | 15 | np.random.seed(123) 16 | df = pd.DataFrame(np.random.randn(10, 4)) 17 | pieces = [df[:3], df[3:7], df[7:]] 18 | -------------------------------------------------------------------------------- /Chapter02/c2_03_pandas_02: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Fri Nov 18 12:42:27 2016 4 | 5 | @author: yany 6 | """ 7 | 8 | import pandas as pd 9 | df = pd.DataFrame(np.random.randn(10, 4)) -------------------------------------------------------------------------------- /Chapter02/c2_04_interplate.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c2_04_interplate.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import numpy as np 12 | import pandas as pd 13 | # 14 | np.random.seed(123) 15 | x=np.arange(1, 3.1, .25)**2 16 | n=np.size(x) 17 | y = pd.Series(x + np.random.randn(n)) 18 | print(y) 19 | y[4]=np.nan 20 | print(y) 21 | z=y.interpolate() 22 | print(z) 23 | 24 | -------------------------------------------------------------------------------- /Chapter02/c2_05_example_statsmodel_OLS.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c2_05_example_statsmodel_OLS.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | import numpy as np 13 | import statsmodels.api as sm 14 | y=[1,2,3,4,2,3,4] 15 | x=range(1,8) 16 | x=sm.add_constant(x) 17 | results=sm.OLS(y,x).fit() 18 | print results.params -------------------------------------------------------------------------------- /Chapter02/c2_06_generate_pickle.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c2_06_generate_pickle.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | import numpy as np 13 | import pandas as pd 14 | np.random.seed(123) 15 | df=pd.Series(np.random.randn(100)) 16 | df.to_pickle('c:/temp/test.pkl') -------------------------------------------------------------------------------- /Chapter02/c2_07_statsmodels_OLS.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c2_07_statsmodels_OLD.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | import numpy as np 13 | import statsmodels.api as sm 14 | y=[1,2,3,4,2,3,4] 15 | x=range(1,8) 16 | x=sm.add_constant(x) 17 | results=sm.OLS(y,x).fit() 18 | print(results.params) 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /Chapter02/c2_08_example_pandas.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c2_08_example_pandas.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import numpy as np 12 | import pandas as pd 13 | dates=pd.date_range('20160101',periods=5) 14 | np.random.seed(12345) 15 | x=pd.DataFrame(np.random.rand(5,2),index=dates,columns=('A','B')) 16 | -------------------------------------------------------------------------------- /Chapter02/c2_09_bsCall.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c2_09_bsCall.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | def bsCall(S,X,T,r,sigma): 12 | from scipy import log,exp,sqrt,stats 13 | d1=(log(S/X)+(r+sigma*sigma/2.)*T)/(sigma*sqrt(T)) 14 | d2 = d1-sigma*sqrt(T) 15 | return S*stats.norm.cdf(d1)-X*exp(-r*T)*stats.norm.cdf(d2) 16 | -------------------------------------------------------------------------------- /Chapter02/c2_99_interplate_not_working.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c2_04_interplate_not_worling.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import numpy as np 12 | import pandas as pd 13 | # 14 | np.random.seed(123) 15 | x=np.arange(1, 3, .25)**2 16 | n=np.size(x) 17 | y = pd.Series(x + np.random.randn(n)) 18 | 19 | bad = np.array([4, 13, 14, 15, 16, 20, 30]) 20 | 21 | x[bad] = np.nan 22 | methods = ['linear', 'quadratic', 'cubic'] 23 | df = pd.DataFrame({m: x.interpolate(method=m) for m in methods}) 24 | #df=x.interpolate(method="linear") 25 | df.plot() 26 | 27 | -------------------------------------------------------------------------------- /Chapter03/c3_01_write_your_own_financial_calculator.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c3_01_writeYour_own_financial_calculator.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | def pvFunction(fv,r,n): 12 | return fv/(1+r)**n 13 | def pvPerpetuity(c,r): 14 | return c/r 15 | def pvPerpetuityDue(c,r): 16 | return c/r*(1+r) 17 | def pvAnnuity(c,r,n): 18 | return c/r*(1-1/(1+r)**n) 19 | def pvAnnuityDue(c,r,n): 20 | return c/r*(1-1/(1+r)**n)*(1+r) 21 | def pvGrowingAnnuity(c,r,n,g): 22 | return c/r*(1-(1+g)**n/(1+r)**n) 23 | def fvFunction(pv,r,n): 24 | return c/r*(1-1/(1+r)**n) 25 | def fvAnnuity(cv,r,n): 26 | return c/r*((1+r)**n-1) 27 | def fvAnnuityDue(cv,r,n): 28 | return c/r*((1+r)**n-1)*(1+r) 29 | 30 | -------------------------------------------------------------------------------- /Chapter03/c3_02_myPV_based_on_scipy.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c3_02_myPV_based_on_scipy.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | def myPV(r,n,fv): 13 | import scipy as sp 14 | return(-sp.pv(r,n,0,fv)) 15 | 16 | 17 | 18 | def myPV(r,n,fv): 19 | """ 20 | Objective: estimate present value of one future cash flow 21 | r : period rate 22 | n : number of periods 23 | fv: fture value 24 | 25 | formula used : pv=fv/(1+r)**n 26 | 27 | Example 1: >>>myPV(0.1,1,100) 28 | 90.9090909090909 29 | 30 | Example #2 >>>myPV(r=0.1,fv=100,n=1) 31 | 90.9090909090909 32 | """ 33 | import scipy as sp 34 | return(-sp.pv(r,n,0,fv)) -------------------------------------------------------------------------------- /Chapter03/c3_03_IRRs_funciton.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c3_03_IRRs_funciton.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | import numpy as sp 13 | cashflows=[55,-50,-50,-50,100] 14 | n=1000 15 | n_cashflow=len(cashflows) 16 | epsilon=sp.abs(sp.mean(cashflows))*0.01 17 | irr=[-99.00] 18 | lag_sign=sp.sign(sp.npv(0,cashflows)) 19 | i=1 20 | j=1 21 | while(i<=n): 22 | interest=i*0.001 23 | s=sp.sign(sp.npv(interest,cashflows)) 24 | i=i+1 25 | if s*lag_sign<0: 26 | lag_sign=s 27 | if j==1: 28 | irr=[interest] 29 | j=2 30 | else: 31 | irr.append(interest) 32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /Chapter03/c3_04_appendix_E_more.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c3_04_appendixE.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | import scipy as sp 13 | from matplotlib.pyplot import * 14 | cashflows=[-120,50,60,70] 15 | rate=[] 16 | npv=[] 17 | x=(0,0.7) 18 | y=(0,0) 19 | for i in range(1,70): 20 | rate.append(0.01*i) 21 | npv.append(sp.npv(0.01*i,cashflows)) 22 | 23 | title("NPV profile") 24 | xlabel("Discount Rate") 25 | ylabel("NPV (Net Present Value)") 26 | plot(rate,npv) 27 | plot(x,y) 28 | show() 29 | -------------------------------------------------------------------------------- /Chapter04/c4_01_dir_pandas_data.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c4_01_dir_pandas.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | import pandas_datareader.data as pddata 13 | print(help(pddata) ) 14 | -------------------------------------------------------------------------------- /Chapter04/c4_02_dir_pandas_data.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c4_02_dir_pandas_data.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | import pandas_datareader.data as pddata 13 | print(help(pddata.DataReader) ) 14 | -------------------------------------------------------------------------------- /Chapter04/c4_03_get_data_google.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c4_03_get_stock_data_google.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | import pandas_datareader.data as getData 12 | df = getData.get_data_google("IBM") 13 | print(df.head()) 14 | -------------------------------------------------------------------------------- /Chapter04/c4_04_dir_fin.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c4_03_dir_fin.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | import matplotlib.finance as fin 12 | print(dir(fin)) 13 | -------------------------------------------------------------------------------- /Chapter04/c4_05_get_data.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c4_05_get_data.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | import pandas_datareader.data as getData 13 | df = getData.DataReader("IBM", 'google') 14 | print(df.head()) 15 | -------------------------------------------------------------------------------- /Chapter04/c4_06_read_local_csv_file.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c4_06_read_local_csv_file.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | import pandas as pd 13 | x=pd.read_csv("c:/temp/ibm.csv") 14 | print(x.head()) 15 | -------------------------------------------------------------------------------- /Chapter04/c4_07_first_one.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c4_07_first_one.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | from matplotlib.finance import quotes_historical_yahoo_ochl as getData 13 | p = getData("IBM", (2015,1,1), (2015,12,31),asobject=True, adjusted=True) 14 | print(p[0:5]) 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /Chapter04/c4_08_get_data_5lines.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c4_08_get_data.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | import datetime 13 | import pandas_datareader.data as getData 14 | begdate = datetime.datetime(1962, 11, 1) 15 | enddate = datetime.datetime(2016, 11, 7) 16 | df = getData.DataReader("IBM", 'google', begdate, enddate) 17 | -------------------------------------------------------------------------------- /Chapter04/c4_09_get_return_only.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c4_09_get_return_only.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | from matplotlib.finance import quotes_historical_yahoo_ochl as getData 13 | ticker='IBM' 14 | begdate=(2015,1,1) 15 | enddate=(2015,11,9) 16 | p = getData(ticker, begdate, enddate,asobject=True, adjusted=True) 17 | ret = (p.aclose[1:] - p.aclose[:-1])/p.aclose[:1] 18 | -------------------------------------------------------------------------------- /Chapter04/c4_10_from_daily_ret_to_monthly_ret.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c4_10_from_daily_ret_to_monthly_ret.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | import numpy as np 13 | import pandas as pd 14 | from matplotlib.finance import quotes_historical_yahoo_ochl as getData 15 | # 16 | ticker='IBM' 17 | begdate=(2015,1,1) 18 | enddate=(2015,12,31) 19 | x = getData(ticker, begdate, enddate,asobject=True, adjusted=True) 20 | logret = np.log(x.aclose[1:]/x.aclose[:-1]) 21 | 22 | date=[] 23 | d0=x.date 24 | for i in range(0,np.size(logret)): 25 | date.append(''.join([d0[i].strftime("%Y"),d0[i].strftime("%m")])) 26 | 27 | y=pd.DataFrame(logret,date,columns=['retMonthly']) 28 | retMonthly=y.groupby(y.index).sum() 29 | -------------------------------------------------------------------------------- /Chapter04/c4_11_daily_ret_to_annual.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c4_11_from_daily_ret_to_annual.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | import numpy as np 13 | import pandas as pd 14 | from matplotlib.finance import quotes_historical_yahoo_ochl as getData 15 | # 16 | ticker='IBM' 17 | begdate=(1980,1,1) 18 | enddate=(2012,12,31) 19 | x=getData(ticker,begdate,enddate,asobject=True,adjusted=True) 20 | logret = np.log(x.aclose[1:]/x.aclose[:-1]) 21 | 22 | date=[] 23 | d0=x.date 24 | for i in range(0,np.size(logret)): 25 | date.append(d0[i].strftime("%Y")) 26 | 27 | y=pd.DataFrame(logret,date,columns=['retAnnual']) 28 | ret_annual=np.exp(y.groupby(y.index).sum())-1 29 | -------------------------------------------------------------------------------- /Chapter04/c4_12_get_ffMonthly.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c4_12_get_ffMonthly.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | import pandas_datareader.data as getData 13 | ff =getData.DataReader("F-F_Research_Data_Factors", "famafrench") 14 | -------------------------------------------------------------------------------- /Chapter04/c4_13_generate_ffMonthly_txt2.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c4_13_generate_ffMonthly_txt2.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | import numpy as np 11 | import pandas as pd 12 | # 13 | file=open("c:/temp/ffMonthly.txt","r") 14 | data=file.readlines() 15 | dd=[] # should not use dd=mkt=smb=hml=rf=[]!!!!! 16 | mkt=[] 17 | smb=[] 18 | hml=[] 19 | rf=[] 20 | n=len(data) 21 | index=range(1,n-3) 22 | 23 | for i in range(4,n): 24 | t=data[i].split() 25 | dd.append(pd.to_datetime(t[0]+'01', format='%Y%m%d').date()) 26 | mkt.append(float(t[1])/100) 27 | smb.append(float(t[2])/100) 28 | hml.append(float(t[3])/100) 29 | rf.append(float(t[4])/100) 30 | 31 | d=np.transpose([dd,mkt,smb,hml,rf]) 32 | ff=pd.DataFrame(d,index=index,columns=['DATE','MKT_RF','SMB','HML','RF']) 33 | ff.to_pickle("c:/temp/ffMonthly.pkl") 34 | 35 | -------------------------------------------------------------------------------- /Chapter04/c4_14_download_one_jpg_image.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c4_14_download_one_jpg_image.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | import urllib 12 | f = open('c:/temp/00000001.jpg','wb') 13 | f.write(urllib.urlopen('http://www.gunnerkrigg.com//comics/00000001.jpg').read()) 14 | f.close() 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /Chapter04/c4_15_get_data_google_01.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c4_15_get_data_google.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | import pandas_datareader.data as getData 13 | aapl =getData.DataReader("AAPL", "google") 14 | 15 | -------------------------------------------------------------------------------- /Chapter04/c4_16_ttest_2stocks.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c4_16_ttest_2stocks.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | 13 | import scipy.stats as stats 14 | from matplotlib.finance import quotes_historical_yahoo_ochl as getData 15 | begdate=(2013,1,1) 16 | enddate=(2016,12,9) 17 | 18 | def ret_f(ticker,begdate,enddate): 19 | p = getData(ticker,begdate, enddate,asobject=True,adjusted=True) 20 | ret=p.aclose[1:] 21 | ret=p.aclose[1:]/p.aclose[:-1]-1 22 | return(ret) 23 | 24 | a=ret_f('IBM',begdate,enddate) 25 | b=ret_f('MSFT',begdate,enddate) 26 | print(stats.ttest_ind(a,b)) 27 | 28 | -------------------------------------------------------------------------------- /Chapter04/c4_17_print_png_image.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c4_17_print_png_image.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | from PIL import Image 12 | img = Image.open('c:/temp/fun.png') 13 | img.show() 14 | 15 | 16 | -------------------------------------------------------------------------------- /Chapter04/c4_18_federal_fund_rate.py: -------------------------------------------------------------------------------- 1 | # generate ff_monthly.pickle 2 | 3 | """ 4 | Name : c4_28_federal_fund_rate.py 5 | Book : Python for Finance (2nd ed.) 6 | Publisher: Packt Publishing Ltd. 7 | Author : Yuxing Yan 8 | Date : 6/6/2017 9 | email : yany@canisius.edu 10 | paulyxy@hotmail.com 11 | """ 12 | 13 | import pandas as pd 14 | import numpy as np 15 | infile="c:/temp/fedFundRate.csv" 16 | data=pd.read_csv(infile,skiprows=6,header=None) 17 | 18 | #data=pd.read_csv(file,skiprows=3) 19 | dd=rate=[] 20 | n=len(data) 21 | y=np.array(data) 22 | rate=[] 23 | 24 | for i in np.arange(n): 25 | t=y[i][0] 26 | dd.append(pd.to_datetime(t, format='%Y-%m-%d').date()) 27 | rate.append(y[i][1]/100.) 28 | # 29 | fedFundRate=pd.DataFrame(rate,index=dd,columns=['FEDFUNDRATE']) 30 | fedFundRate.to_pickle("c:/temp/fedFundRate.pkl") 31 | 32 | 33 | -------------------------------------------------------------------------------- /Chapter04/c4_19_appendixA.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c4_19_appendixA.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | import numpy as np 12 | import matplotlib.mlab as mlab 13 | from matplotlib.pyplot import * 14 | from matplotlib.finance import quotes_historical_yahoo_ochl as getData 15 | # 16 | ticker='IBM' 17 | begdate=(2015,1,1) 18 | enddate=(2015,11,9) 19 | p = getData(ticker, begdate, enddate,asobject=True, adjusted=True) 20 | ret = (p.aclose[1:] - p.aclose[:-1])/p.aclose[:1] 21 | [n,bins,patches] = hist(ret, 100) 22 | mu = np.mean(ret) 23 | sigma = np.std(ret) 24 | x = mlab.normpdf(bins, mu, sigma) 25 | plot(bins, x, color='red', lw=2) 26 | title("IBM return distribution") 27 | xlabel("Returns") 28 | ylabel("Frequency") 29 | show() 30 | -------------------------------------------------------------------------------- /Chapter04/c4_23_read_csv_local_file.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c4_23_read_csv_local_file.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | import pandas as pd 13 | x=pd.read_csv("c:/temp/ibm.csv") 14 | 15 | 16 | -------------------------------------------------------------------------------- /Chapter05/p4f.cpython-35.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Python-for-Finance-Second-Edition/019929145fdbabe23e30ef05e274994dafb5f3e3/Chapter05/p4f.cpython-35.pyc -------------------------------------------------------------------------------- /Chapter05/spreadBasedOnCreditRating.pkl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Python-for-Finance-Second-Edition/019929145fdbabe23e30ef05e274994dafb5f3e3/Chapter05/spreadBasedOnCreditRating.pkl -------------------------------------------------------------------------------- /Chapter06/c6_01_learn_OLS.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c6_01_learn_OLS.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | from scipy import stats 13 | stock_ret = [0.065, 0.0265, -0.0593, -0.001,0.0346] 14 | mkt_ret = [0.055, -0.09, -0.041,0.045,0.022] 15 | (beta, alpha, r_value, p_value, std_err) = stats.linregress(stock_ret,mkt_ret) 16 | #result=stats.linregress(stock_ret,mkt_ret) 17 | 18 | print(beta, alpha) 19 | print("R-squared=", r_value**2) 20 | print("p-value =", p_value) 21 | -------------------------------------------------------------------------------- /Chapter06/c6_02_random_OLS.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c6_02_random_OLS.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | from scipy import stats 13 | import scipy as sp 14 | sp.random.seed(12456) 15 | alpha=1.0 16 | beta=0.8 17 | n=100 18 | x=sp.arange(n) 19 | y=alpha+beta*x+sp.random.rand(n) 20 | (beta, alpha, r_value, p_value, std_err) = stats.linregress(y,x) 21 | print(alpha,beta) 22 | print("R-squared=", r_value**2) 23 | print("p-value =", p_value) 24 | -------------------------------------------------------------------------------- /Chapter06/c6_03_04_read_pickle.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c6_04_read_pickle.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas as pd 12 | x=pd.read_pickle("c:/temp/yanMonthly.pkl ") 13 | print(x[0:10]) 14 | -------------------------------------------------------------------------------- /Chapter06/c6_03_random_OLS.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c6_03_ramdp_OLS.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | import numpy as np 13 | import statsmodels.api as sm 14 | y=[1,2,3,4,2,3,4] 15 | x=range(1,8) 16 | x=sm.add_constant(x) 17 | results=sm.OLS(y,x).fit() 18 | print(results.params) 19 | 20 | print(results.summary()) -------------------------------------------------------------------------------- /Chapter06/c6_05_read_excel.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c6_05_read_Excel.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas as pd 12 | x=pd.read_excel("c:/temp/Book1.xlsx") 13 | print(x) 14 | -------------------------------------------------------------------------------- /Chapter06/c6_06_input_excel_02.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c6_07_input_Excel.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | import pandas as pd 11 | infile=pd.ExcelFile("c:/temp/Book1.xlsx") 12 | x=infile.parse('Sheet1',header=None) 13 | print(x) 14 | -------------------------------------------------------------------------------- /Chapter06/c6_07_read_csv_file.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c6_07_read_csv_file.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas as pd 12 | f=pd.read_csv("c:\\temp\\ibm.csv") 13 | print(f[1:3]) -------------------------------------------------------------------------------- /Chapter06/c6_09_save_price_data_from_Google.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c6_09_save_price_data_from_Google.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas_datareader.data as getData 12 | import re 13 | ticker='msft' 14 | f=open("c:/temp/msft.txt","w") 15 | p = getData.DataReader(ticker, "google") 16 | f.write(str(p)) 17 | f.close() 18 | -------------------------------------------------------------------------------- /Chapter06/c6_10_save_price_data_from_Yahoo.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c6_10_save_price_data_from_Yahoo.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | from matplotlib.finance import quotes_historical_yahoo_ochl as getData 12 | import re 13 | ticker='msft' 14 | f=open("c:/temp/msft3.txt","w") 15 | begdate=(2013,1,1) 16 | enddate=(2013,11,9) 17 | p = getData(ticker, begdate, enddate,asobject=True,adjusted=True) 18 | f.write(str(p)) 19 | f.close() 20 | -------------------------------------------------------------------------------- /Chapter06/c6_11_save_csv_file.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c6_11_save_csv_file.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | from matplotlib.finance import quotes_historical_yahoo_ochl as getData 12 | import csv 13 | f=open("c:/temp/c.csv","w") 14 | 15 | ticker='c' 16 | begdate=(2016,1,1) 17 | enddate=(2017,1,9) 18 | p = getData(ticker, begdate, enddate,asobject=True,adjusted=True) 19 | 20 | writer = csv.writer(f) 21 | writer.writerows(p) 22 | f.close() 23 | -------------------------------------------------------------------------------- /Chapter06/c6_12_save_a_binary_file.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c6_01_save_binary_file.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import array 12 | import numpy as np 13 | outfile = "c:/temp/tmp.bin" 14 | fileobj = open(outfile, mode='wb') 15 | outvalues = array.array('f') 16 | data=np.array([1,2,3]) 17 | outvalues.fromlist(data.tolist()) 18 | outvalues.tofile(fileobj) 19 | fileobj.close() 20 | -------------------------------------------------------------------------------- /Chapter06/c6_13_save_Excel_file.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c6_13_save_Excel_file.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas as pd 12 | import pandas_datareader.data as getData 13 | import re 14 | ticker='msft' 15 | df = getData.DataReader(ticker, "google") 16 | f= pd.ExcelWriter('c:/temp/ibm.xlsx') 17 | df.to_excel(f, sheet_name='IBM_data') 18 | f.save() 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /Chapter06/c6_14_save_Excel_file_index_false.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c6_14_get_sp500.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas as pd 12 | import re 13 | from matplotlib.finance import quotes_historical_yahoo_ochl as getData 14 | ticker='^GSPC' 15 | begdate=(2013,1,1) 16 | enddate=(2013,11,9) 17 | df = getData(ticker, begdate, enddate,asobject=True,adjusted=True) 18 | f=open("c:/temp/sp500.txt","w") 19 | f.write(str(df)) 20 | f.close() 21 | 22 | 23 | -------------------------------------------------------------------------------- /Chapter06/c6_15_string_manipulation.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c6_15_string_manipulation.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | string='Hellow World!' 12 | 13 | # find the length of the string 14 | n_length=len(string) 15 | print(n_length) 16 | 17 | # the number of appearance of letter l 18 | n=string.count('l') 19 | print(n) 20 | 21 | # find teh locatoin of work of 'World' 22 | loc=string.index("World") 23 | print(loc) 24 | 25 | # number of spaces 26 | n2=string.count(' ') 27 | print(n2) 28 | 29 | print(string[0]) # print the first letter 30 | print(string[0:1]) # print the first letter (same as above) 31 | print(string[0:3]) # print the first three letters 32 | print(string[:3]) # same as above 33 | print(string[-3:]) # print the last three letters 34 | print(string[3:]) # ignore the first three 35 | print(string[:-3]) # except the last three 36 | 37 | -------------------------------------------------------------------------------- /Chapter06/c6_16_string_manipulation2.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c6_16_string_manipulation2.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | string='Hellow World!' 12 | 13 | print(string.lower()) 14 | print(string.title()) 15 | print(string.capitalize()) 16 | print(string.swapcase()) 17 | 18 | string2=string.replace("World", "John") 19 | print(string2) 20 | 21 | 22 | # strip() would remove spaces before and the end of string 23 | # lstrip() would remove spaces before and the end of string 24 | # rstrip() would remove spaces before and the end of string 25 | string3=' Hellow World! ' 26 | print(string3) 27 | print(string3.strip()) 28 | print(string3.lstrip()) 29 | print(string3.rstrip()) 30 | 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /Chapter06/c6_17_yanMonthly.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c6_17_yanMonthly.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas as pd 12 | df=pd.read_pickle("c:/temp/yanMonthly.pkl") 13 | print(df[0:10]) 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /Chapter06/c6_18_lag_and_forward.py: -------------------------------------------------------------------------------- 1 | 2 | """ 3 | Name : c6_18_lag_and_formatd.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | import pandas as pd 13 | import scipy as sp 14 | x=sp.arange(1,5,0.5) 15 | y=pd.DataFrame(x,columns=['Ret']) 16 | y['Lag']=y.shift(1) 17 | y['Forward']=y['Ret'].shift(-1) 18 | print(y) 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /Chapter06/c6_19_lag_once.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c6_19_lag_once.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas as pd 12 | import scipy as sp 13 | x=sp.arange(1,5,0.5) 14 | y=pd.DataFrame(x,columns=['Ret']) 15 | y['Lag']=y.shift(1) 16 | y['Forward']=y['Ret'].shift(-1) 17 | #final=[x,lag] 18 | 19 | 20 | 21 | 22 | 23 | #y=pd.DataFrame(logret,date,columns=[ticker]) -------------------------------------------------------------------------------- /Chapter06/c6_20_save_simple_pickle.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c6_20_save_simple_pickle.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas as pd 12 | import numpy as np 13 | np.random.seed(1234) 14 | a = pd.DataFrame(np.random.randn(6,5)) 15 | a.to_pickle('c:/temp/a.pickle') 16 | 17 | -------------------------------------------------------------------------------- /Chapter06/c6_21_yanMonthly_unique_securities.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c6_21_yanMonthly_unique_securities.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas as pd 12 | import numpy as np 13 | df=pd.read_pickle("c:/temp/yanMonthly.pkl") 14 | unique=np.unique(df.index) 15 | print(len(unique)) 16 | print(unique) 17 | 18 | -------------------------------------------------------------------------------- /Chapter06/c6_22_sp500_return_lag_lead.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c6_22_sp500_retun.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas as pd 12 | import numpy as np 13 | df=pd.read_pickle("c:/temp/yanMonthly.pkl") 14 | sp500=df[df.index=='^GSPC'] 15 | print(sp500[0:5]) 16 | ret=sp500['VALUE'].diff()/sp500['VALUE'].shift(1) 17 | print(ret[0:5]) 18 | 19 | -------------------------------------------------------------------------------- /Chapter06/c6_23_lag.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c6_24_lag.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas as pd 12 | import scipy as sp 13 | x=sp.arange(1,5,0.5) 14 | y=pd.DataFrame(x,columns=['Ret']) 15 | y['Lag']=y.shift(1) 16 | print(y) 17 | -------------------------------------------------------------------------------- /Chapter06/c6_24_bible.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c6_24_bible.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | from string import maketrans 13 | import pandas as pd 14 | word_freq = {} 15 | infile="c:/temp/AV1611.txt" 16 | word_list = open(infile, "r").read().split() 17 | ttt='!"#$%&()*+,./:;<=>?@[\\]^_`{|}~0123456789' 18 | for word in word_list: 19 | word = word.translate(maketrans("",""),ttt ) 20 | if word.startswith('-'): 21 | word = word.replace('-','') 22 | if len(word): 23 | word_freq[word] = word_freq.get(word, 0) + 1 24 | keys = sorted(word_freq.keys()) 25 | x=pd.DataFrame(keys) 26 | x.to_pickle('c:/temp/uniqueWords.pkl') 27 | 28 | 29 | -------------------------------------------------------------------------------- /Chapter06/c6_25_mention_canopy.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c6_25.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import scipy as sp 12 | print(sp.sqrt(2)) -------------------------------------------------------------------------------- /Chapter06/c6_26_beta_good.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c6_26_beta_good.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | from scipy import stats 12 | from matplotlib.finance import quotes_historical_yahoo_ochl as getData 13 | begdate=(2012,1,1) 14 | enddate=(2016,12,31) 15 | 16 | ticker='MSFT' 17 | p =getData(ticker, begdate, enddate,asobject=True,adjusted=True) 18 | retIBM = p.aclose[1:]/p.aclose[:1]-1 19 | 20 | ticker='^GSPC' 21 | p2 = getData(ticker, begdate, enddate,asobject=True,adjusted=True) 22 | retMkt = p2.aclose[1:]/p2.aclose[:1]-1 23 | (beta,alpha,r_value,p_value,std_err)=stats.linregress(retMkt,retIBM) 24 | print(alpha,beta) 25 | print("R-squared=", r_value**2) 26 | print("p-value =", p_value) 27 | -------------------------------------------------------------------------------- /Chapter06/c6_27_get_beta_good.py: -------------------------------------------------------------------------------- 1 | from scipy import stats 2 | from matplotlib.finance import quotes_historical_yahoo_ochl as aa 3 | # 4 | def dailyReturn(ticker,begdate,enddate): 5 | p = aa(ticker, begdate,enddate,asobject=True,adjusted=True) 6 | return p.aclose[1:]/p.aclose[:-1]-1 7 | # 8 | begdate=(2012,1,1) 9 | enddate=(2017,1,9) 10 | retIBM=dailyReturn("wmt",begdate,enddate) 11 | retMkt=dailyReturn("^GSPC",begdate,enddate) 12 | outputs=stats.linregress(retMkt,retIBM) 13 | print(outputs) 14 | -------------------------------------------------------------------------------- /Chapter06/c6_28_ols_example.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c6_28_OLS_example.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas as pd 12 | from pandas.stats.api import ols 13 | yRet= [0.1,0.22,0.12,0.04,-0.12] 14 | xRet=[0.1, 0.11, 0.05, -0.04, 0.22] 15 | 16 | df = pd.DataFrame({"y":yRet,"x":xRet}) 17 | result = ols(y=df['y'], x=df['x']) 18 | print(result) 19 | 20 | -------------------------------------------------------------------------------- /Chapter06/c6_29_save_text_file.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c6_29_save_text_file.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | from matplotlib.finance import quotes_historical_yahoo_ochl as getData 12 | import re 13 | ticker='msft' 14 | f=open("c:/temp/msft.txt","w") 15 | begdate=(2013,1,1) 16 | enddate=(2013,11,9) 17 | p = getData(ticker, begdate, enddate,asobject=True,adjusted=True) 18 | f.write(str(p)) 19 | f.close() 20 | -------------------------------------------------------------------------------- /Chapter06/c6_30_suggested_read_pickle_not_working.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c6_30_suggested_read_pickle_not_working.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas as pd 12 | import cStringIO 13 | import urllib2 14 | loc="http://canisius.edu/~yany/python/yanMonthly.pkl" 15 | x=pd.read_pickle(cStringIO.StringIO(urllib2.urlopen(loc).read())) 16 | 17 | 18 | y=cStringIO.StringIO(urllib2.urlopen(loc).read()) -------------------------------------------------------------------------------- /Chapter06/c6_31_read_from_a_binary_file.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c6_31_read_from_a_binary_file.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import array 12 | infile=open("c:/temp/tmp.bin", "rb") 13 | s=infile.read() # read all bytes into a string 14 | d=array.array("f", s) # "f" for float 15 | print(d) 16 | infile.close() 17 | -------------------------------------------------------------------------------- /Chapter07/c7_01_3factor_model.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | """ 4 | Name : c7_01_3factor_model.py 5 | Book : Python for Finance (2nd ed.) 6 | Publisher: Packt Publishing Ltd. 7 | Author : Yuxing Yan 8 | Date : 6/6/2017 9 | email : yany@canisius.edu 10 | paulyxy@hotmail.com 11 | """ 12 | 13 | 14 | from scipy import stats 15 | from pandas.stats.api import ols 16 | import pandas as pd 17 | y = [0.065, 0.0265, -0.0593, -0.001,0.0346] 18 | x1 = [0.055, -0.09, -0.041,0.045,0.022] 19 | x2 = [0.025, 0.10, 0.021,0.145,0.012] 20 | x3= [0.015, -0.08, 0.341,0.245,-0.022] 21 | 22 | df=pd.DataFrame({"y":y,"x1":x1, 'x2':x2,'x3':x3}) 23 | result=ols(y=df['y'],x=df[['x1','x2','x3']]) 24 | print(result) 25 | -------------------------------------------------------------------------------- /Chapter07/c7_02_critical_F_value.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c7_02_critical_F_value.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | import scipy.stats 11 | alpha=0.05 12 | dfNumerator=3 13 | dfDenominator=1 14 | 15 | f=scipy.stats.f.ppf(q=1-alpha, dfn=dfNumerator, dfd=dfDenominator) 16 | print(f) -------------------------------------------------------------------------------- /Chapter07/c7_03_random_OLS.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c7_03_random_OLS.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | import numpy as np 13 | import scipy as sp 14 | import statsmodels.regression.linear_model as sm 15 | 16 | n=100 17 | sp.random.seed(12345) 18 | 19 | y=[1,2,3,4,2,3,4] 20 | x1=range(1,8) 21 | x2=[4,2,-1,4,2,3,5] 22 | x3=[0,2,3,4,2,4,-1] 23 | x=[x1,x2,x3] 24 | x=sm.add_constant(x) 25 | #est = sm.OLS(formula='Sales ~ TV + Radio', data=df_adv).fit() 26 | results=sm.OLS(y,x1).fit() 27 | print(results.summary()) 28 | -------------------------------------------------------------------------------- /Chapter07/c7_04_3factors_model.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c7_04_3factor_model.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas as pd 12 | import numpy as np 13 | import statsmodels.api as sm 14 | 15 | inFile='http://www-bcf.usc.edu/~gareth/ISL/Advertising.csv' 16 | df_adv = pd.read_csv(inFile, index_col=0) 17 | X = df_adv[['TV', 'Radio', 'Newspaper']] 18 | y = df_adv['Sales'] 19 | df_adv.head() 20 | X = sm.add_constant(X) 21 | result = sm.OLS(y, X).fit() 22 | print(result.summary()) 23 | 24 | 25 | -------------------------------------------------------------------------------- /Chapter07/c7_06_3factors_IBMno_meaning.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c7_06_3factor_IBMno_meaning.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | import pandas as pd 11 | import numpy as np 12 | import statsmodels.api as sm 13 | 14 | inFile='http://canisius.edu/~yany/data/ibm.csv' 15 | df = pd.read_csv(inFile, index_col=0) 16 | x = df[['Open', 'High', 'Volume']] 17 | y = df['Adj.Close'] 18 | x = sm.add_constant(x) 19 | result = sm.OLS(y, x).fit() 20 | print(result.summary()) 21 | 22 | 23 | -------------------------------------------------------------------------------- /Chapter07/c7_07_generate_ffMonthly.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c7_14_sharpe_ratio_using_yanMonthly.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | import scipy as sp 11 | import numpy as np 12 | import pandas as pd 13 | file=open("c:/temp/ffMonthly.txt","r") 14 | data=file.readlines() 15 | f=[] 16 | index=[] 17 | for i in range(4,sp.size(data)): 18 | print(data[i].split()) 19 | t=data[i].split() 20 | index.append(pd.to_datetime(t[0]+'01', format='%Y%m%d').date()) 21 | #index.append(int(t[0])) 22 | for j in range(1,5): 23 | k=float(t[j]) 24 | f.append(k/100) 25 | n=len(f) 26 | f1=np.reshape(f,[n/4,4]) 27 | ff=pd.DataFrame(f1,index=index,columns=['MKT_RF','SMB','HML','Rf']) 28 | ff.to_pickle("c:/temp/ffMonthly.pkl") 29 | 30 | -------------------------------------------------------------------------------- /Chapter07/c7_100_generate_ffMonthly_txt.py: -------------------------------------------------------------------------------- 1 | # generate ff_monthly.pickle 2 | 3 | import pandas as pd 4 | import scipy as sp 5 | import numpy as np 6 | file=open("c:/temp/ffMonthly.txt","r") 7 | data=file.readlines() 8 | f=[] 9 | dd=[] 10 | for i in range(4,sp.size(data)): 11 | t=data[i].split() 12 | dd.append(pd.to_datetime(t[0]+'01', format='%Y%m%d').date()) 13 | for j in range(1,5): 14 | k=float(t[j]) 15 | f.append(k/100) 16 | n=len(f) 17 | f1=np.reshape(f,[n/4,4]) 18 | ff=pd.DataFrame(f1,index=dd,columns=['MKT_RF','SMB','HML','RF']) 19 | ff.to_pickle("c:/temp/ffMonthly.pkl") 20 | 21 | -------------------------------------------------------------------------------- /Chapter07/c7_101_generate_ffcMonthly.py: -------------------------------------------------------------------------------- 1 | # still one issue index should be the date!!!! 2 | 3 | 4 | 5 | import pandas as pd 6 | import scipy as sp 7 | import numpy as np 8 | file=open("c:/temp/ffMom.txt","r") 9 | data=file.readlines() 10 | 11 | f=[] 12 | dd=[] 13 | n=sp.size(data)-1 14 | for i in sp.arange(14,n): 15 | t=data[i].split() 16 | dd.append(pd.to_datetime(t[0]+'01', format='%Y%m%d').date()) 17 | f.append(float(t[1])/100) 18 | 19 | 20 | mom=pd.DataFrame(f,index=dd,columns=['MOM']) 21 | import pandas as pd 22 | ff3=pd.read_pickle('c:/temp/ffMonthly.pkl') 23 | ff3['DATE']=ff3.index 24 | mom['DATE']=mom.index 25 | a=pd.merge(ff3,mom) 26 | ffc=pd.DataFrame(a[['DATE','MKT_RF','SMB','HML','MOM','RF']]) 27 | ffc.to_pickle("c:/temp/ffcMonthly.pkl") 28 | -------------------------------------------------------------------------------- /Chapter07/c7_102_generate_ffMonthly5.py: -------------------------------------------------------------------------------- 1 | # generate ff_monthly.pickle 2 | 3 | import pandas as pd 4 | import scipy as sp 5 | import numpy as np 6 | file=open("c:/temp/ffMonthly5.txt","r") 7 | data=file.readlines() 8 | f=[] 9 | dd=[] 10 | for i in range(4,sp.size(data)): 11 | t=data[i].split() 12 | dd.append(pd.to_datetime(t[0]+'01', format='%Y%m%d').date()) 13 | for j in range(1,7): 14 | k=float(t[j]) 15 | f.append(k/100) 16 | n=len(f) 17 | f1=np.reshape(f,[n/6,6]) 18 | ff=pd.DataFrame(f1,index=dd,columns=['MKT_RF','SMB','HML','RMW','CMA','RF']) 19 | ff.to_pickle("c:/temp/ffMonthly5.pkl") 20 | 21 | 22 | -------------------------------------------------------------------------------- /Chapter07/c7_11_dot_diff_and_dot_shift_functions.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c7_11_dot_diff_and_dot_shift_function.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import scipy as sp 12 | import pandas as pd 13 | price=[10,11,12.2,14.0,12] 14 | x=pd.DataFrame({'Price':price}) 15 | x['diff']=x.diff() 16 | x['Ret']=x['Price'].diff()/x['Price'].shift(1) 17 | x['RetLag']=x['Ret'].shift(1) 18 | x['RetLead']=x['Ret'].shift(-1) 19 | print(x) 20 | 21 | 22 | -------------------------------------------------------------------------------- /Chapter07/c7_12_Dimson1979_sp500_lag_lead.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c7_12_Dimson1979_sp500_lag_lead.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import numpy as np 12 | import pandas as pd 13 | from pandas.stats.api import ols 14 | 15 | df=pd.read_pickle("c:/temp/yanMonthly.pkl") 16 | sp500=df[df.index=='^GSPC'] 17 | print(sp500[0:5]) 18 | sp500['retMkt']=sp500['VALUE'].diff()/sp500['VALUE'].shift(1) 19 | sp500['retMktLag']=sp500['retMkt'].shift(1) 20 | sp500['retMktLead']=sp500['retMkt'].shift(-1) 21 | print(sp500.head()) 22 | 23 | ibm=df[df.index=='IBM'] 24 | ibm['RET']=ibm['VALUE'].diff()/ibm['VALUE'].shift(1) 25 | y=pd.DataFrame(ibm[['DATE','RET']]) 26 | x=pd.DataFrame(sp500[['DATE','retMkt','retMktLag','retMktLead']]) 27 | data=pd.merge(x,y) 28 | 29 | result=ols(y=data['RET'],x=data[['retMkt','retMktLag','retMktLead']]) 30 | print(result) 31 | 32 | 33 | -------------------------------------------------------------------------------- /Chapter07/c7_14_sharpe_ratio_using_yanMonthly.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c7_14_sharpe_ratio_using_yanMonthly.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | import scipy as sp 11 | import pandas as pd 12 | df=pd.read_pickle("c:/temp/yanMonthly.pkl") 13 | rf=0.01 14 | ibm=df[df.index=='IBM'] 15 | ibm['RET']=ibm['VALUE'].diff()/ibm['VALUE'].shift(1) 16 | 17 | ret=ibm['RET'] 18 | sharpe=sp.mean((ret)-rf)/sp.std(ret) 19 | print(sharpe) 20 | 21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /Chapter07/c7_16_sharpe_ratio_YahooData.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c7_16_sharpe_ratio_YahooData.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | import scipy as sp 13 | from matplotlib.finance import quotes_historical_yahoo_ochl as getData 14 | 15 | begdate=(2012,1,1) 16 | enddate=(2016,12,31) 17 | 18 | def ret_f(ticker,begdate,enddate): 19 | p = getData(ticker,begdate, enddate,asobject=True,adjusted=True) 20 | return(p.aclose[1:]/p.aclose[:-1]-1) 21 | 22 | y=ret_f('IBM',begdate,enddate) 23 | sharpe=sp.mean(y)/sp.std(y) 24 | print(sharpe) -------------------------------------------------------------------------------- /Chapter07/c7_23_ffMonthly5.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c7_23_ffMonthly5.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas as pd 12 | ff=pd.read_pickle('c:/temp/ffMonthly5.pkl') 13 | 14 | -------------------------------------------------------------------------------- /Chapter07/c7_23_generate_ffMonthly5.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c7_23_generate_ffMonthly5.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | import pandas as pd 11 | import scipy as sp 12 | import numpy as np 13 | file=open("c:/temp/ffMonthly5.txt","r") 14 | data=file.readlines() 15 | 16 | f=[] 17 | dd=[] 18 | n=sp.size(data)-1 19 | for i in sp.arange(14,n): 20 | t=data[i].split() 21 | dd.append(pd.to_datetime(t[0]+'01', format='%Y%m%d').date()) 22 | f.append(float(t[1])/100) 23 | 24 | """ 25 | mom=pd.DataFrame(f,index=dd,columns=['MOM']) 26 | import pandas as pd 27 | ff3=pd.read_pickle('c:/temp/ffMonthly.pkl') 28 | ff3['DATE']=ff3.index 29 | mom['DATE']=mom.index 30 | a=pd.merge(ff3,mom) 31 | ff4=pd.DataFrame(a[['DATE','MKT_RF','SMB','HML','MOM','RF']]) 32 | 33 | 34 | #ff.to_pickle("c:/temp/ffMonthly5.pkl") 35 | """ 36 | -------------------------------------------------------------------------------- /Chapter07/c7_24_generate_ffmonMonthly.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c7_24_generateffmonMonthly.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas as pd 12 | import scipy as sp 13 | import numpy as np 14 | file=open("c:/temp/ffMom.txt","r") 15 | data=file.readlines() 16 | 17 | f=[] 18 | dd=[] 19 | n=sp.size(data)-1 20 | for i in sp.arange(14,n): 21 | t=data[i].split() 22 | dd.append(pd.to_datetime(t[0]+'01', format='%Y%m%d').date()) 23 | f.append(float(t[1])/100) 24 | 25 | mom=pd.DataFrame(f,index=dd,columns=['MOM']) 26 | mom.to_pickle("c:/temp/ffMomMonthly.pkl") 27 | -------------------------------------------------------------------------------- /Chapter07/c7_24_read_ffcMonthly.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c7_24_read_ffMonthly.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | 12 | import pandas as pd 13 | x=pd.read_pickle("c:/temp/ffMonthly.pkl") 14 | print(x.head()) 15 | print(x.tail()) -------------------------------------------------------------------------------- /Chapter07/c7_25_generate_ffcMonthly_pkl.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c7_25_generateffcMonthly_pkl.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas as pd 12 | ff=pd.read_pickle("c:/temp/ffMonthly.pkl") 13 | print(ff.head(2)) 14 | 15 | mom=pd.read_pickle("c:/temp/ffMomMonthly.pkl") 16 | print(mom.head(3)) 17 | 18 | x=pd.merge(ff,mom,left_index=True,right_index=True) 19 | print(x.head()) 20 | 21 | x.to_pickle("c:/temp/ffcMonthly.pkl") 22 | 23 | 24 | -------------------------------------------------------------------------------- /Chapter07/c7_26_read_ffMonthly5.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c7_26_read_ffMonthly5.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas as pd 12 | x=pd.read_pickle("c:/temp/ffMonthly5.pkl") 13 | print(x.head()) 14 | print(x.tail()) 15 | -------------------------------------------------------------------------------- /Chapter07/c7_30_merge_not_good.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c7_30_merge_not_good.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas as pd 12 | x=pd.DataFrame([[40,50],[0.2,0.3]],rows=['A','B']) 13 | y=pd.DataFrame([[30,22],[0.1,-0.25]],rows=['C','B']) 14 | z=pd.merge(x,y) 15 | 16 | -------------------------------------------------------------------------------- /Chapter07/c7_31_merge_01.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c7_31_mrege_01.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | import scipy as sp 11 | import pandas as pd 12 | # 13 | x= pd.DataFrame({'key': ['K0', 'K1', 'K2', 'K3'], 14 | 'A': ['A0', 'A1', 'A2', 'A3'], 15 | 'B': ['B0', 'B1', 'B2', 'B3']}) 16 | y = pd.DataFrame({'key': ['K0', 'K1', 'K2', 'K6'], 17 | 'C': ['C0', 'C1', 'C2', 'C3'], 18 | 'D': ['D0', 'D1', 'D2', 'D3']}) 19 | print(sp.shape(x)) 20 | print(sp.shape(y)) 21 | print(x) 22 | print(y) 23 | 24 | result = pd.merge(x,y, on='key') 25 | print(result) 26 | 27 | result2=pd.merge(x,y) 28 | print(result2) 29 | 30 | -------------------------------------------------------------------------------- /Chapter07/c7_32_merge_02_different_names.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c7_32_mrege_different_names.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas as pd 12 | import scipy as sp 13 | x= pd.DataFrame({'YEAR': [2010,2011, 2012, 2013], 14 | 'IBM': [0.2, -0.3, 0.13, -0.2], 15 | 'WMT': [0.1, 0, 0.05, 0.23]}) 16 | y = pd.DataFrame({'date': [2011,2013,2014, 2015], 17 | 'C': [0.12, 0.23, 0.11, -0.1], 18 | 'SP500': [0.1,0.17, -0.05, 0.13]}) 19 | print(pd.merge(x,y, left_on='YEAR',right_on='date')) 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /Chapter07/c7_32_merge_02_stock.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c7_32_merge_02_stock.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | import pandas as pd 11 | import scipy as sp 12 | x= pd.DataFrame({'YEAR': [2010,2011, 2012, 2013], 13 | 'IBM': [0.2, -0.3, 0.13, -0.2], 14 | 'WMT': [0.1, 0, 0.05, 0.23]}) 15 | y = pd.DataFrame({'YEAR': [2011,2013,2014, 2015], 16 | 'C': [0.12, 0.23, 0.11, -0.1], 17 | 'SP500': [0.1,0.17, -0.05, 0.13]}) 18 | 19 | print(pd.merge(x,y, on='YEAR')) 20 | print(pd.merge(x,y, on='YEAR',how='outer')) 21 | print(pd.merge(x,y, on='YEAR',how='left')) 22 | print(pd.merge(x,y, on='YEAR',how='left')) 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /Chapter07/c7_33_merge_03_left_index.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c7_33_merge_03_lef_right_index.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas as pd 12 | import scipy as sp 13 | x= pd.DataFrame({'YEAR': [2010,2011, 2012, 2013], 14 | 'IBM': [0.2, -0.3, 0.13, -0.2], 15 | 'WMT': [0.1, 0, 0.05, 0.23]}) 16 | y = pd.DataFrame({'date': [2011,2013,2014, 2015], 17 | 'C': [0.12, 0.23, 0.11, -0.1], 18 | 'SP500': [0.1,0.17, -0.05, 0.13]}) 19 | print(pd.merge(x,y, right_index=True,left_index=True)) 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /Chapter07/c7_34_merge_by_two_variables.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c7_34_merge_by_two_variables.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas as pd 12 | x= pd.DataFrame({'ID': ['IBM', 'IBM', 'WMT', 'WMT'], 13 | 'date': [2010, 2011, 2010, 2011], 14 | 'SharesOut': [100, 40, 60, 90], 15 | 'Asset': [20, 30, 10, 30]}) 16 | 17 | y = pd.DataFrame({'ID': ['IBM', 'IBM', 'C', 'WMT'], 18 | 'date': [2010, 2014, 2010, 2010], 19 | 'Ret': [0.1, 0.2, -0.1,0.2], 20 | 'ROA': [0.04,-0.02,0.03,0.1]}) 21 | 22 | z= pd.merge(x,y, on=['ID', 'date']) -------------------------------------------------------------------------------- /Chapter07/c7_39_LPSD.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c7_39_LPSD.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | 12 | import scipy as sp 13 | import numpy as np 14 | 15 | mean=0.10; 16 | Rf=0.02 17 | std=0.20 18 | n=100 19 | sp.random.seed(12456) 20 | x=sp.random.normal(loc=mean,scale=std,size=n) 21 | print("std=", sp.std(x)) 22 | 23 | y=x[x-Rf<0] 24 | m=len(y) 25 | total=0.0 26 | 27 | for i in sp.arange(m): 28 | total+=(y[i]-Rf)**2 29 | 30 | LPSD=total/(m-1) 31 | print("y=",y) 32 | print("LPSD=",LPSD) -------------------------------------------------------------------------------- /Chapter07/c7_40_generate_usCPImonthly.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c7_40_generate_usCPImonthly.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | import scipy as sp 11 | import pandas as pd 12 | # 13 | x=pd.read_csv("c:/temp/CPI_19jan2017.csv",skiprows=8) 14 | n=len(x) 15 | 16 | ddate=[] 17 | cpi0=[] 18 | k=1 19 | for i in sp.arange(n): 20 | y=sp.array(x[i:(i+1)]) 21 | for j in sp.arange(12): 22 | ddate.append(y[0,0]*100+j+1) 23 | cpi0.append(y[0,j+1]/100) 24 | #print(y) 25 | 26 | cpi=pd.DataFrame(cpi0,index=ddate) 27 | cpi.to_pickle("c:/temp/usCPImonthly.pkl") -------------------------------------------------------------------------------- /Chapter07/c7_41_generate_ibmMonthly_pkl.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c7_41_generte_ibmMonthly_pkl.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas as pd 12 | import scipy as sp 13 | import time 14 | # b=time.strptime(x['Date'][0],"%Y-%m-%d") 15 | x=pd.read_csv("c:/temp/ibmMonthly.csv",index_col=0) 16 | n=len(x) 17 | 18 | """ 19 | ddate=[] 20 | for i in sp.arange(n): 21 | ddate.append(time.strptime(x['Date'][i],"%Y-%m-%d")) 22 | 23 | #ibmMonthly=pd.DataFrame(x['Open'],x['High'],x['Low'],x['Close'],x['Volume'],x['Adj Close'],index=ddate) 24 | #ibmMonthly=pd.DataFrame(x,columns=[['DATE','OPEN','HIGH','LOW','CLOSE','VOLUME','ADJCLOSE']]) 25 | """ 26 | 27 | ibmMonthly=pd.DataFrame(x) 28 | 29 | ret=-x['Adj Close'].diff(-1)/x['Adj Close'].shift(-1) 30 | #dd=x['Adj Close'].shift(-1) 31 | 32 | ibmMonthly['RET']=ret 33 | ibmMonthly.to_pickle("c:/temp/ibmMonthly.pkl") 34 | -------------------------------------------------------------------------------- /Chapter07/c7_41_generate_usGDPquarterly.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | import scipy as sp 3 | x=pd.read_csv("c:/temp/GDP_Yan.csv",skiprows=10) 4 | n=len(x) 5 | ddate=[] 6 | a=[] 7 | k=1 8 | for i in sp.arange(n): 9 | y=sp.array(x[i:(i+1)]) 10 | ddate.append( pd.to_datetime(y[0,0]).date()) 11 | a.append(y[0,1]) 12 | #print(y) 13 | 14 | GDP=pd.DataFrame(a,columns=['AdjustedGDPannualBillion'],index=ddate) 15 | GDP.to_pickle("c:/temp/usGDPquarterly.pkl") 16 | -------------------------------------------------------------------------------- /Chapter07/c7_55_merge_how_4types.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | import scipy as sp 3 | x= pd.DataFrame({'YEAR': [2010,2011, 2012, 2013], 4 | 'IBM': [0.2, -0.3, 0.13, -0.2], 5 | 'WMT': [0.1, 0, 0.05, 0.23]}) 6 | y = pd.DataFrame({'YEAR': [2011,2013,2014, 2015], 7 | 'C': [0.12, 0.23, 0.11, -0.1], 8 | 'SP500': [0.1,0.17, -0.05, 0.13]}) 9 | 10 | print(pd.merge(x,y, on='YEAR')) 11 | print(pd.merge(x,y, on='YEAR',how='outer')) 12 | print(pd.merge(x,y, on='YEAR',how='left')) 13 | print(pd.merge(x,y, on='YEAR',how='right')) 14 | -------------------------------------------------------------------------------- /Chapter07/c7_56_merge_ffMonthly_GDPquarterly.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | GDP=pd.read_pickle("c:/temp/usGDPquarterly.pkl") 3 | ff=pd.read_pickle("c:/temp/ffMonthly.pkl") 4 | print(GDP.head()) 5 | print(ff.head()) 6 | 7 | -------------------------------------------------------------------------------- /Chapter07/c7_88_generate_ffMonthly.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | import scipy as sp 3 | import numpy as np 4 | file=open("c:/temp/ffMonthly.txt","r") 5 | data=file.readlines() 6 | f=[] 7 | index=[] 8 | for i in range(4,sp.size(data)): 9 | t=data[i].split() 10 | index.append(int(t[0])) 11 | for j in range(1,5): 12 | k=float(t[j]) 13 | f.append(k/100) 14 | n=len(f) 15 | f1=np.reshape(f,[n/4,4]) 16 | ff=pd.DataFrame(f1,index=index,columns=['MKT_RF','SMB','HML','RF']) 17 | ff.to_pickle("c:/temp/ffMonthly.pkl") 18 | 19 | 20 | -------------------------------------------------------------------------------- /Chapter07/c7_print_ff3factor.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | x=pd.read_pickle("c:/temp/ffMonthly.pkl") 3 | print(x.head()) 4 | print(x.tail()) -------------------------------------------------------------------------------- /Chapter07/c7_simple_ff3_IBM.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | import scipy as sp 3 | import statsmodels.api as ms 4 | 5 | a=pd.read_pickle("c:/temp/ibmMonthly.pkl") 6 | ff=pd.read_pickle("c:/temp/ffMonthly.pkl") 7 | df=pd.merge(a,ff,left_index=True,right_index=True) 8 | 9 | 10 | y=final['RET'] 11 | x=final[['MKT_RF','SMB','HML']] 12 | x=sm.add_constant(x) 13 | results=sm.OLS(y,x).fit() 14 | print(results.summary()) 15 | 16 | 17 | -------------------------------------------------------------------------------- /Chapter08/c8_01_first_one.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c8_01_first_one.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas as pd 12 | import scipy as sp 13 | mean=0.10 14 | std=0.2 15 | ddate = pd.date_range('1/1/2016', periods=252) 16 | n=len(ddate) 17 | 18 | data = pd.Series(sp.random.normal(mean,std,n), index=ddate) 19 | print(data.head()) -------------------------------------------------------------------------------- /Chapter08/c8_02_get_date_varible_using_pandasDataFrame.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c8_02_get_date_variable.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas as pd 12 | import scipy as sp 13 | 14 | sp.random.seed(1257) 15 | mean=0.10 16 | std=0.2 17 | ddate = pd.date_range('1/1/2016', periods=252) 18 | n=len(ddate) 19 | rets=sp.random.normal(mean,std,n) 20 | data = pd.DataFrame(rets, index=ddate,columns=['RET']) 21 | print(data.head()) 22 | -------------------------------------------------------------------------------- /Chapter08/c8_03_daily_to_monthly.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c8_03_daily_to_monthly.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | from matplotlib.finance import quotes_historical_yahoo_ochl as getData 12 | import numpy as np 13 | import pandas as pd 14 | 15 | ticker='IBM' 16 | begdate=(2013,1,1) 17 | enddate=(2013,11,9) 18 | 19 | x = getData(ticker, begdate, enddate,asobject=True, adjusted=True) 20 | logret = np.log(x.aclose[1:]/x.aclose[:-1]) 21 | yyyymm=[] 22 | d0=x.date 23 | 24 | for i in range(0,np.size(logret)): 25 | yyyymm.append(''.join([d0[i].strftime("%Y"),d0[i].strftime("%m")])) 26 | 27 | y=pd.DataFrame(logret,yyyymm,columns=['retMonthly']) 28 | retMonthly=y.groupby(y.index).sum() 29 | 30 | print(retMonthly.head()) 31 | -------------------------------------------------------------------------------- /Chapter08/c8_04_retrieve_daily_from_Yahoo.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c8_04_retrieve_daily_from_Yahoo.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | from matplotlib.finance import quotes_historical_yahoo_ochl as getData 12 | x = getData("IBM",(2016,1,1),(2016,1,21),asobject=True, adjusted=True) 13 | print(x[0:4]) 14 | 15 | -------------------------------------------------------------------------------- /Chapter08/c8_05_print_GDPquarterly_ffMonthly.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c8_05_print_GDPquarterly_ffMonthly.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas as pd 12 | GDP=pd.read_pickle("c:/temp/usGDPquarterly.pkl") 13 | ff=pd.read_pickle("c:/temp/ffMonthly.pkl") 14 | print(GDP.head()) 15 | print(ff.head()) 16 | -------------------------------------------------------------------------------- /Chapter08/c8_05_print_obs_from_Google.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c8_05_print_obs_from_Google.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas_datareader.data as getData 12 | import re 13 | ticker='msft' 14 | p = getData.DataReader(ticker, "google") 15 | print(p.head()) 16 | -------------------------------------------------------------------------------- /Chapter08/c8_05_print_obs_from_Google2.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c8_06_print_obs_from_Google2.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas_datareader.data as web 12 | import datetime 13 | ticker='MSFT' 14 | begdate = datetime.datetime(2012, 1, 2) 15 | enddate = datetime.datetime(2017, 1, 10) 16 | a = web.DataReader(ticker, 'google',begdate,enddate) 17 | print(a.head(3)) 18 | print(a.tail(2)) 19 | -------------------------------------------------------------------------------- /Chapter08/c8_05_yahoo_stock_splits_dividends_data_notWorking.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c8_05_print_obs_from_Google.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | 12 | 13 | import pandas_datareader.data as web 14 | import datetime 15 | ticker='WMT' 16 | begdate = datetime.datetime(2010, 1, 1) 17 | enddate= datetime.datetime(2015, 5, 9) 18 | x=web.DataReader(ticker,'yahoo-actions',begdate,enddate) 19 | print(x.head()) -------------------------------------------------------------------------------- /Chapter08/c8_06_get_daily_data_from_Google.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c8_06_get_daily_data_from_Google.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas_datareader.data as web 12 | import datetime 13 | 14 | ticker='MSFT' 15 | begdate = datetime.datetime(2012, 1, 2) 16 | enddate = datetime.datetime(2017, 1, 10) 17 | 18 | a = web.DataReader(ticker, 'google',begdate,enddate) 19 | 20 | print(a.head(3)) 21 | print(a.tail(2)) -------------------------------------------------------------------------------- /Chapter08/c8_06_noLonger_working.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | url='http://chart.yahoo.com/table.csv?s=IBM' 3 | x=pd.read_csv(url,index_col=0,parse_dates=True) 4 | print(x.head()) 5 | -------------------------------------------------------------------------------- /Chapter08/c8_07_pandas_datareader_GDP.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c8_07_pandas_datareader_GDP.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas_datareader.data as web 12 | import datetime 13 | begdate = datetime.datetime(1900, 1, 1) 14 | enddate = datetime.datetime(2017, 1, 27) 15 | 16 | x= web.DataReader("GDP", "fred", begdate,enddate) 17 | print(x.head(2)) 18 | print(x.tail(3)) 19 | 20 | -------------------------------------------------------------------------------- /Chapter08/c8_07_pandas_read_csv_function.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c8_07_pandas_read+csv_function.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas as pd 12 | url='http://canisius.edu/~yany/data/ibm.csv' 13 | x=pd.read_csv(url,index_col=0,parse_dates=True) 14 | print(x.head()) 15 | -------------------------------------------------------------------------------- /Chapter08/c8_08_gen_quote_yahoo_good.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c8_08_get_quote_yahoo_good.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas_datareader.data as web 12 | ticker='AMZN' 13 | print(web.get_quote_yahoo (ticker)) 14 | -------------------------------------------------------------------------------- /Chapter08/c8_08_generate_GDP_pickle_using_pandas_datareader_GDP.py: -------------------------------------------------------------------------------- 1 | import pandas_datareader.data as web 2 | import datetime 3 | begdate = datetime.datetime(1900, 1, 1) 4 | enddate = datetime.datetime(2017, 1, 27) 5 | 6 | x= web.DataReader("GDP", "fred", begdate,enddate) 7 | print(x.head(2)) 8 | print(x.tail(3)) 9 | 10 | x.to_pickle("c:/temp/usGDPquarterly2.pkl") 11 | 12 | 13 | 14 | 15 | import pandas as pd 16 | a=pd.read_pickle("c:/temp/usGDPquarterly2.pkl") 17 | print(a.head()) 18 | print(a.tail()) -------------------------------------------------------------------------------- /Chapter08/c8_09_foreigh_exchange_not_working.py: -------------------------------------------------------------------------------- 1 | from pandas_datareader.oanda import get_oanda_currency_historical_rates 2 | start, end = "2016-01-01", "2016-06-01" 3 | quote_currency = "USD" 4 | base_currency = ["EUR", "GBP", "JPY"] 5 | df_rates = get_oanda_currency_historical_rates(start, end,quote_currency=quote_currency,base_currency=base_currency) 6 | print(df_rates) 7 | 8 | 9 | -------------------------------------------------------------------------------- /Chapter08/c8_09_pandas_interpolate.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import pandas as pd 3 | nn=np.nan 4 | x=pd.Series([0.29,0.57,nn,1.34,nn,nn,nn,nn,2.7]) 5 | y=x.interpolate() 6 | print(y) 7 | -------------------------------------------------------------------------------- /Chapter08/c8_10_normality_test_random_from_normal_distribution.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c8_10_normality_test_from_normal.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | from scipy import stats 12 | import scipy as sp 13 | 14 | sp.random.seed(12345) 15 | mean=0.1 16 | std=0.2 17 | n=5000 18 | 19 | ret=sp.random.normal(loc=0,scale=std,size=n) 20 | 21 | print 'W-test, and P-value' 22 | print(stats.shapiro(ret)) 23 | -------------------------------------------------------------------------------- /Chapter08/c8_10_ochl_still_working.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c8_10_ochl_still_working.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | 12 | from matplotlib.finance import quotes_historical_yahoo_ochl as getData 13 | x = getData("IBM",(2016,1,1),(2016,1,21),asobject=True, adjusted=True) 14 | print(x[0:4]) 15 | -------------------------------------------------------------------------------- /Chapter08/c8_11_normality_test_random_from_uniform.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c8_11_normality_test_random_from_uniform.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | from scipy import stats 12 | import scipy as sp 13 | sp.random.seed(12345) 14 | n=5000 15 | ret=sp.random.uniform(size=n) 16 | print 'W-test, and P-value' 17 | print(stats.shapiro(ret)) 18 | -------------------------------------------------------------------------------- /Chapter08/c8_12_normality_test_for_IBM.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c8_12_normality_test_for_IBM.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | from scipy import stats 12 | from matplotlib.finance import quotes_historical_yahoo_ochl as getData 13 | import numpy as np 14 | 15 | ticker='IBM' 16 | begdate=(2012,1,1) 17 | enddate=(2016,12,31) 18 | 19 | p =getData(ticker, begdate, enddate,asobject=True, adjusted=True) 20 | ret = (p.aclose[1:] - p.aclose[:-1])/p.aclose[1:] 21 | print 'ticker=',ticker,'W-test, and P-value' 22 | print(stats.shapiro(ret)) 23 | 24 | 25 | print( stats.anderson(ret) ) -------------------------------------------------------------------------------- /Chapter08/c8_13_get_current_quote.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c8_13_get_current_quote.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas_datareader.data as web 12 | ticker='AMZN' 13 | print(web.get_quote_yahoo(ticker)) -------------------------------------------------------------------------------- /Chapter08/c8_14_mean_std_skew_kurt.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c8_14_mean_std_skew_kurt.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | from scipy import stats,random 12 | import numpy as np 13 | np.random.seed(12345) 14 | ret = random.normal(0,1,500000) 15 | 16 | print('mean =', np.mean(ret)) 17 | print('std =',np.std(ret)) 18 | print('skewness=',stats.skew(ret)) 19 | print('kurtosis=',stats.kurtosis(ret)) 20 | -------------------------------------------------------------------------------- /Chapter08/c8_15_merge_ffMonthly_GDP.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c8_15_merge_ffMonthly_GDP.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas as pd 12 | import pandas_datareader.data as web 13 | import datetime 14 | begdate = datetime.datetime(1900, 1, 1) 15 | enddate = datetime.datetime(2017, 1, 27) 16 | GDP= web.DataReader("GDP", "fred", begdate,enddate) 17 | ff=pd.read_pickle("c:/temp/ffMonthly.pkl") 18 | final=pd.merge(ff,GDP,left_index=True,right_index=True,how='left') 19 | tt=final['GDP'] 20 | GDP2=pd.Series(tt).interpolate() 21 | final['GDP2']=GDP2 22 | #print(GDP.head()) 23 | #print(ff.head()) 24 | print(final.head()) 25 | print(final.tail(10)) 26 | 27 | -------------------------------------------------------------------------------- /Chapter08/c8_16_4moments_forSP500.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c8_16_4moments_for_sp500.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | from scipy import stats 12 | from matplotlib.finance import quotes_historical_yahoo_ochl as getData 13 | import numpy as np 14 | ticker='^GSPC' 15 | begdate=(1926,1,1) 16 | enddate=(2016,12,31) 17 | p = getData(ticker, begdate, enddate,asobject=True, adjusted=True) 18 | ret = p.aclose[1:]/p.aclose[:-1]-1 19 | print( 'S&P500 n =',len(ret)) 20 | print( 'S&P500 mean =',round(np.mean(ret),8)) 21 | print('S&P500 std =',round(np.std(ret),8)) 22 | print('S&P500 skewness=',round(stats.skew(ret),8)) 23 | print('S&P500 kurtosis=',round(stats.kurtosis(ret),8)) 24 | -------------------------------------------------------------------------------- /Chapter08/c8_17_ttest_mean_point5.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c8_17_ttest_mean_point5.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | 12 | from scipy import stats 13 | import numpy as np 14 | np.random.seed(1235) 15 | x = stats.norm.rvs(size=10000) 16 | print("T-value P-value (two-tail)") 17 | print(stats.ttest_1samp(x,0.5)) 18 | print(stats.ttest_1samp(x,0)) 19 | -------------------------------------------------------------------------------- /Chapter08/c8_18_merge_ff_daily_return.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c8_18_merge_ffDaily_return.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import numpy as np 12 | import pandas as pd 13 | from matplotlib.finance import quotes_historical_yahoo_ochl as getData 14 | # 15 | ticker='IBM' 16 | begdate=(2016,1,2) 17 | enddate=(2017,1,9) 18 | x =getData(ticker, begdate, enddate,asobject=True, adjusted=True) 19 | myName=ticker+'_adjClose' 20 | x2=pd.DataFrame(x['aclose'],x.date,columns=[myName]) 21 | ff=pd.read_pickle('c:/temp/ffDaily.pkl') 22 | final=pd.merge(x2,ff,left_index=True,right_index=True) 23 | print(final.head()) 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /Chapter08/c8_18_ttest_IBM_2013.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c8_18_ttest_IBM_2013.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | from scipy import stats 12 | import scipy as sp 13 | from matplotlib.finance import quotes_historical_yahoo_ochl as getData 14 | ticker='ibm' 15 | begdate=(2013,1,1) 16 | enddate=(2013,12,31) 17 | p=getData(ticker,begdate,enddate,asobject=True, adjusted=True) 18 | ret=p.aclose[1:]/p.aclose[:-1]-1 19 | print(' Mean T-value P-value ' ) 20 | print(round(sp.mean(ret),5), stats.ttest_1samp(ret,0)) 21 | -------------------------------------------------------------------------------- /Chapter08/c8_19_Roll_spread.py: -------------------------------------------------------------------------------- 1 | 2 | """ 3 | Name : c8_19_Roll_spread.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | from matplotlib.finance import quotes_historical_yahoo_ochl as getData 13 | import scipy as sp 14 | ticker='IBM' 15 | begdate=(2013,9,1) 16 | enddate=(2013,11,11) 17 | data= getData(ticker, begdate, enddate,asobject=True, adjusted=True) 18 | p=data.aclose 19 | d=sp.diff(p) 20 | cov_=sp.cov(d[:-1],d[1:]) 21 | if cov_[0,1]<0: 22 | print("Roll spread for ", ticker, 'is', round(2*sp.sqrt(-cov_[0,1]),3)) 23 | else: 24 | print("Cov is positive for ",ticker, 'positive', round(cov_[0,1],3)) 25 | 26 | -------------------------------------------------------------------------------- /Chapter08/c8_20_Durbin_Watson_test.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c8_20_Durbin_Watson_test.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import statsmodels.stats.stattools as tools 12 | from matplotlib.finance import quotes_historical_yahoo_ochl as getData 13 | # 14 | ticker='IBM' 15 | begdate=(2012,1,2) 16 | enddate=(2016,12,31) 17 | data= getData(ticker, begdate, enddate,asobject=True, adjusted=True) 18 | p=data.aclose 19 | ret=p[:1]/p[1:]-1 20 | 21 | print(tools.durbin_watson(ret)) 22 | -------------------------------------------------------------------------------- /Chapter08/c8_21_use_tempfile.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c8_17_ttest_mean_point5.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import tempfile 12 | import re, string 13 | import pandas as pd 14 | ticker='AAPL' # input a ticker 15 | f1="c:/temp/ttt.txt" # ttt will be replace with above sticker 16 | f2=f1.replace("ttt",ticker) 17 | outfile=open(f2,"w") 18 | #path="http://www.google.com/finance/getprices?q=ttt&i=300&p=10d&f=d,o, h,l,c,v" 19 | path="https://www.google.com/finance/getprices?q=ttt&i=300&p=10d&f=d,o,%20h,l,c,v" 20 | path2=path.replace("ttt",ticker) 21 | df=pd.read_csv(path2,skiprows=8,header=None) 22 | fp = tempfile.TemporaryFile() 23 | df.to_csv(fp) 24 | print(df.head()) 25 | fp.close() 26 | -------------------------------------------------------------------------------- /Chapter08/c8_22_table2_get_year_month_day_from_a_date_var.py: -------------------------------------------------------------------------------- 1 | 2 | """ 3 | Name : c8_22_table2_get_year_month_day.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | import datetime 13 | today=datetime.date.today() 14 | year=today.strftime("%Y") 15 | year2=today.strftime("%y") 16 | month=today.strftime("%m") 17 | day=today.strftime("%d") 18 | 19 | print(year,month,day,year2) -------------------------------------------------------------------------------- /Chapter08/c8_24_second_way_to_calculate_returns.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c8_24_second_way_to_calculate_return.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas as pd 12 | import scipy as sp 13 | p=[1,1.1,0.9,1.05] 14 | a=pd.DataFrame({'Price':p}) 15 | a['Ret']=a['Price'].diff()/a['Price'].shift(1) 16 | print(a) 17 | -------------------------------------------------------------------------------- /Chapter08/c8_25_interplate.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c8_25_interplate.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas as pd 12 | import numpy as np 13 | nn=np.nan 14 | x=pd.Series([1,2,nn,nn,6]) 15 | print(x.interpolate()) 16 | 17 | -------------------------------------------------------------------------------- /Chapter08/c8_26_test_daily_mean_is_zero.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c8_26_test_daily_mean_is_zero.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | import scipy as sp 11 | from scipy import stats 12 | from matplotlib.finance import quotes_historical_yahoo_ochl as getData 13 | # 14 | ticker='ibm' 15 | begdate=(2013,1,1) 16 | enddate=(2013,12,31) 17 | p=getData(ticker,begdate,enddate,asobject=True, adjusted=True) 18 | ret=p.aclose[1:]/p.aclose[:-1]-1 19 | print(' Mean T-value P-value ' ) 20 | print(round(sp.mean(ret),5), stats.ttest_1samp(ret,0)) 21 | -------------------------------------------------------------------------------- /Chapter08/c8_27_test_equal_variances.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c8_37_test_equal_variance.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import scipy as sp 12 | from matplotlib.finance import quotes_historical_yahoo_ochl as getData 13 | begdate=(2012,1,1) 14 | enddate=(2016,12,31) 15 | def ret_f(ticker,begdate,enddate): 16 | p = getData(ticker,begdate, enddate,asobject=True,adjusted=True) 17 | return p.aclose[1:]/p.aclose[:-1]-1 18 | 19 | y=ret_f('IBM',begdate,enddate) 20 | x=ret_f('DELL',begdate,enddate) 21 | print(sp.stats.bartlett(x,y)) 22 | -------------------------------------------------------------------------------- /Chapter08/c8_28_52_week_high.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c8_28_52_week_high.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import numpy as np 12 | from datetime import datetime 13 | from dateutil.relativedelta import relativedelta 14 | from matplotlib.finance import quotes_historical_yahoo_ochl as getData 15 | # 16 | ticker='IBM' 17 | enddate=datetime(2016,12,31) 18 | # 19 | begdate=enddate-relativedelta(years=1) 20 | p =getData(ticker, begdate, enddate,asobject=True, adjusted=True) 21 | x=p[-1] 22 | y=np.array(p.tolist())[:,-1] 23 | high=max(y) 24 | low=min(y) 25 | print(" Today, Price High Low, % from low ") 26 | print(x[0], x[-1], high, low, round((x[-1]-low)/(high-low)*100,2)) 27 | -------------------------------------------------------------------------------- /Chapter08/c8_31_get_high_frequency_data_google.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c8_31_get_high_fequency_data_google.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import re, string 12 | import pandas as pd 13 | ticker='AAPL' # input a ticker 14 | f1="c:/temp/ttt.txt" # ttt will be replace with above sticker 15 | f2=f1.replace("ttt",ticker) 16 | outfile=open(f2,"w") 17 | path="https://www.google.com/finance/getprices?q=ttt&i=300&p=10d&f=d,o,%20h,l,c,v" 18 | path2=path.replace("ttt",ticker) 19 | df=pd.read_csv(path2,skiprows=8,header=None) 20 | df.to_csv(outfile,header=False,index=False) 21 | outfile.close() 22 | -------------------------------------------------------------------------------- /Chapter08/c8_32_print_TORQct.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c8_32_print_TORQct.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import scipy as sp 12 | import pandas as pd 13 | # 14 | x=pd.read_pickle("c:/temp/TORQct.pkl") 15 | print(x.head()) 16 | print(x.tail()) 17 | print(sp.shape(x)) -------------------------------------------------------------------------------- /Chapter08/c8_33_read_TORQcq.py: -------------------------------------------------------------------------------- 1 | 2 | """ 3 | Name : c8_33_print_TORQcq.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | import pandas as pd 13 | cq=pd.read_pickle("c:/temp/TORQcq.pkl") 14 | print(cq.head() ) 15 | -------------------------------------------------------------------------------- /Chapter08/c8_34_Durbin_Watson_test_CAPM_IBM_residual.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c8_36_Durbin_WatSon_.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas as pd 12 | from scipy import stats 13 | import statsmodels.formula.api as sm 14 | import statsmodels.stats.stattools as tools 15 | from matplotlib.finance import quotes_historical_yahoo_ochl as getData 16 | # 17 | begdate=(2012,1,1) 18 | enddate=(2016,12,31) 19 | # 20 | def dailyRet(ticker,begdate,enddate): 21 | p =getData(ticker, begdate, enddate,asobject=True,adjusted=True) 22 | return p.aclose[1:]/p.aclose[:-1]-1 23 | 24 | retIBM=dailyRet('IBM',begdate,enddate) 25 | retMkt=dailyRet('^GSPC',begdate,enddate) 26 | 27 | df = pd.DataFrame({"Y":retIBM, "X": retMkt}) 28 | result = sm.ols(formula="Y ~X", data=df).fit() 29 | print(result.params) 30 | residuals=result.resid 31 | print("Durbin Watson") 32 | print(tools.durbin_watson(residuals)) 33 | -------------------------------------------------------------------------------- /Chapter08/c8_35_pandas_OLS.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c8_35_Pandas_OLS.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import numpy as np 12 | import pandas as pd 13 | from datetime import datetime 14 | n = 252 15 | np.random.seed(12345) 16 | begdate=datetime(2013, 1, 2) 17 | dateRange = pd.date_range(begdate, periods=n) 18 | x0= pd.DataFrame(np.random.randn(n, 1),columns=['ret'],index=dateRange) 19 | y0=pd.Series(np.random.randn(n), index=dateRange) 20 | print pd.ols(y=y0, x=x0) 21 | -------------------------------------------------------------------------------- /Chapter08/c8_36_Fama_Mecbeth_regression.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c8_36_Fama_MecBeth_regression.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import numpy as np 12 | import pandas as pd 13 | import statsmodels.api as sm 14 | from datetime import datetime 15 | # 16 | n = 252 17 | np.random.seed(12345) 18 | begdate=datetime(2013, 1, 2) 19 | dateRange = pd.date_range(begdate, periods=n) 20 | def makeDataFrame(): 21 | data=pd.DataFrame(np.random.randn(n,7),columns=['A','B','C','D','E',' F','G'], 22 | index=dateRange) 23 | return data 24 | # 25 | data = { 'A': makeDataFrame(), 'B': makeDataFrame(), 'C': makeDataFrame() } 26 | Y = makeDataFrame() 27 | print(pd.fama_macbeth(y=Y,x=data)) 28 | -------------------------------------------------------------------------------- /Chapter08/c8_44_Amihud_IBM_WMT.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c8_44_Amihud_IBM_WMT.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | 12 | import numpy as np 13 | import statsmodels.api as sm 14 | from matplotlib.finance import quotes_historical_yahoo_ochl as getData 15 | begdate=(2013,10,1) 16 | enddate=(2013,10,30) 17 | ticker='IBM' # or WMT 18 | data= getData(ticker, begdate, enddate,asobject=True, adjusted=True) 19 | p=np.array(data.aclose) 20 | dollar_vol=np.array(data.volume*p) 21 | ret=np.array((p[1:] - p[:-1])/p[1:]) 22 | illiq=np.mean(np.divide(abs(ret),dollar_vol[1:])) 23 | print("Aminud illiq for =",ticker,illiq) 24 | 25 | -------------------------------------------------------------------------------- /Chapter08/c8_44_generate_bysinessCyclePkl.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c8_44_generate_businessCycle.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas as pd 12 | x=pd.read_csv("c:/temp/business_cycle.csv",index_col=0,parse_dates=[0]) 13 | y=pd.DataFrame(x.cycle,index=x.index,columns=['CYCLE']) 14 | x.to_pickle("c:/temp/businessCycle.pkl") -------------------------------------------------------------------------------- /Chapter08/c8_44_relative_spread_TORQcq.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c8_44_relative_spread_TORQcq.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | 12 | import pandas as pd 13 | import scipy as sp 14 | cq=pd.read_pickle('c:/temp/TORQcq.pkl') 15 | x=cq[cq.index=='MO'] 16 | spread=sp.mean(x.ofr-x.bid) 17 | rel_spread=sp.mean(2*(x.ofr-x.bid)/(x.ofr+x.bid)) 18 | print(round(spread,5) ) 19 | print(round(rel_spread,5) ) 20 | -------------------------------------------------------------------------------- /Chapter08/c8_45_read_crspInfo.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c8_45_crspInfo.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas as pd 12 | x=pd.read_pickle("c:/temp/crspInfo.pkl") 13 | print(x.head(3)) 14 | print(x.tail(2)) 15 | -------------------------------------------------------------------------------- /Chapter08/c8_46_print_indexMonthly_CRSP.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | x=pd.read_pickle("c:/temp/indexMonthly.pkl") 3 | print(x.head()) 4 | -------------------------------------------------------------------------------- /Chapter08/c8_55_merge_business_GDP.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c8_55_merge_business_GDP.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | import datetime 11 | import scipy as sp 12 | import numpy as np 13 | import pandas as pd 14 | import pandas_datareader.data as web 15 | # 16 | cycle=pd.read_pickle("c:/temp/businessCycle.pkl") 17 | begdate = datetime.datetime(1947, 1, 1) 18 | enddate = datetime.datetime(2017, 1, 27) 19 | GDP= web.DataReader("GDP", "fred", begdate,enddate) 20 | final=pd.merge(cycle,GDP,left_index=True,right_index=True,how='right') 21 | print(cycle.head()) 22 | print(GDP.head()) 23 | print(final.head()) 24 | 25 | final2=final[np.isnan(final.cycle)!=True] 26 | print(sp.corrcoef(final2.cycle,final2.GDP)) 27 | 28 | -------------------------------------------------------------------------------- /Chapter08/c8_55_rolling_max_decapitted_.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | import scipy as sp 3 | x=sp.arange(1,1000) 4 | 5 | y=pd.rolling_max(x,5) 6 | -------------------------------------------------------------------------------- /Chapter08/c8_99_01_generate_ffDaily_txt.py: -------------------------------------------------------------------------------- 1 | # generate ff_monthly.pickle 2 | 3 | import pandas as pd 4 | import scipy as sp 5 | import numpy as np 6 | file=open("c:/temp/ffDaily.txt","r") 7 | data=file.readlines() 8 | f=[] 9 | dd=[] 10 | for i in range(5,sp.size(data)): 11 | t=data[i].split() 12 | dd.append(pd.to_datetime(t[0], format='%Y%m%d').date()) 13 | for j in range(1,5): 14 | k=float(t[j]) 15 | f.append(k/100) 16 | n=len(f) 17 | f1=np.reshape(f,[n/4,4]) 18 | ff=pd.DataFrame(f1,index=dd,columns=['MKT_RF','SMB','HML','RF']) 19 | ff.to_pickle("c:/temp/ffDaily.pkl") 20 | 21 | -------------------------------------------------------------------------------- /Chapter08/c8_99_03_generate_crspInfo_pickle.py: -------------------------------------------------------------------------------- 1 | """ 2 | 10000 7952 68391610 OPTIMUM MANUFACTURING INC OMFGA 3 19860131-19870630 3 | 10001 7953 36720410 GAS NATURAL INC EGAS 2 19860131-20151231 4 | 10002 7954 05978R10 BANCTRUST FINANCIAL GROUP INC BTFG 3 19860131-20130228 5 | 10003 7957 39031810 GREAT COUNTRY BK ASONIA CT GCBK 3 19860131-19951229 6 | 7 | """ 8 | 9 | import pandas as pd 10 | infile="c:/temp/cheadfile.dat" 11 | fwidths = [7,6,8,33,5,3,9,1,9] 12 | df = pd.read_fwf(infile, widths=fwidths) 13 | #print(df.head(2)) 14 | 15 | crspInfo=pd.DataFrame(df) 16 | 17 | crspInfo.columns=['PERMNO','PERMCO','CUSIP','FIRMNAME','TICKER','EXCHANGE','BEGDATE','D','ENDDATE'] 18 | 19 | del crspInfo['D'] 20 | 21 | 22 | #crspInfo=pd.DataFrame(df,columns=['PERMNO','PERMCO','CUSIP','NAME','TICKER','EX','BEGDATE','D','ENDDATE']) 23 | crspInfo.to_pickle("c:/temp/crspInfo.pkl") 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /Chapter08/c8_99_04_generate_indexMonthly_pickle.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | x=pd.read_csv("c:/temp/indexMonthly2.csv") 3 | 4 | x.columns=(['DATE','VWRETD', 'VWRETX', 'EWRETD', 'EWRETX','SP500RET','SP500INDEX','TOTALVAL','TOTALN','USEDVAL', 'USEDN']) 5 | x.to_pickle("c:/temp/indexMonthly.pkl") 6 | -------------------------------------------------------------------------------- /Chapter08/c8_99_08_generate_tradingDays.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | 3 | x=pd.read_table("c:/temp/tradingDaysMonthly.txt") 4 | 5 | x.to_pickle("c:/temp/tradingDaysMonthly.pkl") 6 | 7 | 8 | a=pd.read_table("c:/temp/tradingDaysDaily.txt") 9 | 10 | a.to_pickle("c:/temp/tradingDaysDaily.pkl") -------------------------------------------------------------------------------- /Chapter08/c8_generate_critical_F_values_Table.py: -------------------------------------------------------------------------------- 1 | import scipy.stats 2 | import scipy as sp 3 | import pandas as pd 4 | 5 | alpha=0.05 6 | output=[] 7 | for i in sp.arange(1,36): 8 | dfDenominator=i 9 | for j in sp.arange(1,11): 10 | dfNumerator=j 11 | f=scipy.stats.f.ppf(q=1-alpha, dfn=dfNumerator, dfd=dfDenominator) 12 | output.append(round(f,2)) 13 | #print(f) 14 | 15 | n=sp.size(output) 16 | out=sp.reshape(output,[n/10,10]) 17 | rowNames=list(range(1,36)) 18 | #index=list(range(1,36)) 19 | out2=pd.DataFrame(out,index=rowNames,columns=[1,2,3,4,5,6,7,8,9,10]) 20 | 21 | 22 | # output to screen 23 | import sys 24 | out2.to_csv(sys.stdout) 25 | 26 | 27 | 28 | 29 | 30 | #out2=round(out,2) 31 | 32 | #old_names = ['$a', '$b', '$c', '$d', '$e'] 33 | #new_names = ['a', 'b', 'c', 'd', 'e'] 34 | #df.rename(columns=dict(zip(old_names, new_names)), inplace=True) 35 | 36 | #oldNames=out2.columns 37 | #newNames=sp.arange(1,11) 38 | #out2=out2.rename(columns=dict(zip(oldNames,newNames)),inplace=True) -------------------------------------------------------------------------------- /Chapter09/c9_01_optimize.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c9_01_optimize.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | from scipy.optimize import minimize 12 | def myFunction(x): 13 | return (3.2+5*x**2) 14 | 15 | x0=100 16 | res = minimize(myFunction,x0,method='nelder-mead',options={'xtol':1e-8,'disp': True}) 17 | 18 | -------------------------------------------------------------------------------- /Chapter09/c9_02_graph_y_x.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c9_02_graph_y_x.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | 12 | import scipy as sp 13 | import matplotlib.pyplot as plt 14 | x=sp.arange(-5,5,0.01) 15 | a=3.2 16 | b=5.0 17 | y=a+b*x**2 18 | plt.plot(x,y) 19 | plt.title("y= "+str(a)+"+"+str(b)+"x^2") 20 | plt.ylabel("y") 21 | plt.xlabel("x") 22 | plt.show() -------------------------------------------------------------------------------- /Chapter09/c9_02_matrix.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c9_02_matrix.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import numpy as np 12 | ret=np.matrix(np.array([[0.1,0.2],[0.10,0.1071],[-0.02,0.25],[0.012,0.028],[0.06,0.262],[0.14,0.115]])) 13 | print("return matrix") 14 | print(ret) 15 | covar=ret.T*ret 16 | print("covar") 17 | print(covar) 18 | weight=np.matrix(np.array([0.4,0.6])) 19 | print("weight ") 20 | print(weight) 21 | print("mean return") 22 | print(weight*covar*weight.T) 23 | -------------------------------------------------------------------------------- /Chapter09/c9_032_matrix_multiplication.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c9_32_matrix_multiplication.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import numpy as np 12 | ret=np.matrix(np.array([[0.1,0.2],[0.10,0.1071],[-0.02,0.25],[0.012,0.028],[0.06,0.262],[0.14,0.115]])) 13 | covar=np.dot(ret.T,ret) 14 | print("covar") 15 | print(covar) 16 | -------------------------------------------------------------------------------- /Chapter09/c9_03_graph_another_pair_y_x.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c9_03_graph_anoterh_pari_y_x.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import scipy as sp 12 | import matplotlib.pyplot as plt 13 | x=sp.arange(-5,5,0.01) 14 | y=3.4-2*sp.exp(-(x-0.8)**2) 15 | plt.plot(x,y) 16 | plt.title("y= 3.4 -2exp(-(x-0.5)^2)") 17 | plt.ylabel("y") 18 | plt.xlabel("x") 19 | plt.show() -------------------------------------------------------------------------------- /Chapter09/c9_03_optimization.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c9_03_optimization.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import numpy as np 12 | from scipy import optimize 13 | import matplotlib.pyplot as plt 14 | # 15 | # define a function 16 | def f(x): 17 | return 3.4-2*np.exp(-(x - 0.8)**2) 18 | # 19 | # see the plot 20 | x=np.arange(-3,3,0.1) 21 | y=f(x) 22 | plt.plot(x,y) 23 | plt.show() 24 | 25 | # find the miniumu 26 | solution= optimize.brent(f) 27 | print(solution) 28 | 29 | -------------------------------------------------------------------------------- /Chapter09/c9_04_solution_x1_x2_for_quatradic_form.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c9_04_solution_x1_x2_for_quatradic_form.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | 12 | import scipy as sp 13 | a=1 14 | b=6 15 | c=3 16 | 17 | inside=b**2-4*a*c 18 | 19 | if inside>0: 20 | squared=sp.sqrt(inside) 21 | print("x1=",(b+squared)/(2*a)) 22 | print("x2=",(b-squared)/(2*a)) 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /Chapter09/c9_06_find_weight_2stock_portfolio.p: -------------------------------------------------------------------------------- 1 | import scipy as sp 2 | 3 | var1=0.016 4 | var2=0.027 5 | 6 | sigma1=sp.sqrt(var1) 7 | sigma2=sp.sqrt(var2) 8 | rho=-1 9 | n=1000 10 | portVar=10 # assign a big number 11 | tiny=1.0/n 12 | 13 | for i in sp.arange(n): 14 | w1=i*tiny 15 | w2=1-w1 16 | var=w1**2*var1 +w2**2*var2**2+2*w1*w2*rho*sigma1*sigma2 17 | if(var target: 21 | my_max = mid - 1 22 | else: 23 | return mid 24 | raise ValueError 25 | 26 | -------------------------------------------------------------------------------- /Chapter10/c10_35_put_call_ratio.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c10_35_put_call_ratio.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | import scipy as sp 11 | import pandas as pd 12 | from matplotlib.pyplot import * 13 | # 14 | infile='c:/temp/totalpc.csv' 15 | data=pd.read_csv(infile,skiprows=2,index_col=0,parse_dates=True) 16 | data.columns=('Calls','Puts','Total','Ratio') 17 | x=data.index 18 | y=data.Ratio 19 | y2=sp.ones(len(y)) 20 | title('Put-call ratio') 21 | xlabel('Date') 22 | ylabel('Put-call ratio') 23 | ylim(0,1.5) 24 | plot(x, y, 'b-') 25 | plot(x, y2,'r') 26 | show() -------------------------------------------------------------------------------- /Chapter10/c10_38_greeks.py: -------------------------------------------------------------------------------- 1 | # estimate delta, gamma, theta, veta 2 | """ 3 | Name : c10_39_greeks.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | from scipy import log,exp,sqrt,stats 13 | # 14 | tiny=1e-9 15 | S=40 16 | X=40 17 | T=0.5 18 | r=0.01 19 | sigma=0.2 20 | 21 | def bsCall(S,X,T,r,sigma): 22 | d1=(log(S/X)+(r+sigma*sigma/2.)*T)/(sigma*sqrt(T)) 23 | d2 = d1-sigma*sqrt(T) 24 | return S*stats.norm.cdf(d1)-X*exp(-r*T)*stats.norm.cdf(d2) 25 | 26 | def delta1(S,X,T,r,sigma): 27 | d1=(log(S/X)+(r+sigma*sigma/2.)*T)/(sigma*sqrt(T)) 28 | return stats.norm.cdf(d1) 29 | 30 | def delta2(S,X,T,r,sigma): 31 | s1=S 32 | s2=S+tiny 33 | c1=bsCall(s1,X,T,r,sigma) 34 | c2=bsCall(s2,X,T,r,sigma) 35 | delta=(c2-c1)/(s2-s1) 36 | return delta 37 | 38 | print("delta (close form)=", delta1(S,X,T,r,sigma)) 39 | print("delta (tiny number)=", delta2(S,X,T,r,sigma)) 40 | -------------------------------------------------------------------------------- /Chapter10/c10_40_data_case.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c10_40_datacase.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas as pd 12 | x=pd.read_pickle("c:/temp/businessCycle.pkl") 13 | print(x.head()) 14 | print(x.tail()) -------------------------------------------------------------------------------- /Chapter10/c10_42_binomialCallEuropean.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c10_42_binomialEuropeanCall.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | from math import exp,sqrt 13 | import scipy as sp 14 | def binomialCall(s,x,T,r,sigma,n=100): 15 | deltaT = T /n 16 | u = exp(sigma * sqrt(deltaT)) 17 | d = 1.0 / u 18 | a = exp(r * deltaT) 19 | p = (a - d) / (u - d) 20 | v = [[0.0 for j in sp.arange(i + 1)] for i in sp.arange(n + 1)] 21 | for j in sp.arange(n+1): 22 | v[n][j] = max(s * u**j * d**(n - j) - x, 0.0) 23 | for i in sp.arange(n-1, -1, -1): 24 | for j in sp.arange(i + 1): 25 | v[i][j]=exp(-r*deltaT)*(p*v[i+1][j+1]+(1.0-p)*v[i+1][j]) 26 | return v[0][0] 27 | 28 | -------------------------------------------------------------------------------- /Chapter10/c10_43_EW_port.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c10_43_EW_port.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | import numpy as np 13 | 14 | ret_A=np.array([0.102,-0.02, 0.213,0.12,0.13]) 15 | ret_B=np.array([0.1062,0.23, 0.045,0.234,0.113]) 16 | 17 | port_EW=(ret_A+ret_B)/2 18 | 19 | round(np.mean(ret_A),3),round(np.mean(ret_B),3),round(np.mean(port_EW),3) 20 | 21 | round(np.std(ret_A),3),round(np.std(ret_B),3),round(np.std(port_EW),3) 22 | -------------------------------------------------------------------------------- /Chapter11/c11_01_normal_density_function.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c11_01_normal_density_function.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import scipy.stats as stats 12 | from scipy import sqrt, exp,pi 13 | d1=stats.norm.pdf(0,0.1,0.05) 14 | print("d1=",d1) 15 | d2=1/sqrt(2*pi*0.05**2)*exp(-(0.1)**2/0.05**2/2) # verify manually 16 | print("d2=",d2) 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /Chapter11/c11_02_normal_distribution.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c11_02_normal_distribution.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import scipy as sp 12 | import matplotlib.pyplot as plt 13 | x = sp.arange(-3,3,0.1) 14 | y=sp.stats.norm.pdf(x) 15 | plt.title("Standard Normal Distribution") 16 | plt.xlabel("X") 17 | plt.ylabel("Y") 18 | plt.plot(x,y) 19 | plt.show() 20 | -------------------------------------------------------------------------------- /Chapter11/c11_03_standard_normal_dis.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c11_03_standard_normal_dist.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | import scipy as sp 11 | import scipy.stats as stats 12 | x = sp.arange(-3,3,0.01) 13 | ret=stats.norm.pdf(x) 14 | confidence=0.99 15 | position=10000 16 | z=stats.norm.ppf(1-confidence) 17 | print("z=",z) 18 | zES=-stats.norm.pdf(z)/(1-confidence) 19 | print("zES=", zES) 20 | std=sp.std(ret) 21 | VaR=position*z*std 22 | print("VaR=",VaR) 23 | ES=position*zES*std 24 | print("ES=",ES) 25 | 26 | 27 | -------------------------------------------------------------------------------- /Chapter11/c11_04_show_z_negative.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c11_04_show_z_genative.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | from scipy.stats import norm 12 | confidence_level=0.99 13 | z=norm.ppf(1-confidence_level) 14 | print(z) 15 | -------------------------------------------------------------------------------- /Chapter11/c11_07_VaR_500shares_IBM_tomorrow.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c11_07_VaR_500shares_IBM_tomorrow.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import numpy as np 12 | import pandas as pd 13 | from scipy.stats import norm 14 | from matplotlib.finance import quotes_historical_yahoo_ochl as getData 15 | # 16 | # input area 17 | ticker='IBM' # input 1 18 | n_shares=1000 # input 2 19 | confidence_level=0.99 # input 3 20 | begdate=(2012,2,7) # input 4 21 | enddate=(2017,2,7) # input 5 22 | # 23 | z=norm.ppf(1-confidence_level) 24 | x=getData(ticker,begdate,enddate,asobject=True,adjusted=True) 25 | print(x[0]) 26 | ret = x.aclose[1:]/x.aclose[:-1]-1 27 | # 28 | position=n_shares*x.close[0] 29 | std=np.std(ret) 30 | # 31 | VaR=position*z*std 32 | print("Holding=",position, "VaR=", round(VaR,4), "tomorrow") 33 | 34 | 35 | 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /Chapter11/c11_09_normaility_test_msft.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c11_09_normality_test_MSFT.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import numpy as np 12 | from scipy import stats 13 | from matplotlib.finance import quotes_historical_yahoo_ochl as getData 14 | # 15 | ticker='MSFT' 16 | begdate=(2012,1,1) 17 | enddate=(2016,12,31) 18 | # 19 | p =getData(ticker, begdate, enddate,asobject=True, adjusted=True) 20 | ret = (p.aclose[1:] - p.aclose[:-1])/p.aclose[1:] 21 | print 'ticker=',ticker,'W-test, and P-value' 22 | print(stats.shapiro(ret)) 23 | print( stats.anderson(ret)) 24 | 25 | -------------------------------------------------------------------------------- /Chapter11/c11_10_normality_test.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c11_10_normality_test.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import numpy as np 12 | from scipy import stats 13 | from matplotlib.finance import quotes_historical_yahoo_ochl as getData 14 | # 15 | ticker='IBM' 16 | begdate=(2012,1,1) 17 | enddate=(2016,12,31) 18 | # 19 | p =getData(ticker, begdate, enddate,asobject=True, adjusted=True) 20 | ret = (p.aclose[1:] - p.aclose[:-1])/p.aclose[1:] 21 | print 'ticker=',ticker,'W-test, and P-value' 22 | print(stats.shapiro(ret)) 23 | print( stats.anderson(ret) ) -------------------------------------------------------------------------------- /Chapter11/c11_11_normality_test_for_sp500.py: -------------------------------------------------------------------------------- 1 | 2 | """ 3 | Name : c11_11_normality_test_for_SP500.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | import numpy as np 12 | from scipy import stats 13 | from matplotlib.finance import quotes_historical_yahoo_ochl as getData 14 | # 15 | ticker='^GSPC' # ^GSPC is for S&P500 16 | begdate=(2012,1,1) 17 | enddate=(2016,12,31) 18 | # 19 | p =getData(ticker, begdate, enddate,asobject=True, adjusted=True) 20 | ret = (p.aclose[1:] - p.aclose[:-1])/p.aclose[1:] 21 | print 'ticker=',ticker,'W-test, and P-value' 22 | print(stats.shapiro(ret)) 23 | print( stats.anderson(ret) ) 24 | -------------------------------------------------------------------------------- /Chapter11/c11_12_normal_random.py: -------------------------------------------------------------------------------- 1 | 2 | """ 3 | Name : c11_12_normal_random.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | import numpy as np 12 | from scipy import stats,random 13 | # 14 | np.random.seed(12345) 15 | n=5000000 16 | 17 | ret = random.normal(0,1,n) 18 | print('mean =', np.mean(ret)) 19 | print('std =',np.std(ret)) 20 | print('skewness=',stats.skew(ret)) 21 | print('kurtosis=',stats.kurtosis(ret)) 22 | -------------------------------------------------------------------------------- /Chapter11/c11_13_sort_nparray.py: -------------------------------------------------------------------------------- 1 | 2 | """ 3 | Name : c11_13_sor_nparray.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | import numpy as np 12 | a = np.array([[1,-4],[9,10]]) 13 | b=np.sort(a) 14 | 15 | print("a=",a) 16 | print("b=",b) -------------------------------------------------------------------------------- /Chapter11/c11_14_VaR_500shares_WMT.py: -------------------------------------------------------------------------------- 1 | 2 | """ 3 | Name : c11_14_VaR_500shares_WMT.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | import numpy as np 12 | import pandas as pd 13 | from scipy.stats import norm 14 | from matplotlib.finance import quotes_historical_yahoo_ochl as getData 15 | # 16 | ticker='WMT' # input 1 17 | n_shares=500 # input 2 18 | confidence_level=0.99 # input 3 19 | begdate=(2012,1,1) # input 5 20 | enddate=(2016,12,31) # input 6 21 | # 22 | z=norm.ppf(confidence_level) 23 | x=getData(ticker,begdate,enddate,asobject=True,adjusted=True) 24 | ret = x.aclose[1:]/x.aclose[:-1]-1 25 | # 26 | position=n_shares*x.close[0] 27 | std=np.std(ret) 28 | # 29 | VaR=position*z*std 30 | print("Holding=",position, "VaR=", round(VaR,4), "tomorrow") 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /Chapter11/c11_18_sort_pandas.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | """ 4 | Name : c11_18_sort_pandas.py 5 | Book : Python for Finance (2nd ed.) 6 | Publisher: Packt Publishing Ltd. 7 | Author : Yuxing Yan 8 | Date : 6/6/2017 9 | email : yany@canisius.edu 10 | paulyxy@hotmail.com 11 | """ 12 | 13 | import pandas as pd 14 | a = pd.DataFrame([[9,4],[9,2],[1,-1]],columns=['A','B']) 15 | print(a) 16 | # sort by A ascedning, then B descending 17 | b= a.sort_values(['A', 'B'], ascending=[1, 0]) 18 | print(b) 19 | # sort by A and B, both ascedning 20 | c= a.sort_values(['A', 'B'], ascending=[1, 1]) 21 | print(c) -------------------------------------------------------------------------------- /Chapter11/c11_20_VaR_for_5industry_portfolo_ff.py: -------------------------------------------------------------------------------- 1 | 2 | """ 3 | Name : c11_20_VaR_for_5_industry_portfolio.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | import scipy as sp 12 | import pandas as pd 13 | from scipy.stats import norm 14 | 15 | confidence_level=0.99 # input 3 16 | z=norm.ppf(confidence_level) 17 | position=(1,1,1,1,1) 18 | 19 | x=pd.read_pickle("c:/temp/ff5VWindustryMonthly.pkl") 20 | #print(x.head(1)) 21 | mean=sp.mean(x,axis=0) 22 | std=sp.std(x,axis=0) 23 | 24 | t=sp.dot(position,z) 25 | VaR=t*std 26 | print("VaR=",VaR) 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /Chapter11/c11_21_ES_z_value_normal_distribution.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c11_21_ES_z_value_normal_distribution.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import scipy as sp 12 | sp.random.seed(12345) 13 | n=5000000 14 | ret=sp.random.normal(0,1,n) 15 | print(ret[0:5] ) 16 | 17 | 18 | -------------------------------------------------------------------------------- /Chapter11/c11_24_01_generate_ff5VWindustry_49.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | import scipy as sp 3 | #x=pd.read_csv("c:/temp/ff49VWindustryMonthly.csv",skiprows=11,index_col=0) 4 | #x.to_pickle("c:/temp/ff49VWindustryMonthly.pkl") 5 | 6 | x=pd.read_csv("c:/temp/ff5VWindustryMonthly.csv",skiprows=11,index_col=0) 7 | x2=x/100.0 8 | x2.columns = [x.upper() for x in x2.columns] 9 | x2.to_pickle("c:/temp/ff5VWindustryMonthly.pkl") -------------------------------------------------------------------------------- /Chapter12/c12_01_10random_numbers.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c12_01_randard.standard_normal.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import scipy as sp 12 | x=sp.random.standard_normal(size=10) 13 | print(x) -------------------------------------------------------------------------------- /Chapter12/c12_03_graph_standard_normal_dist.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c12_02_graph_standard_noral_dist.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import scipy as sp 12 | import scipy.stats as stats 13 | import matplotlib.pyplot as plt 14 | x = sp.arange(-3,3,0.01) 15 | y=stats.norm.pdf(x) 16 | plt.plot(x,y) 17 | plt.title("A standard normal distribution") 18 | plt.xlabel('x') 19 | plt.ylabel('y') 20 | plt.show() 21 | 22 | 23 | -------------------------------------------------------------------------------- /Chapter12/c12_04_histogram.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c12_03_histogram.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import scipy as sp 12 | import matplotlib.pyplot as plt 13 | # 14 | sp.random.seed(12345) 15 | mean=0.1 16 | std=0.2 17 | n=1000 18 | x=sp.random.normal(mean,std,n) 19 | plt.hist(x, 15, normed=True) 20 | plt.title("Histogram for random numbers drawn from a normal distribution") 21 | plt.annotate("mean="+str(mean),xy=(0.6,1.5)) 22 | plt.annotate("std="+str(std),xy=(0.6,1.4)) 23 | plt.show() 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /Chapter12/c12_05_lognormal_graphs.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c12_05_lognormal_graphs.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import scipy as sp 12 | import numpy as np 13 | import matplotlib.pyplot as plt 14 | from scipy import sqrt,exp,log,pi 15 | # 16 | x=np.linspace(0.001,3,200) 17 | mu=0 18 | sigma0=[0.25,0.5,1] 19 | color=['blue','red','green'] 20 | target=[(1.2,1.3),(1.7,0.4),(0.18,0.7)] 21 | start=[(1.8,1.4),(1.9,0.6),(0.18,1.6)] 22 | # 23 | for i in sp.arange(len(sigma0)): 24 | sigma=sigma0[i] 25 | y=1/(x*sigma*sqrt(2*pi))*exp(-(log(x)-mu)**2/(2*sigma*sigma)) 26 | plt.annotate('mu='+str(mu)+', sigma='+str(sigma),xy=target[i],xytext=start[i],arrowprops=dict(facecolor=color[i],shrink=0.01),) 27 | plt.plot(x,y,color[i]) 28 | plt.title('Lognormal distribution') 29 | plt.xlabel('x') 30 | plt.ylabel('lognormal density distribution') 31 | # 32 | plt.show() 33 | -------------------------------------------------------------------------------- /Chapter12/c12_06_random_number_with_seed.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c12_06_randard_numbers_with_seed.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import scipy as sp 12 | sp.random.seed(12345) 13 | x=sp.random.normal(0,1,20) 14 | print x[0:5] 15 | -------------------------------------------------------------------------------- /Chapter12/c12_07_normal_dist.py: -------------------------------------------------------------------------------- 1 | 2 | """ 3 | Name : c12_07_normal_dist.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | import scipy as sp 13 | sp.random.seed(12345) 14 | mean=0.05 15 | std=0.1 16 | n=50 17 | x=sp.random.normal(mean,std,n) 18 | print(x[0:5]) 19 | 20 | 21 | -------------------------------------------------------------------------------- /Chapter12/c12_08_uniform_dist.py: -------------------------------------------------------------------------------- 1 | 2 | """ 3 | Name : c12_08_uniform_dist.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | import scipy as sp 13 | sp.random.seed(123345) 14 | x=sp.random.uniform(low=1,high=100,size=10) 15 | print(x[0:5]) 16 | -------------------------------------------------------------------------------- /Chapter12/c12_09_roll_a_dice.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c12_09_roll_a_dice.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import random 12 | def rollDice(): 13 | roll = random.randint(1,6) 14 | return roll 15 | i =1 16 | n=10 17 | result=[] 18 | random.seed(123) 19 | while i